-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode2pdf.py
More file actions
249 lines (201 loc) · 7.04 KB
/
Copy pathcode2pdf.py
File metadata and controls
249 lines (201 loc) · 7.04 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
import os
import sys
import subprocess
import shutil
import tempfile
from pathlib import Path
# Config
REPOS = [
# "https://github.com/your-org/repo1.git",
# "https://github.com/your-org/repo2.git",
"https://github.com/TourGuideSeniorDesign/tour-guide-code-module.git"
]
OUTPUT_PDF = "output.pdf"
OUTPUT_TEX = "output.tex"
# File extensions to include (empty = include everything readable)
# INCLUDE_EXTENSIONS = {
# ".py", ".js", ".ts", ".tsx", ".jsx", ".go", ".rs", ".c", ".cpp", ".h",
# ".hpp", ".java", ".rb", ".sh", ".bash", ".zsh", ".fish", ".cs", ".swift",
# ".kt", ".scala", ".r", ".m", ".lua", ".pl", ".php", ".html", ".css",
# ".scss", ".sass", ".less", ".json", ".yaml", ".yml", ".toml", ".ini",
# ".cfg", ".conf", ".env", ".xml", ".sql", ".md", ".txt", ".dockerfile",
# "dockerfile", ".makefile", "makefile", ".gitignore", ".env.example",
# }
INCLUDE_EXTENSIONS = {}
# Directories to skip
SKIP_DIRS = {
".git", ".github", "node_modules", "__pycache__", ".venv", "venv",
"env", ".env", "dist", "build", ".next", ".nuxt", "target", "vendor",
".idea", ".vscode", "coverage", ".nyc_output", "out",
}
# Max file size to include (bytes) — skip huge files
MAX_FILE_BYTES = 2_000_000
# Latex helpers
LATEX_ESCAPE = str.maketrans({
"&": r"\&",
"%": r"\%",
"$": r"\$",
"#": r"\#",
"_": r"\_",
"{": r"\{",
"}": r"\}",
"~": r"\textasciitilde{}",
"^": r"\textasciicircum{}",
"\\": r"\textbackslash{}",
})
def latex_escape(text: str) -> str:
return text.translate(LATEX_ESCAPE)
def verbatim_block(content: str) -> str:
"""Wrap content in a LaTeX verbatim environment, splitting at page boundaries."""
# lstlisting handles long lines and special chars natively
return "\\begin{lstlisting}\n" + content + "\n\\end{lstlisting}\n"
PREAMBLE = r"""\documentclass[10pt,a4paper]{article}
\usepackage[margin=2cm]{geometry}
\usepackage{listings}
\usepackage{xcolor}
\usepackage{hyperref}
\usepackage{titlesec}
\usepackage{parskip}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}
\hypersetup{
colorlinks=true,
linkcolor=blue!60!black,
urlcolor=blue!60!black,
}
\lstset{
basicstyle=\ttfamily\footnotesize,
breaklines=true,
breakatwhitespace=false,
columns=fullflexible,
keepspaces=true,
showstringspaces=false,
extendedchars=true,
frame=single,
framerule=0.4pt,
rulecolor=\color{gray!50},
backgroundcolor=\color{gray!5},
xleftmargin=4pt,
xrightmargin=4pt,
aboveskip=6pt,
belowskip=6pt,
}
\titleformat{\section}{\large\bfseries}{}{0em}{}[\titlerule]
\titleformat{\subsection}{\normalsize\bfseries\ttfamily}{}{0em}{}
\title{\textbf{AUTOGIRO Code Export}}
\date{\today}
\begin{document}
\maketitle
\tableofcontents
\newpage
"""
POSTAMBLE = r"\end{document}" + "\n"
# Core logic
def should_include(path: Path) -> bool:
if not path.is_file():
return False
if path.stat().st_size > MAX_FILE_BYTES:
return False
name_lower = path.name.lower()
suffix_lower = path.suffix.lower()
if not INCLUDE_EXTENSIONS:
return True
return suffix_lower in INCLUDE_EXTENSIONS or name_lower in INCLUDE_EXTENSIONS
def collect_files(repo_dir: Path) -> list[Path]:
files = []
for root, dirs, filenames in os.walk(repo_dir):
dirs[:] = [d for d in dirs if d not in SKIP_DIRS]
for name in sorted(filenames):
p = Path(root) / name
if should_include(p):
files.append(p)
return sorted(files)
def read_file_safe(path: Path) -> str | None:
try:
return path.read_text(encoding="utf-8", errors="replace")
except Exception:
return None
def clone_repo(url: str, target_dir: Path) -> bool:
print(f" Cloning {url} ...", flush=True)
result = subprocess.run(
["git", "clone", "--depth=1", url, str(target_dir)],
capture_output=True, text=True
)
if result.returncode != 0:
print(f" ERROR cloning {url}:\n{result.stderr}", file=sys.stderr)
return False
return True
def repo_name_from_url(url: str) -> str:
name = url.rstrip("/").split("/")[-1]
if name.endswith(".git"):
name = name[:-4]
return name
def build_tex(repos: list[str], work_dir: Path) -> str:
parts = [PREAMBLE]
for url in repos:
name = repo_name_from_url(url)
repo_dir = work_dir / name
if not clone_repo(url, repo_dir):
parts.append(f"\\section{{{latex_escape(name)}}}\n")
parts.append("\\textcolor{red}{Failed to clone repository.}\n\n")
continue
parts.append(f"\\section{{{latex_escape(name)}}}\n")
print(f" Collecting files for {name} ...", flush=True)
files = collect_files(repo_dir)
print(f" Found {len(files)} files.", flush=True)
for fpath in files:
rel = fpath.relative_to(repo_dir)
parts.append(f"\\subsection{{{latex_escape(str(rel))}}}\n")
content = read_file_safe(fpath)
if content is None:
parts.append("\\textit{Could not read file.}\n\n")
else:
parts.append(verbatim_block(content))
parts.append(POSTAMBLE)
return "\n".join(parts)
def compile_pdf(tex_path: Path, output_pdf: Path):
print("Compiling LaTeX ...", flush=True)
for pass_num in (1, 2): # two passes for TOC
result = subprocess.run(
[
"pdflatex",
"-interaction=nonstopmode",
f"-output-directory={tex_path.parent}",
str(tex_path),
],
capture_output=True,
cwd=tex_path.parent,
)
result.stdout = result.stdout.decode("utf-8", errors="replace")
result.stderr = result.stderr.decode("utf-8", errors="replace")
print(f" Pass {pass_num} done.", flush=True)
generated = tex_path.with_suffix(".pdf")
if not generated.exists():
print("LaTeX failed to produce a PDF. Last 40 lines of log:", file=sys.stderr)
log_file = tex_path.with_suffix(".log")
if log_file.exists():
lines = log_file.read_text(errors="replace").splitlines()
print("\n".join(lines[-40:]), file=sys.stderr)
sys.exit(1)
shutil.move(str(generated), str(output_pdf))
print(f"\nDone! PDF written to: {output_pdf.resolve()}")
def main():
repos = REPOS
if not repos:
print("No repos specified. Edit the REPOS list in this script.")
sys.exit(1)
# Validate URLs
for url in repos:
if not url.endswith(".git"):
print(f"Warning: '{url}' does not end in .git — continuing anyway.")
with tempfile.TemporaryDirectory(prefix="code2pdf_") as tmp:
work_dir = Path(tmp)
tex_path = work_dir / OUTPUT_TEX
print("Building LaTeX source ...", flush=True)
tex = build_tex(repos, work_dir)
tex_path.write_text(tex, encoding="utf-8")
print(f" Wrote {tex_path} ({len(tex):,} chars)")
compile_pdf(tex_path, Path(OUTPUT_PDF))
if __name__ == "__main__":
main()