gen_wiki_nav.py 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149
  1. # SPDX-License-Identifier: Apache-2.0
  2. """Write the wiki Contents page, the sidebar and the Home page map from one manifest (issue #249).
  3. The manifest is the directory docs/wiki/_nav/: index.yaml (groups, links, readers, goals) plus one
  4. <group id>.yaml page list per group. It lists every wiki page once, in a theme group, with a
  5. short title, an audience, an optional status marker and a one-line description. Three
  6. outputs are generated from it, so adding a page is one line in one file:
  7. docs/wiki/Contents.md every page, grouped, one line each, with its status marker
  8. docs/wiki/_Sidebar.md the sidebar: top links, then one collapsible group each (<details>
  9. and <summary>, which GitHub's collapsed-sections page documents),
  10. with only the core path open by default. Every group lists EVERY
  11. page, one line each, then a "Full list" link to its section of
  12. Contents.md, so a reader reaches any page from the sidebar (issue #378).
  13. docs/wiki/Home.md the hand-written intro stays; only the block between the BEGIN and
  14. END markers (HOME_BEGIN, HOME_END) is rewritten: a "Start here" line
  15. per kind of reader, then every page grouped like Contents with its
  16. one-line description. Nothing outside the markers is touched, and a
  17. Home.md without exactly one marker pair is an error.
  18. Order in the sidebar (the sidebar line budget is a test, not a goal):
  19. - the numbered core path is listed in full, in reading order;
  20. - any other group lists the entries marked `sidebar: true` first (pinned to the top, in display
  21. order), then the rest in display order; with none marked it is simply display order;
  22. - every group ends with "Full list (N)", linking to its heading in Contents.md. The
  23. section headings of Contents.md are the group titles, so group titles must make
  24. distinct anchors (validate checks this).
  25. - an entry may carry `subgroup: "Title"` (not on the core path or the start group). Entries
  26. with no subgroup are listed first, one per line; then each subgroup is a nested
  27. `<details><summary>Title (n)</summary>` in order of first appearance, whose rows pack up to
  28. SIDEBAR_PACK_LINKS (5) links, and at most SIDEBAR_PACK_CHARS (170) characters of visible
  29. text, per line, joined by a middle dot. A group with no subgroup field is one page per line.
  30. A page with no subgroup costs one line, a subgroup costs three lines plus its rows, and the
  31. budget test fails before the limit is reached: that is the signal to fold more pages into
  32. subgroups, not to raise the budget. The first summary line of every block shares its line
  33. with <details>, which saves a line per block.
  34. The optional top-level `readers` list gives each audience its Start-here page for the Home map
  35. (every audience exactly once, an existing page). The optional `goals` list (issue #416) adds a
  36. Start-here line per topic track and per goal ({who, page}; no audience, an existing page).
  37. A group with `numbered: true` and `track: true` is a topic track (issue #416): numbered and curated
  38. in Contents and Home like the core path, but closed by default and folded into subgroups in the
  39. sidebar (the core path, with `numbered` alone, is listed in full and takes no subgroup). A page is
  40. in exactly one group, so a track holds its pages instead of a theme group.
  41. Page navigation (issue #417, moved to the publish step by issue #521): every other page also gets two generated
  42. blocks when the wiki is published, a short one after its first heading and leading quote banners (breadcrumb,
  43. previous, next) and the full one at the end (previous, next, the rest of its group, related pages), each between a
  44. BEGIN GENERATED PAGE NAV and an END GENERATED PAGE NAV line (NAV_BEGIN, NAV_END; "top" and "bottom"). They are NOT
  45. stored in docs/wiki/*.md: a block lists the neighbors and the whole group, so storing it made every new page rewrite
  46. 28 to 42 other files and every lesson PR conflict with every other. scripts/gen-wiki.sh calls `--publish-to DIR`, which
  47. renders the pages with their blocks from docs/wiki/_nav/ into a staging tree, and publishes that. Home and Contents
  48. get none, nor does a page whose first line is a GENERATED comment (another generator writes it whole). --check fails
  49. when a page file still carries a navigation block (running the generator without arguments removes it), and when a
  50. page cannot take the blocks at publish time. The optional `related` list of a page entry, the fallback rule and the
  51. reading orders are explained in the header of docs/wiki/_nav/index.yaml.
  52. In-page contents (issue #441): a page whose author text (all generated blocks taken out) is over TOC_MIN_LINES
  53. (300) lines gets a third generated block, between TOC_BEGIN and TOC_END ("BEGIN/END GENERATED PAGE CONTENTS"), right
  54. after the first heading and the leading quote banners. It is a bold label and a list of links to the page's own headings, so it adds no
  55. heading: the `##` headings, plus the `###` headings (nested under the `##` above them) on a page with fewer than
  56. TOC_SUBHEADINGS_BELOW (6) `##` headings, where the finer list is what the reader needs. The anchors follow GitHub's rule
  57. (heading_slug, page_headings: lower case, punctuation dropped, spaces to hyphens, repeats suffixed -1, -2, code
  58. fences skipped). A page under the threshold, or with nothing to list, carries no block, and one that shrank loses it.
  59. Tests read pages through tests/wikitext.py page_text(), which strips this block too (strip_generated).
  60. Parts, kept apart on purpose (the same shape as gen_project_status.py):
  61. load_manifest(text) parse and reject duplicate keys; PyYAML is imported here only
  62. load_manifest_dir(dir) read docs/wiki/_nav/ (index.yaml plus one page list per group) into one manifest
  63. validate(manifest, pages) pure: the problems with a manifest against a set of page names
  64. render_contents(m), render_sidebar(m), render_home_map(m)
  65. pure: manifest in, Markdown out. No file reads, no clock.
  66. apply_home_map(text, block)
  67. pure: swap the block between the markers of a Home.md text.
  68. render_page_nav(m, page), apply_page_nav(text, blocks), strip_page_nav(text)
  69. pure: the two blocks of a page, put into (or taken out of) a page text.
  70. render_published_page(m, name, text), publish_pages(root, out)
  71. the publish step (issue #521): pages with their navigation blocks, written to a directory.
  72. render_page_contents(text), apply_page_contents(text, block), strip_generated(text)
  73. pure: the contents block of a page (issue #441), put into or taken out of a page text.
  74. main() --check is offline and exits 1 when a generated file is stale
  75. or the manifest does not match the pages in docs/wiki.
  76. Usage (from anywhere inside a clone):
  77. python -I scripts/gen_wiki_nav.py --check exit 1 when stale or inconsistent
  78. python -I scripts/gen_wiki_nav.py rewrite Contents.md, _Sidebar.md, the Home map and the page contents blocks
  79. python -I scripts/gen_wiki_nav.py --publish-to DIR write every page with its navigation blocks into DIR (gen-wiki.sh)
  80. Exit codes: 0 ok, 1 stale or inconsistent (--check) or an unreadable manifest, 2 usage or
  81. a missing PyYAML.
  82. """
  83. from __future__ import annotations
  84. import argparse
  85. import html
  86. import re
  87. import sys
  88. import unicodedata
  89. from pathlib import Path
  90. ROOT = Path(__file__).resolve().parent.parent
  91. WIKI = Path("docs/wiki")
  92. MANIFEST = WIKI / "_nav" # a directory: index.yaml plus one <group id>.yaml page list per group
  93. LEGACY_MANIFEST = WIKI / "_nav.yaml" # the old single file; still read when the directory is absent
  94. CONTENTS = WIKI / "Contents.md"
  95. SIDEBAR = WIKI / "_Sidebar.md"
  96. HOME = WIKI / "Home.md"
  97. # The generated block of Home.md sits between these two lines; everything else on Home is hand-written.
  98. HOME_BEGIN = "<!-- BEGIN GENERATED PAGE MAP: rewritten from docs/wiki/_nav.yaml by scripts/gen_wiki_nav.py; edit the manifest, not this block -->"
  99. HOME_END = "<!-- END GENERATED PAGE MAP -->"
  100. SPECIAL = {"_Sidebar", "_Footer"} # wiki chrome, not pages a reader navigates to
  101. # Page navigation blocks (issue #417): two generated blocks per page, one at the top (breadcrumb, previous and
  102. # next) and one at the bottom (previous and next, the rest of the track, related pages).
  103. NAV_BEGIN = "<!-- BEGIN GENERATED PAGE NAV {where}: rewritten from docs/wiki/_nav.yaml by scripts/gen_wiki_nav.py; edit the manifest, not this block -->"
  104. NAV_END = "<!-- END GENERATED PAGE NAV {where} -->"
  105. NAV_PLACES = ("top", "bottom")
  106. # Home has its own page map and Contents is the index itself, so neither gets a block. A page whose first line is a
  107. # GENERATED comment is written whole by another generator (the status, growth and settings pages); a block added
  108. # here would make that generator's --check fail, so those are left alone too.
  109. NAV_EXEMPT = {"Home", "Contents"}
  110. GENERATED_PAGE_START = "<!-- GENERATED"
  111. RELATED_MIN = 3
  112. RELATED_MAX = 6
  113. RELATED_FALLBACK = 4 # how many neighbors stand in for a missing `related:` list
  114. # The in-page contents block (issue #441): a third generated block, after the top navigation block, on a page whose author
  115. # text (generated blocks taken out) is over TOC_MIN_LINES lines. It lists the page's `##` headings; a page with fewer than
  116. # TOC_SUBHEADINGS_BELOW of them also lists its `###` headings, nested under the `##` above. Nothing else is listed.
  117. TOC_BEGIN = "<!-- BEGIN GENERATED PAGE CONTENTS: rewritten from the page's own headings by scripts/gen_wiki_nav.py; edit the headings, not this block -->"
  118. TOC_END = "<!-- END GENERATED PAGE CONTENTS -->"
  119. TOC_LABEL = "**On this page:**"
  120. TOC_MIN_LINES = 300
  121. TOC_SUBHEADINGS_BELOW = 6
  122. AUDIENCES = ("everyone", "newcomer", "learner", "builder", "engineer", "operator", "security reader")
  123. STATUSES = ("draft", "est. steps", "unbuilt")
  124. ORDERS = ("curated", "sorted")
  125. MAX_DESC = 220
  126. MAX_TITLE = 80
  127. MAX_WHO = 80
  128. # A subgroup row in the sidebar holds at most this many links and this many characters of visible text.
  129. SIDEBAR_PACK_LINKS = 5
  130. SIDEBAR_PACK_CHARS = 170
  131. # The group the sidebar shows as a row of links across the top instead of a collapsible block.
  132. TOP_GROUP = "start"
  133. TOP_BAR_LABELS = {"Give-Feedback-and-Open-an-Issue": "Give feedback"}
  134. PAGE_NAME = re.compile(r"^[A-Za-z0-9_-]+$")
  135. GROUP_ID = re.compile(r"^[a-z][a-z0-9-]*$")
  136. URL = re.compile(r"^https://github\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/(blob|tree)/[A-Za-z0-9_./-]+$")
  137. FORBIDDEN_TEXT = ("|", "\n", "\r", "—", "–", "](", "<", ">", "`")
  138. # -- reading the manifest ---------------------------------------------------------------
  139. def load_manifest(text: str) -> dict:
  140. """Parse a manifest mapping. A repeated key in any mapping is an error, not a silent overwrite."""
  141. loaded = load_yaml_any(text)
  142. if not isinstance(loaded, dict):
  143. raise TypeError("the manifest must be a mapping with groups, pages and links")
  144. return loaded
  145. def load_yaml_any(text: str):
  146. """Strict, safe YAML parse (no Python tags, no repeated keys); returns whatever the document holds."""
  147. try:
  148. import yaml
  149. except ImportError as exc: # pragma: no cover - CI installs PyYAML
  150. raise RuntimeError("PyYAML is required to read docs/wiki/_nav/") from exc
  151. class Strict(yaml.SafeLoader):
  152. pass
  153. def construct(loader, node, deep=False):
  154. seen = set()
  155. for key_node, _ in node.value:
  156. key = loader.construct_object(key_node, deep=deep)
  157. if key in seen:
  158. raise ValueError(f"duplicate key {key!r} (line {key_node.start_mark.line + 1})")
  159. seen.add(key)
  160. return yaml.SafeLoader.construct_mapping(loader, node, deep=deep)
  161. Strict.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, construct)
  162. try:
  163. loaded = yaml.load(text, Loader=Strict) # a SafeLoader subclass: no Python tags
  164. except yaml.YAMLError as exc:
  165. raise ValueError(f"malformed YAML: {str(exc).splitlines()[0] if str(exc) else type(exc).__name__}") from exc
  166. return loaded
  167. def load_manifest_dir(directory: Path) -> dict:
  168. """Load docs/wiki/_nav/: index.yaml (groups, links, readers, goals) plus <group id>.yaml, a list of page entries.
  169. A group with no file has no pages; a file whose name is not a declared group id is an error, so a typo cannot
  170. drop pages silently. The result has the shape load_manifest gives for the old single file.
  171. """
  172. manifest = load_manifest((directory / "index.yaml").read_text(encoding="utf-8"))
  173. if "pages" in manifest:
  174. raise ValueError("index.yaml must not carry pages: they live in one <group id>.yaml file per group")
  175. ids = [g.get("id") for g in groups_of(manifest) if isinstance(g, dict)]
  176. files = {p.stem: p for p in directory.glob("*.yaml") if p.name != "index.yaml"}
  177. for stem in sorted(set(files) - set(ids)):
  178. raise ValueError(f"{stem}.yaml is not a declared group id in index.yaml")
  179. pages: dict[str, list] = {}
  180. for gid in ids:
  181. if gid in files:
  182. listed = load_yaml_any(files[gid].read_text(encoding="utf-8"))
  183. if listed is None:
  184. listed = []
  185. if not isinstance(listed, list):
  186. raise TypeError(f"{files[gid].name} must be a list of page entries")
  187. pages[gid] = listed
  188. manifest["pages"] = pages
  189. return manifest
  190. def groups_of(manifest: dict) -> list[dict]:
  191. return manifest.get("groups") or []
  192. def entries(manifest: dict, group_id: str) -> list[dict]:
  193. """The page entries of a group in display order (sorted groups are sorted here, too)."""
  194. group = next(g for g in groups_of(manifest) if g["id"] == group_id)
  195. found = list((manifest.get("pages") or {}).get(group_id) or [])
  196. if group.get("order") == "sorted":
  197. found.sort(key=lambda e: e["title"].casefold())
  198. return found
  199. def link_entries(manifest: dict, group_id: str) -> list[dict]:
  200. found = list((manifest.get("links") or {}).get(group_id) or [])
  201. found.sort(key=lambda e: e["title"].casefold())
  202. return found
  203. def all_page_names(manifest: dict) -> list[str]:
  204. names = []
  205. for pages in (manifest.get("pages") or {}).values():
  206. names.extend(e.get("page") for e in pages or [] if isinstance(e, dict))
  207. return names
  208. # -- checking the manifest --------------------------------------------------------------
  209. def _text_problems(where: str, label: str, value: object, limit: int) -> list[str]:
  210. if not isinstance(value, str) or not value.strip():
  211. return [f"{where}: {label} must be non-empty text"]
  212. out = []
  213. if len(value) > limit:
  214. out.append(f"{where}: {label} is {len(value)} characters, over {limit}")
  215. for bad in FORBIDDEN_TEXT:
  216. if bad in value:
  217. out.append(f"{where}: {label} contains {bad!r}, which breaks the generated Markdown or the style rules")
  218. if value != value.strip() or " " in value:
  219. out.append(f"{where}: {label} has stray spaces")
  220. return out
  221. def _reader_problems(readers: object, listed: set[str]) -> list[str]:
  222. """The optional `readers` list: one Start-here page per audience, every audience exactly once."""
  223. if readers is None:
  224. return []
  225. if not isinstance(readers, list):
  226. return ["readers: must be a list of {audience, who, page} entries"]
  227. problems: list[str] = []
  228. covered: list[str] = []
  229. for r in readers:
  230. if not isinstance(r, dict):
  231. problems.append(f"readers: entry {r!r} is not a mapping")
  232. continue
  233. where = f"readers.{r.get('audience')}"
  234. extra = set(r) - {"audience", "who", "page"}
  235. if extra:
  236. problems.append(f"{where}: unknown field(s) {sorted(extra)}")
  237. if r.get("audience") not in AUDIENCES:
  238. problems.append(f"{where}: audience {r.get('audience')!r} is not one of {AUDIENCES}")
  239. else:
  240. covered.append(r["audience"])
  241. problems += _text_problems(where, "who", r.get("who"), MAX_WHO)
  242. if r.get("page") not in listed:
  243. problems.append(f"{where}: page {r.get('page')!r} is not a page in the manifest")
  244. for a in sorted({a for a in covered if covered.count(a) > 1}):
  245. problems.append(f"readers: audience {a!r} is listed twice")
  246. for a in AUDIENCES:
  247. if a not in covered:
  248. problems.append(f"readers: no start page for audience {a!r}")
  249. return problems
  250. def _goal_problems(goals: object, listed: set[str]) -> list[str]:
  251. """The optional `goals` list (issue #416): a Start-here page per topic track or goal, no audience implied."""
  252. if goals is None:
  253. return []
  254. if not isinstance(goals, list):
  255. return ["goals: must be a list of {who, page} entries"]
  256. problems: list[str] = []
  257. seen_who: list[str] = []
  258. for r in goals:
  259. if not isinstance(r, dict):
  260. problems.append(f"goals: entry {r!r} is not a mapping")
  261. continue
  262. where = f"goals.{r.get('who')}"
  263. extra = set(r) - {"who", "page"}
  264. if extra:
  265. problems.append(f"{where}: unknown field(s) {sorted(extra)}")
  266. problems += _text_problems(where, "who", r.get("who"), MAX_WHO)
  267. if isinstance(r.get("who"), str):
  268. seen_who.append(r["who"])
  269. if r.get("page") not in listed:
  270. problems.append(f"{where}: page {r.get('page')!r} is not a page in the manifest")
  271. for w in sorted({w for w in seen_who if seen_who.count(w) > 1}):
  272. problems.append(f"goals: {w!r} is listed twice")
  273. return problems
  274. def _related_problems(where: str, page: object, related: object, listed: set[str]) -> list[str]:
  275. """The optional `related` list of a page (issue #417): RELATED_MIN to RELATED_MAX page names that exist, no
  276. link to the page itself, none twice."""
  277. if not isinstance(related, list) or not all(isinstance(r, str) for r in related):
  278. return [f"{where}: related must be a list of page names"]
  279. problems = []
  280. if not RELATED_MIN <= len(related) <= RELATED_MAX:
  281. problems.append(f"{where}: related has {len(related)} entries, it needs {RELATED_MIN} to {RELATED_MAX}")
  282. for r in related:
  283. if r == page:
  284. problems.append(f"{where}: related lists the page itself")
  285. elif r not in listed:
  286. problems.append(f"{where}: related page {r!r} is not a page in the manifest")
  287. for r in sorted({r for r in related if related.count(r) > 1}):
  288. problems.append(f"{where}: related lists {r!r} twice")
  289. return problems
  290. def _series_problems(manifest: dict) -> list[str]:
  291. """A series is one run of neighboring pages of ONE group, in display order (a sorted group is title-sorted):
  292. the sidebar folds it into a single line."""
  293. problems: list[str] = []
  294. home: dict[str, str] = {}
  295. sorted_ids = {g.get("id") for g in groups_of(manifest) if isinstance(g, dict) and g.get("order") == "sorted"}
  296. for gid, group_entries in (manifest.get("pages") or {}).items():
  297. previous = None
  298. closed: set[str] = set()
  299. shown = list(group_entries or [])
  300. if gid in sorted_ids and all(isinstance(e, dict) and isinstance(e.get("title"), str) for e in shown):
  301. shown.sort(key=lambda e: e["title"].casefold()) # the display order entries() gives, which the sidebar folds
  302. for e in shown:
  303. name = e.get("series") if isinstance(e, dict) else None
  304. name = name if isinstance(name, str) else None
  305. if name != previous and previous is not None:
  306. closed.add(previous)
  307. if name is not None:
  308. if home.setdefault(name, gid) != gid:
  309. problems.append(f"series {name!r} is in groups {home[name]} and {gid}; a series lives in one group")
  310. elif name in closed:
  311. problems.append(f"series {name!r} in group {gid} is not contiguous: its pages must follow one another")
  312. previous = name
  313. return problems
  314. def validate(manifest: dict, pages: set[str]) -> list[str]:
  315. """Problems with a manifest, given the page names that exist in docs/wiki (minus the special ones).
  316. Every page exactly once (no orphan, no duplicate), no entry for a missing page, known
  317. groups, audiences and statuses, and curated text that cannot break the Markdown."""
  318. problems: list[str] = []
  319. groups = groups_of(manifest)
  320. if not groups:
  321. return ["the manifest has no groups"]
  322. ids = []
  323. for g in groups:
  324. gid = g.get("id") if isinstance(g, dict) else None
  325. if not isinstance(gid, str) or not GROUP_ID.match(gid):
  326. problems.append(f"group {g!r}: id must be lower-case letters, digits and hyphens")
  327. continue
  328. if gid in ids:
  329. problems.append(f"group {gid}: declared twice")
  330. ids.append(gid)
  331. problems += _text_problems(f"group {gid}", "title", g.get("title"), MAX_TITLE)
  332. if g.get("order") not in ORDERS:
  333. problems.append(f"group {gid}: order must be one of {ORDERS}")
  334. if g.get("track") and (not g.get("numbered") or g.get("order") != "curated" or g.get("open")):
  335. problems.append(f"group {gid}: a topic track must be numbered, curated and closed by default")
  336. if TOP_GROUP not in ids:
  337. problems.append(f"the {TOP_GROUP!r} group is missing (the sidebar's top row comes from it)")
  338. opened = [g.get("id") for g in groups if g.get("open")]
  339. if opened != ["core"] and "core" in ids:
  340. problems.append("exactly the core group should be open by default in the sidebar")
  341. titles = [g.get("title") for g in groups]
  342. for t in sorted({t for t in titles if titles.count(t) > 1}, key=str):
  343. problems.append(f"two groups are both titled {t!r}")
  344. for section in ("pages", "links"):
  345. for gid in manifest.get(section) or {}:
  346. if gid not in ids:
  347. problems.append(f"{section}: group {gid!r} is not declared in groups")
  348. seen: dict[str, str] = {}
  349. for gid, group_entries in (manifest.get("pages") or {}).items():
  350. for e in group_entries or []:
  351. if not isinstance(e, dict):
  352. problems.append(f"pages.{gid}: entry {e!r} is not a mapping")
  353. continue
  354. name = e.get("page")
  355. where = f"pages.{gid}.{name}"
  356. extra = set(e) - {"page", "title", "audience", "status", "desc", "sidebar", "subgroup", "related", "series"}
  357. if extra:
  358. problems.append(f"{where}: unknown field(s) {sorted(extra)}")
  359. if not isinstance(name, str) or not PAGE_NAME.match(name):
  360. problems.append(f"pages.{gid}: bad page name {name!r}")
  361. continue
  362. if name in SPECIAL:
  363. problems.append(f"{where}: {name} is wiki chrome and is not listed")
  364. if name in seen:
  365. problems.append(f"{where}: listed twice (also in {seen[name]})")
  366. seen[name] = gid
  367. problems += _text_problems(where, "title", e.get("title"), MAX_TITLE)
  368. problems += _text_problems(where, "desc", e.get("desc"), MAX_DESC)
  369. if e.get("audience") not in AUDIENCES:
  370. problems.append(f"{where}: audience {e.get('audience')!r} is not one of {AUDIENCES}")
  371. if "status" in e and e["status"] not in STATUSES:
  372. problems.append(f"{where}: status {e['status']!r} is not one of {STATUSES}")
  373. if "sidebar" in e and not isinstance(e["sidebar"], bool):
  374. problems.append(f"{where}: sidebar must be true or false")
  375. if "series" in e:
  376. problems += _text_problems(where, "series", e["series"], MAX_TITLE)
  377. if "subgroup" in e:
  378. problems += _text_problems(where, "subgroup", e["subgroup"], MAX_TITLE)
  379. if gid == TOP_GROUP:
  380. problems.append(f"{where}: the {TOP_GROUP!r} group is the sidebar's top row and takes no subgroup")
  381. if any(g.get("id") == gid and g.get("numbered") and not g.get("track") for g in groups if isinstance(g, dict)):
  382. problems.append(f"{where}: a numbered group is a reading path and takes no subgroup")
  383. problems += _series_problems(manifest)
  384. for gid, group_links in (manifest.get("links") or {}).items():
  385. for e in group_links or []:
  386. where = f"links.{gid}.{(e or {}).get('title')}"
  387. if not isinstance(e, dict) or not isinstance(e.get("url"), str) or not URL.match(e["url"]):
  388. problems.append(f"{where}: url must be a github.com blob or tree link")
  389. continue
  390. problems += _text_problems(where, "title", e.get("title"), MAX_TITLE)
  391. problems += _text_problems(where, "desc", e.get("desc"), MAX_DESC)
  392. if e.get("audience") not in AUDIENCES:
  393. problems.append(f"{where}: audience {e.get('audience')!r} is not one of {AUDIENCES}")
  394. if "sidebar" in e and not isinstance(e["sidebar"], bool):
  395. problems.append(f"{where}: sidebar must be true or false")
  396. anchors: dict[str, str] = {}
  397. for g in groups:
  398. if isinstance(g, dict) and isinstance(g.get("title"), str) and isinstance(g.get("id"), str):
  399. anchor = slug(g["title"])
  400. if anchor in anchors:
  401. problems.append(f"groups {anchors[anchor]} and {g['id']} have the same Contents anchor #{anchor}")
  402. anchors.setdefault(anchor, g["id"])
  403. for group_entries in (manifest.get("pages") or {}).values():
  404. for e in group_entries or []:
  405. if isinstance(e, dict) and "related" in e:
  406. problems += _related_problems(f"pages.{e.get('page')}", e.get("page"), e["related"], set(seen))
  407. problems += _reader_problems(manifest.get("readers"), set(seen))
  408. problems += _goal_problems(manifest.get("goals"), set(seen))
  409. for name in sorted(pages - set(seen)):
  410. problems.append(f"orphan: {name}.md is a wiki page but has no manifest entry")
  411. for name in sorted(set(seen) - pages):
  412. problems.append(f"dead entry: {name} is in the manifest but docs/wiki/{name}.md does not exist")
  413. for g in groups:
  414. gid = g.get("id")
  415. if g.get("order") == "sorted":
  416. listed = [e.get("title") for e in (manifest.get("pages") or {}).get(gid) or [] if isinstance(e, dict)]
  417. if listed != sorted(listed, key=lambda t: str(t).casefold()):
  418. problems.append(f"group {gid}: entries are not in title order (it is a sorted group)")
  419. if g.get("numbered") and not (manifest.get("pages") or {}).get(gid):
  420. problems.append(f"group {gid}: numbered but empty")
  421. return problems
  422. # -- rendering --------------------------------------------------------------------------
  423. def slug(heading: str) -> str:
  424. """The anchor GitHub builds from a heading (the same rule tests/test_markdown_anchors.py uses)."""
  425. return re.sub(r"[^\w\- ]", "", heading.lower()).replace(" ", "-")
  426. def _suffix(entry: dict) -> str:
  427. return f" ({entry['status']})" if entry.get("status") else ""
  428. def _sidebar_item(entry: dict) -> str:
  429. if "url" in entry:
  430. return f"[{entry['title']}]({entry['url']})"
  431. return f"[{entry['title']}]({entry['page']}.md){_suffix(entry)}"
  432. def fold_series(pages: list[dict]) -> list[dict]:
  433. """Fold each run of pages sharing a `series` into one entry: the series name as the title, the first page as
  434. the link, pinned when any member is pinned. Pages with no series pass through. Only the sidebar folds; Contents,
  435. Home and the page navigation keep every page."""
  436. folded: list[dict] = []
  437. for e in pages:
  438. name = e.get("series")
  439. last = folded[-1] if folded else None
  440. if name and last is not None and last.get("series") == name and last.get("_folded"):
  441. if e.get("sidebar"):
  442. last["sidebar"] = True
  443. continue
  444. folded.append({**{k: v for k, v in e.items() if k != "status"}, "title": name, "_folded": True} if name else e)
  445. return folded
  446. def sidebar_entries(manifest: dict, group: dict) -> list[dict]:
  447. """The entries a group shows in the sidebar: see the module docstring for the rule."""
  448. gid = group["id"]
  449. pages, extra = entries(manifest, gid), link_entries(manifest, gid)
  450. everything = fold_series(pages) + extra
  451. if group.get("numbered") and not group.get("track"):
  452. return everything
  453. # Marked entries are pinned to the top; the rest follow. Both keep display order, nothing is dropped.
  454. return [e for e in everything if e.get("sidebar")] + [e for e in everything if not e.get("sidebar")]
  455. def _pack(members: list[dict]) -> list[str]:
  456. """Pack links into rows joined by " · ": at most SIDEBAR_PACK_LINKS links and SIDEBAR_PACK_CHARS
  457. characters of visible text (titles, status suffixes and separators) per row; order is kept."""
  458. rows: list[list[str]] = []
  459. widths: list[int] = []
  460. for e in members:
  461. item = _sidebar_item(e)
  462. visible = len(e["title"]) + (0 if "url" in e else len(_suffix(e)))
  463. if rows and len(rows[-1]) < SIDEBAR_PACK_LINKS and widths[-1] + 3 + visible <= SIDEBAR_PACK_CHARS:
  464. rows[-1].append(item)
  465. widths[-1] += 3 + visible
  466. else:
  467. rows.append([item])
  468. widths.append(visible)
  469. return [" · ".join(row) for row in rows]
  470. def render_sidebar(manifest: dict) -> str:
  471. # Line-saving layout (the budget is a test): the <summary> shares its line with <details>, no
  472. # blank line between groups, none before </details>. A blank line is kept after each summary
  473. # because Markdown inside an HTML block needs it, and between the top row and the first group.
  474. # A page with a `subgroup` goes into a nested <details> whose rows pack several links each.
  475. lines = [
  476. "<!-- GENERATED from docs/wiki/_nav.yaml by scripts/gen_wiki_nav.py. Do not edit this",
  477. "file by hand: add the page to the manifest and re-run the script. CI fails when this",
  478. "file does not match the manifest. -->",
  479. "",
  480. ]
  481. top = entries(manifest, TOP_GROUP)
  482. lines.append(" | ".join(f"**[{TOP_BAR_LABELS.get(e['page'], e['title'])}]({e['page']}.md)**" for e in top))
  483. lines.append("")
  484. for group in groups_of(manifest):
  485. if group["id"] == TOP_GROUP:
  486. continue
  487. count = len(entries(manifest, group["id"])) + len(link_entries(manifest, group["id"]))
  488. opener = "<details open>" if group.get("open") else "<details>"
  489. lines += [f"{opener}<summary><b>{group['title']}</b> ({count})</summary>", ""]
  490. shown = sidebar_entries(manifest, group)
  491. flat = [e for e in shown if not e.get("subgroup")]
  492. for number, e in enumerate(flat, start=1):
  493. numbered = group.get("numbered") and not group.get("track") and "url" not in e
  494. lines.append(f"{f'{number}.' if numbered else '-'} {_sidebar_item(e)}")
  495. subgroups: dict[str, list[dict]] = {}
  496. for e in shown:
  497. if e.get("subgroup"):
  498. subgroups.setdefault(e["subgroup"], []).append(e)
  499. for title, members in subgroups.items():
  500. lines += [f"<details><summary>{title} ({len(members)})</summary>", ""]
  501. lines += [f"- {row}" for row in _pack(members)]
  502. lines.append("</details>")
  503. if subgroups:
  504. lines.append("") # an HTML block runs to the next blank line, so the Full list link needs one before it
  505. lines.append(f"- [Full list ({count})](Contents.md#{slug(group['title'])})")
  506. lines.append("</details>")
  507. return "\n".join(lines) + "\n"
  508. def render_home_map(manifest: dict) -> str:
  509. """The generated block of Home.md, markers included: a Start-here line per kind of reader, then
  510. every page grouped like Contents with its one-line description (and status marker)."""
  511. groups = groups_of(manifest)
  512. total = sum(len(entries(manifest, g["id"])) for g in groups)
  513. titles = {e["page"]: e["title"] for g in groups for e in entries(manifest, g["id"])}
  514. out = [
  515. HOME_BEGIN,
  516. "",
  517. "## Every page, by theme",
  518. "",
  519. (
  520. f"All {total} pages of this wiki, grouped the way [Contents](Contents.md) groups them, with one line on what "
  521. "each is for. Pages marked draft, est. steps or unbuilt say so in their own banner; "
  522. "[Contents](Contents.md) explains the markers."
  523. ),
  524. ]
  525. readers = manifest.get("readers") or []
  526. if readers:
  527. out += ["", "### Start here, by kind of reader", ""]
  528. out += [f"- **{r['who']}**: [{titles[r['page']]}]({r['page']}.md)" for r in readers]
  529. goals = manifest.get("goals") or []
  530. if goals:
  531. out += ["", "### Start here, by topic track and by goal", ""]
  532. out += [f"- **{r['who']}**: [{titles[r['page']]}]({r['page']}.md)" for r in goals]
  533. for g in groups:
  534. pages, extra = entries(manifest, g["id"]), link_entries(manifest, g["id"])
  535. out += ["", f"### {g['title']}", ""]
  536. for number, e in enumerate(pages, start=1):
  537. bullet = f"{number}." if g.get("numbered") else "-"
  538. out.append(f"{bullet} [{e['title']}]({e['page']}.md){_suffix(e)}: {e['desc']}")
  539. out += [f"- [{e['title']}]({e['url']}): {e['desc']}" for e in extra]
  540. out += ["", HOME_END]
  541. return "\n".join(out)
  542. def apply_home_map(text: str, block: str) -> str:
  543. """Replace the block between the markers of a Home.md text; refuse a text without exactly one ordered pair."""
  544. if text.count(HOME_BEGIN) != 1 or text.count(HOME_END) != 1:
  545. raise ValueError("Home.md needs exactly one BEGIN and one END page-map marker line")
  546. start, end = text.index(HOME_BEGIN), text.index(HOME_END)
  547. if end < start:
  548. raise ValueError("the END page-map marker comes before the BEGIN marker in Home.md")
  549. return text[:start] + block + text[end + len(HOME_END):]
  550. def _row(cells: list[str]) -> str:
  551. return "| " + " | ".join(cells) + " |"
  552. def render_contents(manifest: dict) -> str:
  553. groups = groups_of(manifest)
  554. total = sum(len(entries(manifest, g["id"])) for g in groups)
  555. out = [
  556. "<!-- GENERATED from docs/wiki/_nav.yaml by scripts/gen_wiki_nav.py. Do not edit this",
  557. "page by hand: add the page to the manifest and re-run the script. CI fails when this",
  558. "page does not match the manifest. -->",
  559. "",
  560. "# Contents",
  561. "",
  562. "> Unfamiliar word or acronym? The [Glossary](Glossary.md) defines it.",
  563. "",
  564. (
  565. f"Every page of this wiki appears here once ({total} pages), grouped by theme, with a line on what it is for "
  566. "and who it is for. If you do not know where to begin, take the numbered core path; "
  567. "[Reading order](Reading-Order.md) has the same pages with time estimates and checkpoints, "
  568. "and [Start here if you are new](Start-Here-If-You-Are-New.md) is the gentlest first page."
  569. ),
  570. "",
  571. "Some pages carry a status marker, copied from the page's own banner:",
  572. "",
  573. "- **draft**: the page calls itself an unverified draft.",
  574. "- **est. steps**: the page was written from reading, and its steps were not run.",
  575. "- **unbuilt**: the page describes something that is not built or not applied yet.",
  576. "",
  577. "A page with no marker has no such banner. It may still say what was and was not run, so read its status note.",
  578. "",
  579. "## Groups",
  580. "",
  581. ]
  582. for g in groups:
  583. n = len(entries(manifest, g["id"])) + len(link_entries(manifest, g["id"]))
  584. out.append(f"- [{g['title']}](#{slug(g['title'])}) ({n})")
  585. for g in groups:
  586. pages = entries(manifest, g["id"])
  587. extra = link_entries(manifest, g["id"])
  588. numbered = bool(g.get("numbered"))
  589. out += ["", f"## {g['title']}", ""]
  590. head = (["Step"] if numbered else []) + ["Page", "What it is for and who it is for", "Audience", "Status"]
  591. out.append(_row(head))
  592. out.append(_row(["---"] * len(head)))
  593. for number, e in enumerate(pages, start=1):
  594. cells = ([str(number)] if numbered else []) + [
  595. f"[{e['title']}]({e['page']}.md)", e["desc"], e["audience"], e.get("status", ""),
  596. ]
  597. out.append(_row(cells))
  598. for e in extra:
  599. cells = ([""] if numbered else []) + [f"[{e['title']}]({e['url']})", e["desc"], e["audience"], ""]
  600. out.append(_row(cells))
  601. return "\n".join(out) + "\n"
  602. # -- the per-page navigation blocks (issue #417) ----------------------------------------
  603. def has_reading_order(group: dict) -> bool:
  604. """A numbered group (the core path, a track) or a sorted one has a reading order; the start group and
  605. the curated, unnumbered tools group do not, so their pages get a breadcrumb and no previous or next."""
  606. return bool(group.get("numbered")) or group.get("order") == "sorted"
  607. def page_home(manifest: dict) -> dict[str, tuple[dict, list[dict], int]]:
  608. """Each page name -> (its group, the group's entries in display order, its index in them)."""
  609. found = {}
  610. for g in groups_of(manifest):
  611. ordered = entries(manifest, g["id"])
  612. for i, e in enumerate(ordered):
  613. found[e["page"]] = (g, ordered, i)
  614. return found
  615. def related_for(manifest: dict, page: str) -> list[str]:
  616. """The pages a page shows as Related: its own `related:` list, else the fallback rule.
  617. Fallback (deterministic, documented in the manifest header): up to RELATED_FALLBACK other pages of the
  618. same group, leaving out the previous and next page (they are shown beside it), taking first the pages of
  619. the same subgroup and then the rest, each nearest first by distance in the group's order, earlier before later."""
  620. home = page_home(manifest)
  621. group, ordered, index = home[page]
  622. own = ordered[index]
  623. if "related" in own:
  624. return list(own["related"])
  625. skip = {page}
  626. if has_reading_order(group):
  627. skip |= {ordered[j]["page"] for j in (index - 1, index + 1) if 0 <= j < len(ordered)}
  628. candidates = [(j, e) for j, e in enumerate(ordered) if e["page"] not in skip]
  629. candidates.sort(key=lambda je: (je[1].get("subgroup") != own.get("subgroup"), abs(je[0] - index), je[0]))
  630. return [e["page"] for _, e in candidates[:RELATED_FALLBACK]]
  631. def _link(entry: dict) -> str:
  632. return f"[{entry['title']}]({entry['page']}.md)"
  633. def _neighbors(group: dict, ordered: list[dict], index: int) -> str:
  634. if not has_reading_order(group):
  635. return ""
  636. parts = []
  637. if index > 0:
  638. parts.append(f"Previous: {_link(ordered[index - 1])}")
  639. if index + 1 < len(ordered):
  640. parts.append(f"Next: {_link(ordered[index + 1])}")
  641. return " / ".join(parts)
  642. def _wrap(where: str, body: list[str]) -> str:
  643. return "\n".join([NAV_BEGIN.format(where=where), *body, NAV_END.format(where=where)])
  644. def render_page_nav(manifest: dict, page: str) -> dict[str, str]:
  645. """The two generated blocks of one page, markers included: {"top": ..., "bottom": ...}."""
  646. group, ordered, index = page_home(manifest)[page]
  647. me = ordered[index]
  648. crumb = f"[Home](Home.md) > [{group['title']}](Contents.md#{slug(group['title'])}) > {me['title']}"
  649. neighbors = _neighbors(group, ordered, index)
  650. top = [crumb] + (["", neighbors] if neighbors else [])
  651. kind = "track" if group.get("track") or group.get("id") == "core" else "group"
  652. bottom = [f"Where you are: {crumb}"]
  653. if neighbors:
  654. bottom += ["", neighbors]
  655. plain = [e for e in ordered if not e.get("subgroup")]
  656. subgroups: dict[str, list[dict]] = {}
  657. for e in ordered:
  658. if e.get("subgroup"):
  659. subgroups.setdefault(e["subgroup"], []).append(e)
  660. def shown(e: dict) -> str:
  661. return f"**{e['title']}**" if e["page"] == page else _link(e)
  662. bottom += ["", f"In this {kind}: [{group['title']}](Contents.md#{slug(group['title'])}), {len(ordered)} pages", ""]
  663. if plain:
  664. label = "Also here: " if subgroups else ""
  665. bottom.append(f"- {label}{' / '.join(shown(e) for e in plain)}")
  666. for title, members in subgroups.items():
  667. bottom.append(f"- {title}: {' / '.join(shown(e) for e in members)}")
  668. titles = {e["page"]: e["title"] for g in groups_of(manifest) for e in entries(manifest, g["id"])}
  669. related = related_for(manifest, page)
  670. if related:
  671. bottom += ["", "Related pages:", ""]
  672. bottom += [f"- [{titles[r]}]({r}.md)" for r in related]
  673. return {"top": _wrap("top", top), "bottom": _wrap("bottom", bottom)}
  674. def has_page_nav(name: str, text: str) -> bool:
  675. """Does this page carry the generated blocks? Not Home, Contents or a page another generator writes whole."""
  676. return name not in NAV_EXEMPT and name not in SPECIAL and not text.startswith(GENERATED_PAGE_START)
  677. def _top_insertion_point(lines: list[str]) -> int:
  678. """The line index where the top block goes: after the first heading and after any leading blockquote
  679. paragraphs (the status banner, the glossary line, the prerequisites line), so a banner stays where it is."""
  680. i = 1
  681. while i < len(lines):
  682. if not lines[i].strip():
  683. i += 1
  684. elif lines[i].startswith(">"):
  685. while i < len(lines) and lines[i].startswith(">"):
  686. i += 1
  687. else:
  688. break
  689. return i
  690. def apply_page_nav(text: str, blocks: dict[str, str]) -> str:
  691. """Swap the two blocks of a page text for new ones; a text with no markers gets them inserted once
  692. (top after the heading and the leading banner quotes, bottom at the end). Anything else is an error."""
  693. begins = {w: NAV_BEGIN.format(where=w) for w in NAV_PLACES}
  694. ends = {w: NAV_END.format(where=w) for w in NAV_PLACES}
  695. counts = [text.count(begins[w]) for w in NAV_PLACES] + [text.count(ends[w]) for w in NAV_PLACES]
  696. if counts == [0, 0, 0, 0]:
  697. lines = text.split("\n")
  698. if not lines or not lines[0].startswith("# "):
  699. raise ValueError("the page does not begin with a first-level heading, so the top block has no place")
  700. at = _top_insertion_point(lines)
  701. before, after = "\n".join(lines[:at]).rstrip("\n"), "\n".join(lines[at:]).strip("\n")
  702. top_half = f"{before}\n\n{blocks['top']}\n" + (f"\n{after}" if after else "")
  703. return top_half.rstrip("\n") + f"\n\n{blocks['bottom']}\n"
  704. if counts != [1, 1, 1, 1]:
  705. raise ValueError("a page needs exactly one BEGIN and one END marker line for each of its top and bottom page-nav blocks")
  706. out = text
  707. for w in NAV_PLACES:
  708. start, end = out.index(begins[w]), out.index(ends[w])
  709. if end < start:
  710. raise ValueError(f"the END page-nav {w} marker comes before its BEGIN marker")
  711. out = out[:start] + blocks[w] + out[end + len(ends[w]):]
  712. if out.index(begins["top"]) > out.index(begins["bottom"]):
  713. raise ValueError("the top page-nav block comes after the bottom one")
  714. return out
  715. def _strip_block(text: str, begin: str, end: str) -> str:
  716. """The text without every block between a BEGIN and an END line, and the blank line each leaves behind."""
  717. while begin in text and end in text:
  718. start, stop = text.index(begin), text.index(end) + len(end)
  719. text = text[:start].rstrip("\n") + ("\n\n" if text[stop:].strip("\n") and text[:start].strip("\n") else "\n") + text[stop:].lstrip("\n")
  720. return text
  721. def strip_page_nav(text: str) -> str:
  722. """The page text without the generated navigation blocks and the blank line each leaves behind (for tests that
  723. count links or look at the top of a page: the block is navigation, not content)."""
  724. for w in NAV_PLACES:
  725. text = _strip_block(text, NAV_BEGIN.format(where=w), NAV_END.format(where=w))
  726. return text
  727. def strip_page_contents(text: str) -> str:
  728. """The page text without the generated contents block (issue #441) and the blank line it leaves behind."""
  729. return _strip_block(text, TOC_BEGIN, TOC_END)
  730. def strip_generated(text: str) -> str:
  731. """The author's text: both navigation blocks and the contents block taken out. This is what tests/wikitext.py
  732. page_text() returns, and what the contents block's threshold and headings are read from."""
  733. return strip_page_contents(strip_page_nav(text))
  734. # -- the per-page contents block (issue #441) -----------------------------------------------
  735. HEADING_LINE = re.compile(r"^ {0,3}(#{1,6})(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$")
  736. FENCE_OPEN = re.compile(r"^\s*(`{3,}|~{3,})")
  737. MD_IMAGE = re.compile(r"!\[([^\]]*)\]\([^)]*\)")
  738. MD_LINK = re.compile(r"\[([^\]]*)\]\([^)]*\)")
  739. HTML_TAG = re.compile(r"</?[A-Za-z][^>]*>")
  740. def _plain_heading(heading: str) -> str:
  741. """A heading's text as it reads rendered: images and links reduced to their text, HTML tags dropped,
  742. entities decoded. Emphasis and code markers stay (the slugger drops them as punctuation)."""
  743. text = MD_IMAGE.sub(r"\1", heading)
  744. text = MD_LINK.sub(r"\1", text)
  745. return html.unescape(HTML_TAG.sub("", text))
  746. def heading_slug(heading: str) -> str:
  747. """The anchor GitHub builds from one heading: lower case, then everything dropped that is not a letter,
  748. mark, number, connector (underscore), hyphen or space, then each space becomes a hyphen. Two spaces make
  749. two hyphens ("Tom & Jerry" is tom--jerry), trailing punctuation just goes. The -1, -2 suffix for a repeat is
  750. added by page_headings, which sees the whole page."""
  751. kept = [
  752. c for c in _plain_heading(heading).lower()
  753. if c in "- " or unicodedata.category(c)[0] in "LMN" or unicodedata.category(c) == "Pc"
  754. ]
  755. return "".join(kept).replace(" ", "-")
  756. def page_headings(text: str) -> list[tuple[int, str, str]]:
  757. """Every heading of a page text as (level, raw text, anchor), in order. Lines inside a code fence (backticks
  758. or tildes, closed by a fence of the same kind at least as long) are not headings, and neither is a line
  759. that is indented four spaces or has no space after the hashes. A repeated anchor gets -1, -2, ... and, as
  760. on GitHub, a suffixed anchor that is itself taken moves on to the next number."""
  761. found: list[tuple[int, str, str]] = []
  762. taken: dict[str, int] = {}
  763. fence: str | None = None
  764. for line in text.split("\n"):
  765. opening = FENCE_OPEN.match(line)
  766. if fence is not None:
  767. if opening and opening.group(1)[0] == fence[0] and len(opening.group(1)) >= len(fence) and not line.strip().strip(fence[0]):
  768. fence = None
  769. continue
  770. if opening:
  771. fence = opening.group(1)
  772. continue
  773. m = HEADING_LINE.match(line)
  774. if not m or not (m.group(2) or "").strip():
  775. continue
  776. base = heading_slug(m.group(2))
  777. anchor = base
  778. while anchor in taken:
  779. taken[base] = taken.get(base, 0) + 1
  780. anchor = f"{base}-{taken[base]}"
  781. taken[anchor] = 0
  782. found.append((len(m.group(1)), m.group(2).strip(), anchor))
  783. return found
  784. def _contents_text(heading: str) -> str:
  785. """The link text for a heading: links and images reduced to their text, stray brackets dropped."""
  786. return re.sub(r"\s+", " ", _plain_heading(heading).replace("[", "").replace("]", "")).strip()
  787. def render_page_contents(text: str) -> str | None:
  788. """The contents block of a page, markers included, or None when the page gets none.
  789. A page gets one when its author text (the generated blocks taken out) is over TOC_MIN_LINES lines. It lists
  790. the `##` headings in order, each a link to its anchor. When the page has fewer than TOC_SUBHEADINGS_BELOW
  791. `##` headings it also lists its `###` headings, nested one step under the `##` heading above (or at the top
  792. level when there is none yet): a long page with few sections needs the finer list. Deeper levels and the
  793. page title are never listed. The block adds no heading (a bold label and a list, like the navigation
  794. blocks), so the page's heading levels and its tables are unchanged."""
  795. author = strip_generated(text)
  796. if len(author.splitlines()) <= TOC_MIN_LINES:
  797. return None
  798. headings = page_headings(author)
  799. levels = (2,) if sum(1 for lvl, _, _ in headings if lvl == 2) >= TOC_SUBHEADINGS_BELOW else (2, 3)
  800. lines = []
  801. seen_second = False
  802. for level, raw, anchor in headings:
  803. if level not in levels:
  804. continue
  805. nested = level == 3 and seen_second
  806. seen_second = seen_second or level == 2
  807. label = _contents_text(raw) or anchor
  808. lines.append(f"{' ' if nested else ''}- [{label}](#{anchor})")
  809. if not lines:
  810. return None
  811. return "\n".join([TOC_BEGIN, TOC_LABEL, "", *lines, TOC_END])
  812. def _insert_after_banners(text: str, block: str) -> str:
  813. """Put a block right after the first heading and the leading quote banners, with a blank line each side."""
  814. lines = text.split("\n")
  815. if not lines or not lines[0].startswith("# "):
  816. raise ValueError("the page does not begin with a first-level heading, so the block has no place")
  817. at = _top_insertion_point(lines)
  818. before, after = "\n".join(lines[:at]).rstrip("\n"), "\n".join(lines[at:]).strip("\n")
  819. return (f"{before}\n\n{block}\n" + (f"\n{after}" if after else "")).rstrip("\n") + "\n"
  820. def apply_page_contents(text: str, block: str | None) -> str:
  821. """Put the contents block into a page text: inserted after the first heading and the leading quote banners when
  822. the page has none yet, rewritten in place when it has one, removed when `block` is None. A page with a broken,
  823. repeated or reversed marker is an error, not a guess."""
  824. begins, ends = text.count(TOC_BEGIN), text.count(TOC_END)
  825. if (begins, ends) not in ((0, 0), (1, 1)):
  826. raise ValueError("a page needs exactly one BEGIN and one END marker line for its page-contents block, or none")
  827. if begins == 0:
  828. return text if block is None else _insert_after_banners(text, block)
  829. start, stop = text.index(TOC_BEGIN), text.index(TOC_END) + len(TOC_END)
  830. if stop - len(TOC_END) < start:
  831. raise ValueError("the END page-contents marker comes before its BEGIN marker")
  832. if block is None:
  833. return text[:start].rstrip("\n") + text[stop:]
  834. return text[:start] + block + text[stop:]
  835. # -- files ------------------------------------------------------------------------------
  836. def wiki_pages(root: Path) -> set[str]:
  837. return {p.stem for p in (root / WIKI).glob("*.md")} - SPECIAL
  838. def read_manifest(root: Path) -> dict:
  839. """The manifest of a tree: docs/wiki/_nav/ when it exists, else the old single docs/wiki/_nav.yaml."""
  840. directory = root / MANIFEST
  841. if directory.is_dir():
  842. return load_manifest_dir(directory)
  843. return load_manifest((root / LEGACY_MANIFEST).read_text(encoding="utf-8"))
  844. def check(root: Path) -> list[str]:
  845. """Every reason the manifest or the two generated files are not in order (empty when all is well)."""
  846. try:
  847. manifest = read_manifest(root)
  848. except (OSError, ValueError, TypeError, RuntimeError) as exc:
  849. return [f"cannot read {MANIFEST}: {exc}"]
  850. problems = validate(manifest, wiki_pages(root))
  851. if problems:
  852. return problems
  853. for path, render in ((CONTENTS, render_contents), (SIDEBAR, render_sidebar)):
  854. try:
  855. current = (root / path).read_text(encoding="utf-8")
  856. except OSError:
  857. problems.append(f"{path} is missing")
  858. continue
  859. if current != render(manifest):
  860. problems.append(f"{path} does not match {MANIFEST}")
  861. try:
  862. home = (root / HOME).read_text(encoding="utf-8")
  863. if home != apply_home_map(home, render_home_map(manifest)):
  864. problems.append(f"the page map in {HOME} does not match {MANIFEST}")
  865. except OSError:
  866. problems.append(f"{HOME} is missing")
  867. except ValueError as exc:
  868. problems.append(f"{HOME}: {exc}")
  869. for name, path, current, wanted in page_contents_plan(root, manifest, problems):
  870. if has_nav_blocks(current):
  871. problems.append(f"{path} carries a generated navigation block; the publish step writes those now (run scripts/gen_wiki_nav.py to remove it)")
  872. elif current != wanted:
  873. problems.append(f"the page contents block in {path} does not match the page")
  874. return problems
  875. def has_nav_blocks(text: str) -> bool:
  876. return any(NAV_BEGIN.format(where=w) in text or NAV_END.format(where=w) in text for w in NAV_PLACES)
  877. def page_contents_plan(root: Path, manifest: dict, problems: list[str]) -> list[tuple[str, Path, str, str]]:
  878. """For every page that takes generated blocks: (name, path, text now, text as it should be in the repository).
  879. The repository text carries the contents block only; any navigation block left over from before issue #521 is
  880. taken out. A page that cannot take its blocks, in the repository or when published, is reported in `problems`
  881. and left out."""
  882. plan = []
  883. for name in sorted(wiki_pages(root)):
  884. path = WIKI / f"{name}.md"
  885. try:
  886. current = (root / path).read_text(encoding="utf-8")
  887. except OSError:
  888. problems.append(f"{path} is missing")
  889. continue
  890. if not has_page_nav(name, current):
  891. continue
  892. try:
  893. wanted = strip_page_nav(current)
  894. wanted = apply_page_contents(wanted, render_page_contents(wanted))
  895. render_published_page(manifest, name, wanted) # the publish step must be able to take it, too
  896. except ValueError as exc:
  897. problems.append(f"{path}: {exc}")
  898. continue
  899. plan.append((name, path, current, wanted))
  900. return plan
  901. def render_published_page(manifest: dict, name: str, text: str) -> str:
  902. """A page as the wiki shows it: the repository text with the two navigation blocks added (issue #521)."""
  903. if not has_page_nav(name, text):
  904. return text
  905. return apply_page_nav(text, render_page_nav(manifest, name))
  906. def publish_pages(root: Path, out: Path) -> int:
  907. """Write every docs/wiki page, with its navigation blocks, into `out` (made if missing). Returns the page count."""
  908. manifest = read_manifest(root)
  909. problems = validate(manifest, wiki_pages(root))
  910. if problems:
  911. raise ValueError("; ".join(problems))
  912. out.mkdir(parents=True, exist_ok=True)
  913. count = 0
  914. for name in sorted(wiki_pages(root) | SPECIAL):
  915. source = root / WIKI / f"{name}.md"
  916. if not source.is_file():
  917. continue
  918. rendered = render_published_page(manifest, name, source.read_text(encoding="utf-8"))
  919. (out / f"{name}.md").write_text(rendered, encoding="utf-8")
  920. count += 1
  921. return count
  922. def main(argv: list[str] | None = None) -> int:
  923. parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
  924. parser.add_argument("--check", action="store_true", help="offline: fail when a generated file is stale")
  925. parser.add_argument("--publish-to", metavar="DIR", help="write every page with its navigation blocks into DIR (the wiki publish step)")
  926. parser.add_argument("--root", default=str(ROOT), help="repository root")
  927. args = parser.parse_args(argv)
  928. root = Path(args.root)
  929. if args.publish_to:
  930. try:
  931. count = publish_pages(root, Path(args.publish_to))
  932. except RuntimeError as exc:
  933. print(f"gen_wiki_nav: {exc}", file=sys.stderr)
  934. return 2
  935. except (OSError, ValueError, TypeError) as exc:
  936. print(f"gen_wiki_nav: cannot publish: {exc}", file=sys.stderr)
  937. return 1
  938. print(f"gen_wiki_nav: wrote {count} pages with their navigation blocks to {args.publish_to}")
  939. return 0
  940. if args.check:
  941. problems = check(root)
  942. if problems:
  943. for p in problems:
  944. print(f"gen_wiki_nav: {p}", file=sys.stderr)
  945. print("gen_wiki_nav: fix the manifest, then re-render with: python -I scripts/gen_wiki_nav.py", file=sys.stderr)
  946. return 1
  947. print(f"gen_wiki_nav: {CONTENTS}, {SIDEBAR}, the {HOME} page map and every page's contents block match {MANIFEST}, and no page file carries a navigation block")
  948. return 0
  949. try:
  950. manifest = read_manifest(root)
  951. except RuntimeError as exc:
  952. print(f"gen_wiki_nav: {exc}", file=sys.stderr)
  953. return 2
  954. except (OSError, ValueError, TypeError) as exc:
  955. print(f"gen_wiki_nav: cannot read {MANIFEST}: {exc}", file=sys.stderr)
  956. return 1
  957. problems = validate(manifest, wiki_pages(root) | {"Contents"})
  958. if problems:
  959. for p in problems:
  960. print(f"gen_wiki_nav: {p}", file=sys.stderr)
  961. return 1
  962. try: # build Home first: a Home without its markers must stop the run before anything is written
  963. home = apply_home_map((root / HOME).read_text(encoding="utf-8"), render_home_map(manifest))
  964. except (OSError, ValueError) as exc:
  965. print(f"gen_wiki_nav: {HOME}: {exc}", file=sys.stderr)
  966. return 1
  967. nav_problems: list[str] = []
  968. plan = page_contents_plan(root, manifest, nav_problems)
  969. if nav_problems: # a page that cannot take its blocks stops the run before anything is written
  970. for p in nav_problems:
  971. print(f"gen_wiki_nav: {p}", file=sys.stderr)
  972. return 1
  973. (root / CONTENTS).write_text(render_contents(manifest), encoding="utf-8")
  974. (root / SIDEBAR).write_text(render_sidebar(manifest), encoding="utf-8")
  975. (root / HOME).write_text(home, encoding="utf-8")
  976. changed = 0
  977. for _, path, current, wanted in plan:
  978. if current != wanted:
  979. (root / path).write_text(wanted, encoding="utf-8")
  980. changed += 1
  981. with_contents = sum(1 for _, _, _, wanted in plan if TOC_BEGIN in wanted)
  982. print(
  983. f"gen_wiki_nav: wrote {CONTENTS}, {SIDEBAR}, the page map in {HOME} and the contents blocks of {len(plan)} pages "
  984. f"({with_contents} with a contents block, {changed} changed)"
  985. )
  986. return 0
  987. if __name__ == "__main__":
  988. sys.exit(main())