-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathetcgendex
More file actions
227 lines (205 loc) · 8.94 KB
/
Copy pathetcgendex
File metadata and controls
227 lines (205 loc) · 8.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
#!/usr/bin/env python3
# gendex_lsF.py — terminal-style index (ls -F) with LS_COLORS, column-major layout
# @spiralbend 2025-09-10
import os
import stat
import argparse
import datetime
from pathlib import Path
# --- LS_COLORS support ----------------------------------------------------
FG = {30:"black",31:"red",32:"green",33:"yellow",34:"dodgerblue",35:"magenta",36:"cyan",37:"white"}
BG = {code+10: color for code, color in FG.items()}
skipped = 0
def parse_ls_colors():
raw = os.getenv("LS_COLORS", "")
cmap = {}
for part in raw.split(":"):
if "=" not in part: continue
key, val = part.split("=", 1)
codes = [int(x) for x in val.split(";") if x.isdigit()]
styles = []
for c in codes:
if c == 1: styles.append("font-weight:bold")
elif c == 4: styles.append("text-decoration:underline")
elif c in FG: styles.append(f"color:{FG[c]}")
elif c in BG: styles.append(f"background-color:{BG[c]}")
if styles: cmap[key] = ";".join(styles)
return cmap
LS_COLOR_MAP = parse_ls_colors()
def color_style(st_mode, full_path):
if stat.S_ISDIR(st_mode): key = "di"
elif stat.S_ISLNK(st_mode): key = "ln"
elif stat.S_ISFIFO(st_mode): key = "pi"
elif stat.S_ISSOCK(st_mode): key = "so"
elif stat.S_ISBLK(st_mode): key = "bd"
elif stat.S_ISCHR(st_mode): key = "cd"
else: key = "ex" if os.access(full_path, os.X_OK) else "fi"
if key in LS_COLOR_MAP: return LS_COLOR_MAP[key]
name = full_path.lower()
for pat, style in sorted(LS_COLOR_MAP.items(), key=lambda x: -len(x[0])):
if pat.startswith("*.") and name.endswith(pat[1:].lower()):
return style
return ""
def classify_suffix(st_mode, is_dir, full_path):
if is_dir: return "/"
if stat.S_ISLNK(st_mode): return "@"
if stat.S_ISFIFO(st_mode): return "|"
if stat.S_ISSOCK(st_mode): return "="
if os.access(full_path, os.X_OK): return "*"
return ""
# ---------------------------------------------------------------------------
TEMPLATE = """<!DOCTYPE html>
<html>
<head>
<link rel="icon" type="image/x-icon" href="/favicon.ico?v=2">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Index of /{path}</title>
<style>
html,body,pre,span,a {{ background-color:black!important; font-size:12pt; }}
@media (max-width: 500px) {{ html,body,pre,span,a {{ font-size:8pt; }} }}
body {{ margin:0; padding:0; color:lime; font-family:monospace; margin-left:0.5cm; }}
a {{ color:lime; text-decoration:none; }}
a:hover {{ text-decoration:underline; }}
.prompt {{ color:orange }}
.dir {{ color:white }}
.cursor {{ display:inline-block; animation: blink 1s steps(1) infinite; }}
@keyframes blink {{ 50% {{ opacity:0; }} }}
/* Listing container; JS will set columns; keep items tight like terminal */
#grid {{ display:grid; grid-auto-rows:min-content; align-items:start; column-gap:2ch; row-gap:0.2em; }}
.item {{ white-space:pre; }}
</style>
</head>
<body onload="boot()">
<!-- ::spiralbend:: autogenerated index -->
<script>
function formatLinuxDate(date=new Date()) {{
const days=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
const months=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
const d=date, dayName=days[d.getDay()], monthName=months[d.getMonth()];
const day=String(d.getDate()).padStart(2,' ');
const hh=String(d.getHours()).padStart(2,'0');
const mm=String(d.getMinutes()).padStart(2,'0');
const ss=String(d.getSeconds()).padStart(2,'0');
const tz=new Intl.DateTimeFormat('en-US',{{timeZoneName:'short'}}).formatToParts(d).find(p=>p.type==='timeZoneName').value;
return `${{dayName}} ${{monthName}} ${{day}} ${{hh}}:${{mm}}:${{ss}} ${{tz}} ${{d.getFullYear()}}`;
}}
function chWidth(el) {{
const t=document.createElement('span');
t.textContent='0'.repeat(100);
t.style.visibility='hidden'; t.style.position='absolute'; t.style.whiteSpace='pre';
el.appendChild(t);
const w=t.getBoundingClientRect().width/100;
t.remove(); return w;
}}
function columnMajorReorder(nodes, cols) {{
const items=[...nodes];
const rows=Math.ceil(items.length/cols);
const ordered=[];
for (let r=0;r<rows;r++) {{
for (let c=0;c<cols;c++) {{
const idx=c*rows + r;
if (items[idx]) ordered.push(items[idx]);
}}
}}
return ordered;
}}
function layout() {{
const grid=document.getElementById('grid');
if (!grid) return;
const items=[...grid.children];
if (items.length===0) return;
const maxLen=Math.max(...items.map(n=>parseInt(n.dataset.len||'0',10)));
const cw=chWidth(grid);
const cols=Math.max(1, Math.floor(grid.clientWidth / ((maxLen+2)*cw)));
grid.style.gridTemplateColumns=`repeat(${{cols}}, max-content)`;
const ordered=columnMajorReorder(items, cols);
grid.innerHTML='';
ordered.forEach(n=>grid.appendChild(n));
}}
function boot() {{
document.getElementById('theDate').textContent=formatLinuxDate();
layout();
addEventListener('resize', ()=>layout());
}}
</script>
<pre>
<span class="prompt">𝜟<span class="dir"><span style="letter-spacing:-0.5ch;"> </span>{dir}</span>·</span> ls -F
<div id="grid">
{items}
</div>
<span class="prompt">𝜟<span class="dir"><span style="letter-spacing:-0.5ch;"> </span>{dir}</span>·</span> date<br><span id="theDate"></span>
<span class="prompt">𝜟<span class="dir"><span style="letter-spacing:-0.5ch;"> </span>{dir}</span>·</span> <span class="cursor"><b>_</b></span>
</pre>
</body>
</html>
"""
TOKEN = "::spiralbend:: autogenerated index"
def make_item(name, href, full_path, st_mode):
style = color_style(st_mode, full_path)
style_attr = f' style="{style}"' if style else ""
disp = name
return f'<span class="item" data-len="{len(disp)}"><a href="{href}"{style_attr}>{disp}</a></span>'
def build_index(dirpath, rel_dir, dirnames, filenames, include_dotfiles):
items = []
# parent link first
rel_parent = os.path.relpath(os.path.join(dirpath, ".."), dirpath)
parent_full = os.path.join(dirpath, "..")
items.append(make_item("..", rel_parent, parent_full, os.lstat(parent_full).st_mode))
all_entries = sorted(dirnames + filenames, key=str.lower)
all_entries = [n for n in all_entries if n.lower() != "index.html"]
for name in all_entries:
if not include_dotfiles and name.startswith((".", "__")):
continue
full_path = os.path.join(dirpath, name)
try:
st = os.lstat(full_path)
except FileNotFoundError:
continue
is_dir = stat.S_ISDIR(st.st_mode)
suffix = classify_suffix(st.st_mode, is_dir, full_path)
disp = name + suffix
href = f"{name}/" if is_dir else name
items.append(make_item(disp, href, full_path, st.st_mode))
return TEMPLATE.format(
path=rel_dir if rel_dir != "." else "",
dir=Path(rel_dir).name,
items="\n".join(items),
)
def process_dir(root, include_dotfiles=False, verbose=False, no_depth=False):
global skipped
for dirpath, dirnames, filenames in os.walk(root):
if no_depth and os.path.abspath(dirpath) != os.path.abspath(root):
break
rel_dir = os.path.relpath(dirpath, root)
if rel_dir != "." and not include_dotfiles and any(part.startswith((".", "__")) for part in rel_dir.split(os.sep)):
continue
index_path = os.path.join(dirpath, "index.html")
index_exists = os.path.exists(index_path)
html = build_index(dirpath, rel_dir, dirnames, filenames, include_dotfiles)
if index_exists:
try:
with open(index_path, "r") as fh:
content = fh.read()
except Exception as e:
if verbose: print(f"Error reading {index_path}: {e}")
continue
if TOKEN not in content:
if verbose: print(f"Skipping existing index (no token): {index_path}")
continue
if content.strip() == html.strip():
skipped += 1
if verbose: print(f"Skipping unmodified index: {index_path}")
continue
with open(index_path, "w") as fh:
fh.write(html)
print(f"{'Updated' if index_exists else 'Created'} index: {index_path}")
if __name__ == "__main__":
p = argparse.ArgumentParser(description="Generate ls -F style index.html files with LS_COLORS and column layout.")
p.add_argument("root", nargs="?", default=".", help="Root directory (default: .)")
p.add_argument("--include-dotfiles", action="store_true", help="Include dotfiles and dot directories")
p.add_argument("--verbose", action="store_true", help="Print progress while generating indexes")
p.add_argument("--no-depth", action="store_true", help="Only generate index.html in the root directory")
args = p.parse_args()
process_dir(args.root, include_dotfiles=args.include_dotfiles, verbose=args.verbose, no_depth=args.no_depth)
if not args.verbose: print(f"Skipped {skipped} unmodified indexes.")