-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgendex.py
More file actions
executable file
·345 lines (308 loc) · 10.4 KB
/
Copy pathgendex.py
File metadata and controls
executable file
·345 lines (308 loc) · 10.4 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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
#!/usr/bin/env python3
# gendex.py
# @spiralbend 2025-07-29
import os
import stat
import argparse
import datetime
from pathlib import Path
# --- LS_COLORS support ----------------------------------------------------
# ANSI color to CSS color mapping for foreground
FG = {
30: "black",
31: "red",
32: "green",
33: "yellow",
34: "dodgerblue",
35: "magenta",
36: "cyan",
37: "white",
}
# ANSI color to CSS background mapping (40–47)
BG = {code + 10: color for code, color in FG.items()}
skipped = 0
def parse_ls_colors():
"""Parse LS_COLORS env var and return dict of {key: 'css:prop;…'}"""
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 get_color_style(st_mode, full_path):
"""
Determine CSS style from LS_COLOR_MAP based on file type or extension.
"""
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 ""
# ---------------------------------------------------------------------------
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;
}}
pre {{
border: none;
margin: 0;
padding: 0;
color: lime;
white-space: pre;
}}
a {{
color: lime;
text-decoration: none;
}}
a:hover {{
text-decoration: underline;
}}
.cursor {{
display: inline-block;
animation: blink 1s steps(1) infinite;
}}
@keyframes blink {{
50% {{ opacity: 0; }}
}}
.prompt {{
color:orange
}}
.dir {{
color:white
}}
</style>
</head>
<body onload="document.getElementById('theDate').textContent = formatLinuxDate()">
<!-- ::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;
const dayName = days[d.getDay()];
const 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 year = d.getFullYear();
const tz = new Intl.DateTimeFormat('en-US',{{ timeZoneName: 'short' }})
.formatToParts(d)
.find(part => part.type === 'timeZoneName')
.value;
return `${{dayName}} ${{monthName}} ${{day}} ${{hh}}:${{mm}}:${{ss}} ${{tz}} ${{year}}`;
}}
</script>
<pre>
<span class="prompt">𝜟<span class="dir"><span style="letter-spacing:-0.5ch;"> </span>{dir}</span>·</span> ll
total {total_size}
{entries}
<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 human_readable_size(size):
for unit in ["B", "K", "M", "G", "T"]:
if size < 1024.0:
return f"{size:>4.1f}{unit}" if unit != "B" else f"{int(size):>4d}{unit}"
size /= 1024.0
return f"{size:.1f}P"
def get_mode_str(mode):
return stat.filemode(mode) + "."
def classify_suffix(st_mode, is_dir, full_path):
if is_dir:
return "/"
elif stat.S_ISLNK(st_mode):
return "@"
elif stat.S_ISFIFO(st_mode):
return "|"
elif stat.S_ISSOCK(st_mode):
return "="
elif os.access(full_path, os.X_OK):
return "*"
else:
return ""
def format_entry(mode, nlink, size, mtime, name, href, is_dir, full_path):
size_str = human_readable_size(size) if not is_dir else ""
now = datetime.datetime.now()
six_months = datetime.timedelta(days=182)
if mtime < now - six_months or mtime > now + six_months:
date_str = mtime.strftime("%b %e %Y")
else:
date_str = mtime.strftime("%b %e %H:%M")
if name == "..":
date_str = "Jun 26 09:16"
style = get_color_style(os.lstat(full_path).st_mode, full_path)
style_attr = f' style="{style}"' if style else ""
link = f'<a href="{href}"{style_attr}>{name}</a>'
return f"{mode:11} {nlink:>2} {size_str:>6} {date_str} {link}"
def build_index(dirpath, rel_dir, dirnames, filenames, include_dotfiles):
entries = []
total_size = 0
rel_parent = os.path.relpath(os.path.join(dirpath, ".."), dirpath)
parent_full = os.path.join(dirpath, "..")
parent_mtime = datetime.datetime.fromtimestamp(os.lstat(parent_full).st_mtime)
entries.append(
format_entry(
get_mode_str(os.lstat(parent_full).st_mode),
1,
0,
parent_mtime,
"..",
rel_parent,
True,
parent_full,
)
)
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)
display_name = name + suffix
entries.append(
format_entry(
get_mode_str(st.st_mode),
st.st_nlink,
st.st_size,
datetime.datetime.fromtimestamp(st.st_mtime),
display_name,
f"{name}/" if is_dir else name,
is_dir,
full_path,
)
)
if not is_dir:
total_size += st.st_size
return TEMPLATE.format(
path=rel_dir if rel_dir != "." else "",
dir=Path(rel_dir).name,
entries="\n".join(entries),
total_size=human_readable_size(total_size),
)
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, only process the root directory
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__":
parser = argparse.ArgumentParser(
description="Generate terminal-style index.html files for a directory tree."
)
parser.add_argument(
"root", nargs="?", default=".", help="Root directory to start from (default: .)"
)
parser.add_argument(
"--include-dotfiles",
action="store_true",
help="Include dotfiles and dot directories",
)
parser.add_argument(
"--verbose", action="store_true", help="Print progress while generating indexes"
)
parser.add_argument(
"--no-depth",
action="store_true",
help="Only generate index.html in the root directory, no sub‑dirs",
)
args = parser.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.")