Debian Codegraph @

scripts/ensure-stable-doc-urls.py

raw
1 #!/usr/bin/env python3
2
3 # Doc URLs may change with time because they depend on Doxygen machinery.
4 # This is unfortunate because it is good practice to keep valid URLs.
5 # See: “Cool URIs don’t change” at https://www.w3.org/Provider/Style/URI.html.
6 #
7 # There is no built-in solution in Doxygen that we are aware of.
8 # The solution proposed here is to maintain a registry of all URLs and manage
9 # legacy URLs as redirections to their canonical page.
10
11 import argparse
12 from enum import IntFlag
13 import glob
14 from itertools import chain
15 from pathlib import Path
16 from string import Template
17 from typing import NamedTuple, Sequence
18
19 import yaml
20
21
22 class Update(NamedTuple):
23 new: str
24 old: str
25
26
27 class ExitCode(IntFlag):
28 NORMAL = 0
29 INVALID_UPDATES = 1 << 4
30 MISSING_UPDATES = 1 << 5
31 NON_UNIQUE_DIRECTIONS = 1 << 6
32
33
34 THIS_SCRIPT_PATH = Path(__file__)
35 RELATIVE_SCRIPT_PATH = THIS_SCRIPT_PATH.relative_to(THIS_SCRIPT_PATH.parent.parent)
36
37 REDIRECTION_DELAY = 6 # in seconds. Note: at least 6s for accessibility
38 REDIRECTION_TITLE = "xkbcommon: Page Redirection"
39 OPTIONAL_ENTRY = "__optional__"
40
41 # NOTE: The redirection works with the HTML tag: <meta http-equiv="refresh">.
42 # See: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta#http-equiv
43 #
44 # NOTE: This page is a simplified version of the Doxygen-generated ones.
45 # It does use the current stylesheets, but it may break if the theme is updated.
46 # Ideally, we would just let Doxygen generate them, but I (Wismill) could not
47 # find a way to do this with the redirection feature.
48 REDIRECTION_PAGE_TEMPLATE = Template(
49 """<!DOCTYPE HTML>
50 <html lang="en-US">
51 <head>
52 <meta charset="UTF-8">
53 <meta http-equiv="refresh" content="${delay}; url=${canonical}">
54 <link href="doxygen.css" rel="stylesheet" type="text/css">
55 <link href="doxygen-extra.css" rel="stylesheet" type="text/css">
56 <title>${title}</title>
57 </head>
58 <body>
59 <div id="top">
60 <div id="titlearea" style="padding: 1em 0 1em 0.5em;">
61 <div id="projectname">
62 libxkbcommon
63 </div>
64 </div>
65 </div>
66 <div>
67 <div class="header">
68 <div class="headertitle">
69 <div class="title">🔀 Redirection</div>
70 </div>
71 </div>
72 <div class="contents">
73 <p>This page has been moved.</p>
74 <p>
75 If you are not redirected automatically,
76 follow the <a href="${canonical}">link to the current page</a>.
77 </p>
78 </div>
79 </div>
80 </body>
81 </html>
82 """
83 )
84
85
86 def parse_page_update(update: str) -> Update:
87 updateʹ = Update(*update.split("="))
88 if updateʹ.new == updateʹ.old:
89 raise ValueError(f"Invalid update: {updateʹ}")
90 return updateʹ
91
92
93 def is_page_redirection(path: Path):
94 with path.open("rt", encoding="utf-8") as fd:
95 for line in fd:
96 if REDIRECTION_TITLE in line:
97 return True
98 return False
99
100
101 def update_registry(registry_path: Path, doc_dir: Path, updates: Sequence[str]):
102 """
103 Update the URL registry by:
104 • Adding new pages
105 • Updating page aliases
106 """
107 # Parse updates
108 updates_ = dict(map(parse_page_update, updates))
109 # Update
110 invalid_updates = set(updates_)
111 # Load previous registry
112 with registry_path.open("rt", encoding="utf-8") as fd:
113 registry: dict[str, list[str]] = yaml.safe_load(fd) or {}
114 registryʹ = dict(
115 (canonical, aliases)
116 for canonical, aliases in registry.items()
117 if canonical != OPTIONAL_ENTRY
118 )
119 # Expected updates
120 missing_updates = set(
121 canonical for canonical in registryʹ if not (doc_dir / canonical).is_file()
122 )
123 # Ensure each page is unique
124 for d, rs in registryʹ.items():
125 if clashes := frozenset(rs).intersection(registry):
126 print(
127 f"[ERROR] The following redirections of “{d}”",
128 f"clash with canonical directions: {clashes}",
129 )
130 exit(ExitCode.NON_UNIQUE_DIRECTIONS)
131 redirections = frozenset(chain.from_iterable(registryʹ.values()))
132 for file in glob.iglob("**/*.html", root_dir=doc_dir, recursive=True):
133 # Skip redirection pages
134 if file in redirections:
135 continue
136 # Get previous entry and potential update
137 if old := updates_.get(file):
138 # Update old entry
139 invalid_updates.remove(file)
140 entry = registry.get(old)
141 if entry is None:
142 raise ValueError(f"Invalid update: {file}<-{old}")
143 else:
144 del registry[old]
145 missing_updates.remove(old)
146 registry[file] = [e for e in [old] + entry if e != file]
147 print(f"[INFO] Updated: “{old}” to “{file}”")
148 else:
149 entry = registry.get(file)
150 if entry is None:
151 # New entry
152 registry[file] = []
153 print(f"[INFO] Added: {file}")
154 else:
155 # Keep previous entry
156 pass
157 exit_code = ExitCode.NORMAL
158 # Check
159 if invalid_updates:
160 for update in invalid_updates:
161 print(f"[ERROR] Update not processed: {update}")
162 exit_code |= ExitCode.INVALID_UPDATES
163 if missing_updates:
164 for old in missing_updates:
165 # Handle older Doxygen versions
166 if old in registry.get(OPTIONAL_ENTRY, []):
167 print(
168 "[WARNING] Handling old Doxygen version:",
169 f"skip optional “{old}”",
170 )
171 missing_updates.remove(old)
172 continue
173 old_redirections = registry[old]
174 for r in old_redirections:
175 path = doc_dir / r
176 if path.is_file() and not is_page_redirection(path):
177 print(
178 "[WARNING] Handling old Doxygen version:",
179 f"use “{r}” instead of “{old}” for the canonical direction",
180 )
181 missing_updates.remove(old)
182 break
183 else:
184 print(f"[ERROR] “{old}” not found and has no update.")
185 if missing_updates:
186 exit_code |= ExitCode.MISSING_UPDATES
187 if exit_code:
188 print("[ERROR] Processing interrupted: please fix the errors above.")
189 exit(exit_code.value)
190 # Write changes
191 with registry_path.open("wt", encoding="utf-8") as fd:
192 fd.write(f"# WARNING: This file is autogenerated by: {RELATIVE_SCRIPT_PATH}\n")
193 fd.write("# Do not edit manually.\n")
194 yaml.dump(registry, fd)
195
196
197 def generate_redirections(registry_path: Path, doc_dir: Path):
198 """
199 Create redirection pages using the aliases in the given URL registry.
200 """
201 cool = True
202 # Load registry
203 with registry_path.open("rt", encoding="utf-8") as fd:
204 registry: dict[str, list[str]] = yaml.safe_load(fd) or {}
205 registryʹ = dict(
206 (canonical, aliases)
207 for canonical, aliases in registry.items()
208 if canonical != OPTIONAL_ENTRY
209 )
210 for canonical, aliases in registryʹ.items():
211 # Check canonical path is up-to-date
212 if not (doc_dir / canonical).is_file():
213 # Handle older Doxygen versions
214 if canonical in registry.get(OPTIONAL_ENTRY, []):
215 print(
216 "[WARNING] Handling old Doxygen version:",
217 f"skip optional “{canonical}”",
218 )
219 continue
220 for r in aliases:
221 path = doc_dir / r
222 if path.is_file() and not is_page_redirection(path):
223 print(
224 "[WARNING] Handling old Doxygen version:",
225 f"use “{r}” instead of “{canonical}” for the canonical direction",
226 )
227 canonical = r
228 aliases.remove(r)
229 break
230 else:
231 cool = False
232 print(
233 f"ERROR: missing canonical documentation page “{canonical}”. "
234 f"Please update “{registry_path}” using {RELATIVE_SCRIPT_PATH}”."
235 )
236 # Add a redirection page
237 for alias in aliases:
238 path = doc_dir / alias
239 with path.open("wt", encoding="utf-8") as fd:
240 fd.write(
241 REDIRECTION_PAGE_TEMPLATE.substitute(
242 canonical=canonical,
243 delay=REDIRECTION_DELAY,
244 title=REDIRECTION_TITLE,
245 )
246 )
247 if not cool:
248 exit(1)
249
250
251 def add_registry_argument(parser):
252 parser.add_argument(
253 "registry",
254 type=Path,
255 help="Path to the doc URI registry.",
256 )
257
258
259 def add_docdir_argument(parser):
260 parser.add_argument(
261 "docdir",
262 type=Path,
263 metavar="DOC_DIR",
264 help="Path to the generated HTML documentation directory.",
265 )
266
267
268 if __name__ == "__main__":
269 parser = argparse.ArgumentParser(
270 description="Tool to ensure HTML documentation has stable URLs"
271 )
272 subparsers = parser.add_subparsers()
273
274 parser_registry = subparsers.add_parser(
275 "update-registry", help="Update the registry of URIs"
276 )
277 add_registry_argument(parser_registry)
278 add_docdir_argument(parser_registry)
279 parser_registry.add_argument(
280 "updates",
281 nargs="*",
282 type=str,
283 help="Update: new=previous entries",
284 )
285 parser_registry.set_defaults(
286 run=lambda args: update_registry(args.registry, args.docdir, args.updates)
287 )
288
289 parser_redirections = subparsers.add_parser(
290 "generate-redirections", help="Generate URIs redirections"
291 )
292 add_registry_argument(parser_redirections)
293 add_docdir_argument(parser_redirections)
294 parser_redirections.set_defaults(
295 run=lambda args: generate_redirections(args.registry, args.docdir)
296 )
297
298 args = parser.parse_args()
299 args.run(args)