Debian Codegraph @

dh_doc_privacy

raw
1 #!/usr/bin/python3
2 """
3 Remove remote assets from documentation files.
4
5 This tool strips remotely-hosted images, iframes, and tracking scripts from
6 documentation sources before they are turned into HTML and installed under
7 /usr/share/doc/.
8 """
9
10 from __future__ import annotations
11
12 import argparse
13 import hashlib
14 import os
15 from pathlib import Path
16 import re
17 import shutil
18 import sys
19 import textwrap
20
21 HTML_IMG_RE = re.compile(r'<img\b[^>]*\bsrc=["\']([^"\']+)["\'][^>]*>', re.I)
22 HTML_SRC_HREF_RE = re.compile(r'\b(?:src|href)=["\']([^"\']+)["\']', re.I)
23 HTML_IFRAME_RE = re.compile(
24 r'<iframe\b[^>]*\bsrc=["\']([^"\']+)["\'][^>]*>.*?</iframe>',
25 re.I | re.S,
26 )
27 HTML_TWITTER_WIDGETS_SCRIPT_RE = re.compile(
28 r"<script\b[^>]*>.*?\+'\:\/\/platform\.twitter\.com\/widgets\.js'.*?</script>",
29 re.I | re.S,
30 )
31 HTML_PIWIK_SCRIPT_RE = re.compile(
32 r"<script\b[^>]*>.*?setTrackerUrl.*?</script>", re.I | re.S
33 )
34 RST_SUB_DEF_RE = re.compile(r"^\s*\.\.\s+\|([^|]+)\|\s+(?:figure|image)::\s+(\S+)\s*$")
35 __version__ = "unknown"
36
37
38 class Options:
39 """Runtime options parsed from command-line arguments."""
40
41 def __init__(
42 self,
43 excludes: list[str],
44 no_act: bool,
45 verbose: bool,
46 sourcedir: Path | None,
47 ) -> None:
48 """Store the parsed command-line settings."""
49 self.excludes = excludes
50 self.no_act = no_act
51 self.verbose = verbose
52 self.sourcedir = sourcedir
53
54
55 def error(message: str) -> None:
56 """Print an error message to stderr and exit with status 1."""
57 sys.stderr.write(f"dh_doc_privacy: error: {message}\n")
58 raise SystemExit(1)
59
60
61 def verbose_print(message: str, options: Options) -> None:
62 """Print a message to stderr when verbose or no-act mode is active."""
63 if options.verbose or options.no_act:
64 print(message, file=sys.stderr)
65
66
67 def parse_args(argv: list[str]) -> tuple[Options, list[str]]:
68 """Parse command-line arguments and return options and positional paths."""
69 description = textwrap.dedent("""\
70 Remove remote badge images, iframes, and tracking scripts from
71 documentation files before they are shipped in a Debian package.
72
73 By default the command scans the top-level README.md, README.rst, and
74 README.html files. You can also pass explicit files or directories to
75 process.
76 """)
77 parser = argparse.ArgumentParser(
78 add_help=True,
79 description=description,
80 formatter_class=argparse.RawDescriptionHelpFormatter,
81 )
82 parser.add_argument(
83 "paths",
84 nargs="*",
85 metavar="PATH",
86 help="file or directory to process; defaults to top-level README files",
87 )
88 parser.add_argument(
89 "-X",
90 "--exclude",
91 action="append",
92 default=[],
93 metavar="PATTERN",
94 help="skip files whose path contains PATTERN; may be specified multiple times",
95 )
96 parser.add_argument(
97 "--no-act",
98 "-n",
99 action="store_true",
100 help="report files that would be changed without modifying them",
101 )
102 parser.add_argument(
103 "--verbose",
104 "-v",
105 action="store_true",
106 help="print a message for each file that is examined or changed",
107 )
108 parser.add_argument(
109 "--version", action="version", version=f"%(prog)s {__version__}"
110 )
111 parser.add_argument(
112 "--sourcedir",
113 metavar="DIR",
114 help="treat DIR as the package source root instead of the current directory",
115 )
116 parsed, rest = parser.parse_known_args(argv)
117 unknown = [arg for arg in rest if arg.startswith("-")]
118 if unknown:
119 error(f"unknown option(s): {' '.join(unknown)}")
120 sourcedir = Path(parsed.sourcedir) if parsed.sourcedir else None
121 options = Options(
122 excludes=parsed.exclude,
123 no_act=parsed.no_act,
124 verbose=parsed.verbose,
125 sourcedir=sourcedir,
126 )
127 return options, parsed.paths
128
129
130 def excludefile(path: str, options: Options) -> bool:
131 """Return True if the file path matches any exclude pattern."""
132 return any(exclude in path for exclude in options.excludes)
133
134
135 def is_remote_url(url: str) -> bool:
136 """Return True if the URL is http, https, or protocol-relative."""
137 value = url.strip().strip("<>")
138 return re.match(r"^(https?:)?//", value, re.I) is not None
139
140
141 def remove_html_blocks(lines: list[str]) -> list[str]:
142 """Remove HTML block elements that contain only remote assets."""
143 result: list[str] = []
144 idx = 0
145 while idx < len(lines):
146 line = lines[idx]
147 start_tag: str | None = None
148 for tag in ("table", "p", "div", "iframe"):
149 if f"<{tag}" in line:
150 start_tag = tag
151 break
152 if start_tag is None:
153 result.append(line)
154 idx += 1
155 continue
156 end_tag = f"</{start_tag}>"
157 block = [line]
158 idx += 1
159 while idx < len(lines) and end_tag not in lines[idx]:
160 block.append(lines[idx])
161 idx += 1
162 if idx < len(lines):
163 block.append(lines[idx])
164 idx += 1
165 block_text = "\n".join(block)
166 has_remote = False
167 has_local = False
168 for match in HTML_IMG_RE.finditer(block_text):
169 if is_remote_url(match.group(1)):
170 has_remote = True
171 else:
172 has_local = True
173 for match in HTML_IFRAME_RE.finditer(block_text):
174 if is_remote_url(match.group(1)):
175 has_remote = True
176 else:
177 has_local = True
178 if has_remote and not has_local:
179 stripped = re.sub(r"<[^>]+>|&[a-zA-Z0-9#]+;", "", block_text)
180 if stripped.strip() == "":
181 result.append("__BADGE_BLOCK_REMOVED__")
182 if idx < len(lines) and not lines[idx].strip():
183 idx += 1
184 continue
185 result.extend(block)
186 return result
187
188
189 def remove_markdown_images(line: str) -> str:
190 """Remove remote Markdown image links from a single line."""
191
192 def replace_link(match: re.Match[str]) -> str:
193 return "" if is_remote_url(match.group(1)) else match.group(0)
194
195 line = re.sub(
196 r"\[!\[[^\]]*\]\(([^)]+)\)\]\([^)]+\)",
197 replace_link,
198 line,
199 flags=re.I | re.S,
200 )
201 line = re.sub(r"!\[[^\]]*\]\(([^)]+)\)", replace_link, line, flags=re.I | re.S)
202 return line
203
204
205 def remove_html_images(line: str) -> str:
206 """Remove remote HTML img and iframe tags from a single line."""
207
208 def replace_html(match: re.Match[str]) -> str:
209 return "" if is_remote_url(match.group(1)) else match.group(0)
210
211 line = re.sub(HTML_IMG_RE, replace_html, line)
212 line = re.sub(HTML_IFRAME_RE, replace_html, line)
213 return line
214
215
216 def remove_html_scripts_text(text: str) -> str:
217 """Strip known tracking script patterns from text."""
218 text = re.sub(HTML_TWITTER_WIDGETS_SCRIPT_RE, "", text)
219 text = re.sub(HTML_PIWIK_SCRIPT_RE, "", text)
220 return text
221
222
223 def remove_rst_badges(lines: list[str]) -> list[str]:
224 """Remove remote RST image/figure directives and named substitution refs."""
225 removed_names: dict[str, bool] = {}
226 result: list[str] = []
227 idx = 0
228 while idx < len(lines):
229 line = lines[idx]
230 match = RST_SUB_DEF_RE.match(line)
231 if match and is_remote_url(match.group(2)):
232 removed_names[match.group(1)] = True
233 idx += 1
234 while idx < len(lines) and lines[idx].startswith((" ", "\t")):
235 idx += 1
236 if idx < len(lines) and not lines[idx].strip():
237 idx += 1
238 continue
239 inline_match = re.match(r"^\s*\.\.\s+(?:figure|image)::\s+(\S+)\s*$", line)
240 if inline_match and is_remote_url(inline_match.group(1)):
241 idx += 1
242 while idx < len(lines) and lines[idx].startswith((" ", "\t")):
243 idx += 1
244 if idx < len(lines) and not lines[idx].strip():
245 idx += 1
246 continue
247 if re.match(r"^\s*\.\.\s+raw::\s+html\s*$", line):
248 block_lines = [line]
249 idx += 1
250 while idx < len(lines):
251 l = lines[idx]
252 if not l.strip() or l[0] in (" ", "\t"):
253 block_lines.append(l)
254 idx += 1
255 else:
256 break
257 block_text = "\n".join(block_lines)
258 if any(
259 is_remote_url(m.group(1)) for m in HTML_SRC_HREF_RE.finditer(block_text)
260 ):
261 continue
262 result.extend(block_lines)
263 continue
264 result.append(line)
265 idx += 1
266
267 final: list[str] = []
268 removed_prev = False
269 for i, original in enumerate(result):
270 line = original
271 is_badge_block_line = re.match(r"^\s*\|", original) is not None
272 neighbor_badge = False
273 if is_badge_block_line:
274 if i > 0 and re.match(r"^\s*\|", result[i - 1]):
275 neighbor_badge = True
276 if i + 1 < len(result) and re.match(r"^\s*\|", result[i + 1]):
277 neighbor_badge = True
278 if is_badge_block_line and neighbor_badge:
279 final.append(original)
280 continue
281 for name in removed_names.keys():
282 line = line.replace(f"|{name}|", "")
283 if line.strip() and line.strip("|").strip() == "":
284 removed_prev = True
285 continue
286 if original.strip() and not line.strip():
287 removed_prev = True
288 continue
289 if removed_prev and not line.strip():
290 removed_prev = False
291 if final and final[-1].strip():
292 final.append(line)
293 continue
294 removed_prev = False
295 final.append(line)
296 return final
297
298
299 def remove_markdown_badges(text: str) -> str:
300 """Remove remote badge images and HTML blocks from Markdown text."""
301 text = remove_html_scripts_text(text)
302 had_trailing_newline = text.endswith("\n")
303 lines = text.split("\n")
304 lines = remove_html_blocks(lines)
305 cleaned: list[str] = []
306 removed_prev = False
307 idx = 0
308 while idx < len(lines):
309 original = lines[idx]
310 if original == "__BADGE_BLOCK_REMOVED__":
311 removed_prev = True
312 idx += 1
313 continue
314 line = remove_markdown_images(original)
315 line = remove_html_images(line)
316 if original.strip() and not line.strip():
317 removed_prev = True
318 idx += 1
319 continue
320 if removed_prev:
321 if not line.strip():
322 removed_prev = False
323 idx += 1
324 continue
325 removed_prev = False
326 cleaned.append(line)
327 idx += 1
328 while cleaned and not cleaned[0].strip():
329 cleaned.pop(0)
330 while cleaned and not cleaned[-1].strip():
331 cleaned.pop()
332 output = "\n".join(cleaned)
333 if had_trailing_newline:
334 output += "\n"
335 return output
336
337
338 def remove_rst_badges_text(text: str) -> str:
339 """Remove remote RST directives and inline images from RST text."""
340 text = remove_html_scripts_text(text)
341 lines = text.split("\n")
342 lines = remove_html_blocks(lines)
343 lines = remove_rst_badges(lines)
344 return "\n".join(remove_html_images(line) for line in lines)
345
346
347 def remove_badges(text: str, path: str) -> str:
348 """Dispatch badge removal for .rst or Markdown/HTML files."""
349 if path.lower().endswith(".rst"):
350 return remove_rst_badges_text(text)
351 cleaned = remove_markdown_badges(text)
352 return remove_rst_badges_text(cleaned)
353
354
355 def restore_file_on_clean(path: Path, options: Options) -> None:
356 """Back up the original file so dh_clean can restore it later."""
357 if options.no_act:
358 return
359 if path.is_absolute():
360 error("restore_file_on_clean requires a path relative to the package dir")
361 bucket_index = Path("debian/.debhelper/bucket/index")
362 bucket_dir = Path("debian/.debhelper/bucket/files")
363 bucket_dir.mkdir(parents=True, exist_ok=True)
364 cleaned = Path(str(path).lstrip("./"))
365 normalized = Path(str(cleaned).replace("//", "/"))
366 normalized_str = str(normalized)
367 if (
368 normalized_str.startswith(".")
369 or "/CVS/" in normalized_str
370 or "/." in normalized_str
371 ):
372 error("Attempt to store a hidden or VCS file path")
373 if normalized.is_symlink() or not normalized.is_file():
374 error("Cannot store non-regular file for restore")
375 checksum = hashlib.sha256(normalized.read_bytes()).hexdigest()
376 stored_already = False
377 if bucket_index.exists():
378 for line in bucket_index.read_text(encoding="utf-8").splitlines():
379 parts = line.split(" ", 1)
380 if len(parts) == 2 and parts[1] == normalized_str:
381 stored_already = True
382 break
383 if not stored_already:
384 bucket_file = bucket_dir / checksum
385 if not bucket_file.exists():
386 tmp_file = bucket_dir / f"{checksum}.tmp"
387 shutil.copy2(normalized, tmp_file)
388 os.replace(tmp_file, bucket_file)
389 bucket_index.parent.mkdir(parents=True, exist_ok=True)
390 with bucket_index.open("a", encoding="utf-8") as handle:
391 handle.write(f"{checksum} {normalized_str}\n")
392
393
394 def clean_file(path: Path, options: Options) -> None:
395 """Strip remote assets from a single file and record it for restoration."""
396 if excludefile(str(path), options):
397 return
398 try:
399 text = path.read_text(encoding="utf-8")
400 except OSError as exc:
401 error(f"Unable to read {path}: {exc}")
402 cleaned = remove_badges(text, str(path))
403 if cleaned == text:
404 return
405 restore_file_on_clean(path, options)
406 if options.no_act:
407 verbose_print(f"Would update {path}", options)
408 return
409 try:
410 path.write_text(cleaned, encoding="utf-8")
411 except OSError as exc:
412 error(f"Unable to write {path}: {exc}")
413
414
415 def clean_dir(path: Path, options: Options) -> None:
416 """Recursively strip remote assets from all doc files under a directory."""
417 for root, _, files in os.walk(path):
418 for filename in files:
419 if not filename.lower().endswith((".md", ".rst", ".html")):
420 continue
421 clean_file(Path(root) / filename, options)
422
423
424 def run(paths: list[str], options: Options) -> None:
425 """Process each path, or scan top-level README files if none are given."""
426 if paths:
427 for path_str in paths:
428 path = Path(path_str)
429 if not path.exists():
430 error(f"No such file: {path_str}")
431 if path.is_dir():
432 clean_dir(path, options)
433 continue
434 if not path.is_file():
435 error(f"{path_str} is not a file")
436 clean_file(path, options)
437 return
438 for entry in Path(".").iterdir():
439 if entry.is_file() and re.match(r"^README\.(md|rst|html)$", entry.name, re.I):
440 clean_file(entry, options)
441
442
443 def main(argv: list[str] | None = None) -> int:
444 """Parse arguments, optionally change directory, then run."""
445 options, paths = parse_args(argv or sys.argv[1:])
446 if options.sourcedir:
447 os.chdir(options.sourcedir)
448 run(paths, options)
449 return 0
450
451
452 if __name__ == "__main__":
453 raise SystemExit(main())