- Notifications
You must be signed in to change notification settings - Fork 267
Expand file tree
/
Copy pathrendergit.py
More file actions
Latest commit
520 lines (435 loc) · 17 KB
/
Copy pathrendergit.py
File metadata and controls
520 lines (435 loc) · 17 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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
#!/usr/bin/env python3
"""
Flatten a GitHub repo into a single static HTML page for fast skimming and Ctrl+F.
"""
from __future__ importannotations
importargparse
importhtml
importos
importpathlib
importshutil
importsubprocess
importsys
importtempfile
importwebbrowser
fromdataclassesimportdataclass
fromtypingimportList
# External deps
frompygmentsimporthighlight
frompygments.formattersimportHtmlFormatter
frompygments.lexersimportget_lexer_for_filename, TextLexer
importmarkdown
MAX_DEFAULT_BYTES=50*1024
BINARY_EXTENSIONS= {
".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".svg", ".ico",
".pdf", ".zip", ".tar", ".gz", ".bz2", ".xz", ".7z", ".rar",
".mp3", ".mp4", ".mov", ".avi", ".mkv", ".wav", ".ogg", ".flac",
".ttf", ".otf", ".eot", ".woff", ".woff2",
".so", ".dll", ".dylib", ".class", ".jar", ".exe", ".bin",
}
MARKDOWN_EXTENSIONS= {".md", ".markdown", ".mdown", ".mkd", ".mkdn"}
@dataclass
classRenderDecision:
include: bool
reason: str# "ok" | "binary" | "too_large" | "ignored"
@dataclass
classFileInfo:
path: pathlib.Path# absolute path on disk
rel: str# path relative to repo root (slash-separated)
size: int
decision: RenderDecision
defrun(cmd: List[str], cwd: str|None=None, check: bool=True) ->subprocess.CompletedProcess:
returnsubprocess.run(cmd, cwd=cwd, check=check, text=True, capture_output=True)
defgit_clone(url: str, dst: str) ->None:
run(["git", "clone", "--depth", "1", url, dst])
defgit_head_commit(repo_dir: str) ->str:
try:
cp=run(["git", "rev-parse", "HEAD"], cwd=repo_dir)
returncp.stdout.strip()
exceptException:
return"(unknown)"
defbytes_human(n: int) ->str:
"""Human-readable bytes: 1 decimal for KiB and above, integer for B."""
units= ["B", "KiB", "MiB", "GiB", "TiB"]
f=float(n)
i=0
whilef>=1024.0andi<len(units) -1:
f/=1024.0
i+=1
ifi==0:
returnf"{int(f)}{units[i]}"
else:
returnf"{f:.1f}{units[i]}"
deflooks_binary(path: pathlib.Path) ->bool:
ext=path.suffix.lower()
ifextinBINARY_EXTENSIONS:
returnTrue
try:
withpath.open("rb") asf:
chunk=f.read(8192)
ifb"\x00"inchunk:
returnTrue
# Heuristic: try UTF-8 decode; if it hard-fails, likely binary
try:
chunk.decode("utf-8")
exceptUnicodeDecodeError:
returnTrue
returnFalse
exceptException:
# If unreadable, treat as binary to be safe
returnTrue
defdecide_file(path: pathlib.Path, repo_root: pathlib.Path, max_bytes: int) ->FileInfo:
rel=str(path.relative_to(repo_root)).replace(os.sep, "/")
try:
size=path.stat().st_size
exceptFileNotFoundError:
size=0
# Ignore VCS and build junk
if"/.git/"inf"/{rel}/"orrel.startswith(".git/"):
returnFileInfo(path, rel, size, RenderDecision(False, "ignored"))
ifsize>max_bytes:
returnFileInfo(path, rel, size, RenderDecision(False, "too_large"))
iflooks_binary(path):
returnFileInfo(path, rel, size, RenderDecision(False, "binary"))
returnFileInfo(path, rel, size, RenderDecision(True, "ok"))
defcollect_files(repo_root: pathlib.Path, max_bytes: int) ->List[FileInfo]:
infos: List[FileInfo] = []
forpinsorted(repo_root.rglob("*")):
ifp.is_symlink():
continue
ifp.is_file():
infos.append(decide_file(p, repo_root, max_bytes))
returninfos
defgenerate_tree_fallback(root: pathlib.Path) ->str:
"""Minimal tree-like output if `tree` command is missing."""
lines: List[str] = []
prefix_stack: List[str] = []
defwalk(dir_path: pathlib.Path, prefix: str=""):
entries= [eforeindir_path.iterdir() ife.name!=".git"]
entries.sort(key=lambdae: (note.is_dir(), e.name.lower()))
fori, einenumerate(entries):
last=i==len(entries) -1
branch="└── "iflastelse"├── "
lines.append(prefix+branch+e.name)
ife.is_dir():
extension=" "iflastelse"│ "
walk(e, prefix+extension)
lines.append(root.name)
walk(root)
return"\n".join(lines)
deftry_tree_command(root: pathlib.Path) ->str:
try:
cp=run(["tree", "-a", "."], cwd=str(root))
returncp.stdout
exceptException:
returngenerate_tree_fallback(root)
defread_text(path: pathlib.Path) ->str:
returnpath.read_text(encoding="utf-8", errors="replace")
defrender_markdown_text(md_text: str) ->str:
returnmarkdown.markdown(md_text, extensions=["fenced_code", "tables", "toc"]) # type: ignore
defhighlight_code(text: str, filename: str, formatter: HtmlFormatter) ->str:
try:
lexer=get_lexer_for_filename(filename, stripall=False)
exceptException:
lexer=TextLexer(stripall=False)
returnhighlight(text, lexer, formatter)
defslugify(path_str: str) ->str:
# Simple slug: keep alnum, dash, underscore; replace others with '-'
out= []
forchinpath_str:
ifch.isalnum() orchin {"-", "_"}:
out.append(ch)
else:
out.append("-")
return"".join(out)
defgenerate_cxml_text(infos: List[FileInfo], repo_dir: pathlib.Path) ->str:
"""Generate CXML format text for LLM consumption."""
lines= ["<documents>"]
rendered= [iforiininfosifi.decision.include]
forindex, iinenumerate(rendered, 1):
lines.append(f'<document index="{index}">')
lines.append(f"<source>{i.rel}</source>")
lines.append("<document_content>")
try:
text=read_text(i.path)
lines.append(text)
exceptExceptionase:
lines.append(f"Failed to read: {str(e)}")
lines.append("</document_content>")
lines.append("</document>")
lines.append("</documents>")
return"\n".join(lines)
defbuild_html(repo_url: str, repo_dir: pathlib.Path, head_commit: str, infos: List[FileInfo]) ->str:
formatter=HtmlFormatter(nowrap=False)
pygments_css=formatter.get_style_defs('.highlight')
# Stats
rendered= [iforiininfosifi.decision.include]
skipped_binary= [iforiininfosifi.decision.reason=="binary"]
skipped_large= [iforiininfosifi.decision.reason=="too_large"]
skipped_ignored= [iforiininfosifi.decision.reason=="ignored"]
total_files=len(rendered) +len(skipped_binary) +len(skipped_large) +len(skipped_ignored)
# Directory tree
tree_text=try_tree_command(repo_dir)
# Generate CXML text for LLM view
cxml_text=generate_cxml_text(infos, repo_dir)
# Table of contents
toc_items: List[str] = []
foriinrendered:
anchor=slugify(i.rel)
toc_items.append(
f'<li><a href="#file-{anchor}">{html.escape(i.rel)}</a> '
f'<span class="muted">({bytes_human(i.size)})</span></li>'
)
toc_html="".join(toc_items)
# Render file sections
sections: List[str] = []
foriinrendered:
anchor=slugify(i.rel)
p=i.path
ext=p.suffix.lower()
try:
text=read_text(p)
ifextinMARKDOWN_EXTENSIONS:
body_html=render_markdown_text(text)
else:
code_html=highlight_code(text, i.rel, formatter)
body_html=f'<div class="highlight">{code_html}</div>'
exceptExceptionase:
body_html=f'<pre class="error">Failed to render: {html.escape(str(e))}</pre>'
sections.append(f"""
<section class="file-section" id="file-{anchor}">
<h2>{html.escape(i.rel)} <span class="muted">({bytes_human(i.size)})</span></h2>
<div class="file-body">{body_html}</div>
<div class="back-top"><a href="#top">↑ Back to top</a></div>
</section>
""")
# Skips lists
defrender_skip_list(title: str, items: List[FileInfo]) ->str:
ifnotitems:
return""
lis= [
f"<li><code>{html.escape(i.rel)}</code> "
f"<span class='muted'>({bytes_human(i.size)})</span></li>"
foriinitems
]
return (
f"<details open><summary>{html.escape(title)} ({len(items)})</summary>"
f"<ul class='skip-list'>\n"+"\n".join(lis) +"\n</ul></details>"
)
skipped_html= (
render_skip_list("Skipped binaries", skipped_binary) +
render_skip_list("Skipped large files", skipped_large)
)
# HTML with left sidebar TOC
returnf"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Flattened repo – {html.escape(repo_url)}</title>
<style>
body {{
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, 'Apple Color Emoji','Segoe UI Emoji';
margin: 0; padding: 0; line-height: 1.45;
}}
.container {{ max-width: 1100px; margin: 0 auto; padding: 0 1rem; }}
.meta small {{ color: #666; }}
.counts {{ margin-top: 0.25rem; color: #333; }}
.muted {{ color: #777; font-weight: normal; font-size: 0.9em; }}
/* Layout with sidebar */
.page {{ display: grid; grid-template-columns: 320px minmax(0,1fr); gap: 0; }}
#sidebar {{
position: sticky; top: 0; align-self: start;
height: 100vh; overflow: auto;
border-right: 1px solid #eee; background: #fafbfc;
}}
#sidebar .sidebar-inner {{ padding: 0.75rem; }}
#sidebar h2 {{ margin: 0 0 0.5rem 0; font-size: 1rem; }}
.toc {{ list-style: none; padding-left: 0; margin: 0; overflow-x: auto; }}
.toc li {{ padding: 0.15rem 0; white-space: nowrap; }}
.toc a {{ text-decoration: none; color: #0366d6; display: inline-block; text-decoration: none; }}
.toc a:hover {{ text-decoration: underline; }}
main.container {{ padding-top: 1rem; }}
pre {{ background: #f6f8fa; padding: 0.75rem; overflow: auto; border-radius: 6px; }}
code {{ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono','Courier New', monospace; }}
.highlight {{ overflow-x: auto; }}
.file-section {{ padding: 1rem; border-top: 1px solid #eee; }}
.file-section h2 {{ margin: 0 0 0.5rem 0; font-size: 1.1rem; }}
.file-body {{ margin-bottom: 0.5rem; }}
.back-top {{ font-size: 0.9rem; }}
.skip-list code {{ background: #f6f8fa; padding: 0.1rem 0.3rem; border-radius: 4px; }}
.error {{ color: #b00020; background: #fff3f3; }}
/* Hide duplicate top TOC on wide screens */
.toc-top {{ display: block; }}
@media (min-width: 1000px) {{ .toc-top {{ display: none; }} }}
:target {{ scroll-margin-top: 8px; }}
/* View toggle */
.view-toggle {{
margin: 1rem 0;
display: flex;
gap: 0.5rem;
align-items: center;
}}
.toggle-btn {{
padding: 0.5rem 1rem;
border: 1px solid #d1d9e0;
background: white;
cursor: pointer;
border-radius: 6px;
font-size: 0.9rem;
}}
.toggle-btn.active {{
background: #0366d6;
color: white;
border-color: #0366d6;
}}
.toggle-btn:hover:not(.active) {{
background: #f6f8fa;
}}
/* LLM view */
#llm-view {{ display: none; }}
#llm-text {{
width: 100%;
height: 70vh;
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-size: 0.85em;
border: 1px solid #d1d9e0;
border-radius: 6px;
padding: 1rem;
resize: vertical;
}}
.copy-hint {{
margin-top: 0.5rem;
color: #666;
font-size: 0.9em;
}}
/* Pygments */
{pygments_css}
</style>
</head>
<body>
<a id="top"></a>
<div class="page">
<nav id="sidebar"><div class="sidebar-inner">
<h2>Contents ({len(rendered)})</h2>
<ul class="toc toc-sidebar">
<li><a href="#top">↑ Back to top</a></li>
{toc_html}
</ul>
</div></nav>
<main class="container">
<section>
<div class="meta">
<div><strong>Repository:</strong> <a href="{html.escape(repo_url)}">{html.escape(repo_url)}</a></div>
<small><strong>HEAD commit:</strong> {html.escape(head_commit)}</small>
<div class="counts">
<strong>Total files:</strong> {total_files} · <strong>Rendered:</strong> {len(rendered)} · <strong>Skipped:</strong> {len(skipped_binary) +len(skipped_large) +len(skipped_ignored)}
</div>
</div>
</section>
<div class="view-toggle">
<strong>View:</strong>
<button class="toggle-btn active" onclick="showHumanView()">👤 Human</button>
<button class="toggle-btn" onclick="showLLMView()">🤖 LLM</button>
</div>
<div id="human-view">
<section>
<h2>Directory tree</h2>
<pre>{html.escape(tree_text)}</pre>
</section>
<section class="toc-top">
<h2>Table of contents ({len(rendered)})</h2>
<ul class="toc">{toc_html}</ul>
</section>
<section>
<h2>Skipped items</h2>
{skipped_html}
</section>
{''.join(sections)}
</div>
<div id="llm-view">
<section>
<h2>🤖 LLM View - CXML Format</h2>
<p>Copy the text below and paste it to an LLM for analysis:</p>
<textarea id="llm-text" readonly>{html.escape(cxml_text)}</textarea>
<div class="copy-hint">
💡 <strong>Tip:</strong> Click in the text area and press Ctrl+A (Cmd+A on Mac) to select all, then Ctrl+C (Cmd+C) to copy.
</div>
</section>
</div>
</main>
</div>
<script>
function showHumanView() {{
document.getElementById('human-view').style.display = 'block';
document.getElementById('llm-view').style.display = 'none';
document.querySelectorAll('.toggle-btn').forEach(btn => btn.classList.remove('active'));
event.target.classList.add('active');
}}
function showLLMView() {{
document.getElementById('human-view').style.display = 'none';
document.getElementById('llm-view').style.display = 'block';
document.querySelectorAll('.toggle-btn').forEach(btn => btn.classList.remove('active'));
event.target.classList.add('active');
// Auto-select all text when switching to LLM view for easy copying
setTimeout(() => {{
const textArea = document.getElementById('llm-text');
textArea.focus();
textArea.select();
}}, 100);
}}
</script>
</body>
</html>
"""
defderive_temp_output_path(repo_url: str) ->pathlib.Path:
"""Derive a temporary output path from the repo URL."""
# Extract repo name from URL like https://github.com/owner/repo or https://github.com/owner/repo.git
parts=repo_url.rstrip('/').split('/')
iflen(parts) >=2:
repo_name=parts[-1]
ifrepo_name.endswith('.git'):
repo_name=repo_name[:-4]
filename=f"{repo_name}.html"
else:
filename="repo.html"
returnpathlib.Path(tempfile.gettempdir()) /filename
defmain() ->int:
ap=argparse.ArgumentParser(description="Flatten a GitHub repo to a single HTML page")
ap.add_argument("repo_url", help="GitHub repo URL (https://github.com/owner/repo[.git])")
ap.add_argument("-o", "--out", help="Output HTML file path (default: temporary file derived from repo name)")
ap.add_argument("--max-bytes", type=int, default=MAX_DEFAULT_BYTES, help="Max file size to render (bytes); larger files are listed but skipped")
ap.add_argument("--no-open", action="store_true", help="Don't open the HTML file in browser after generation")
args=ap.parse_args()
# Set default output path if not provided
ifargs.outisNone:
args.out=str(derive_temp_output_path(args.repo_url))
tmpdir=tempfile.mkdtemp(prefix="flatten_repo_")
repo_dir=pathlib.Path(tmpdir, "repo")
try:
print(f"📁 Cloning {args.repo_url} to temporary directory: {repo_dir}", file=sys.stderr)
git_clone(args.repo_url, str(repo_dir))
head=git_head_commit(str(repo_dir))
print(f"✓ Clone complete (HEAD: {head[:8]})", file=sys.stderr)
print(f"📊 Scanning files in {repo_dir}...", file=sys.stderr)
infos=collect_files(repo_dir, args.max_bytes)
rendered_count=sum(1foriininfosifi.decision.include)
skipped_count=len(infos) -rendered_count
print(f"✓ Found {len(infos)} files total ({rendered_count} will be rendered, {skipped_count} skipped)", file=sys.stderr)
print(f"🔨 Generating HTML...", file=sys.stderr)
html_out=build_html(args.repo_url, repo_dir, head, infos)
out_path=pathlib.Path(args.out)
print(f"💾 Writing HTML file: {out_path.resolve()}", file=sys.stderr)
out_path.write_text(html_out, encoding="utf-8")
file_size=out_path.stat().st_size
print(f"✓ Wrote {bytes_human(file_size)} to {out_path}", file=sys.stderr)
ifnotargs.no_open:
print(f"🌐 Opening {out_path} in browser...", file=sys.stderr)
webbrowser.open(f"file://{out_path.resolve()}")
print(f"🗑️ Cleaning up temporary directory: {tmpdir}", file=sys.stderr)
return0
finally:
shutil.rmtree(tmpdir, ignore_errors=True)
if__name__=="__main__":
main()