askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
sync_app_docs.py · 8.3 KB · 202 lines
| 1 | #!/usr/bin/env python3 |
| 2 | """Regenerate the public /docs pages (packages/app-docs) from docs/. |
| 3 | |
| 4 | packages/app-docs/seed/doc_pages.tsv ships one record per guide. Each |
| 5 | record's `content` is a generated copy of a file under docs/; its `id`, |
| 6 | `title`, `category`, `nav_order` and `summary` are written by hand in the TSV |
| 7 | and are left alone. Never edit `content` by hand: edit the file under docs/ |
| 8 | and run this script. tests/test_app_docs_seed_sync.py fails while the two |
| 9 | differ. |
| 10 | |
| 11 | python scripts/sync_app_docs.py # rewrite the seed from docs/ |
| 12 | python scripts/sync_app_docs.py --check # exit 1 and name the pages that differ |
| 13 | |
| 14 | What a page's copy changes, in this order: |
| 15 | |
| 16 | 1. The first line (the `# Title`) and the blank line after it are dropped: |
| 17 | the page template prints the record's title itself. |
| 18 | 2. A link to another docs/ file becomes a link to its page |
| 19 | (`[x](site-routing.md#hosts)` to `[x](/docs/site-routing#hosts)`). A link |
| 20 | to a file that has no page (README.md, a doc that is not seeded) keeps its |
| 21 | words and loses the link. |
| 22 | 3. The package may not name the organisation that hosts the repository |
| 23 | (tests/test_app_docs_package.py bans those names), so the clone address |
| 24 | becomes `<repository-url>`, links to that organisation keep only their |
| 25 | words, and the sentences listed in REWORDED are swapped for neutral ones. |
| 26 | A REWORDED entry whose text is no longer in its docs/ file is an error, so |
| 27 | the list cannot rot. |
| 28 | 4. The result is refused if it still holds a banned name, a raw `.md)` link |
| 29 | or a link to a page that is not seeded. Add a REWORDED entry or fix docs/. |
| 30 | |
| 31 | To add a page: add its row to the TSV (any `content`), add it to DOC_FILES if |
| 32 | its docs/ file is not `<id>.md`, and run the script. After a change, bump |
| 33 | `version` in packages/app-docs/dbbasic-package.json so installs pick it up. |
| 34 | |
| 35 | Standard library only. |
| 36 | """ |
| 37 | |
| 38 | from __future__ import annotations |
| 39 | |
| 40 | import argparse |
| 41 | import csv |
| 42 | import io |
| 43 | import re |
| 44 | import sys |
| 45 | from pathlib import Path |
| 46 | |
| 47 | REPO = Path(__file__).resolve().parents[1] |
| 48 | DOCS = REPO / "docs" |
| 49 | SEED = REPO / "packages" / "app-docs" / "seed" / "doc_pages.tsv" |
| 50 | |
| 51 | # page id -> docs/ file stem, where the two differ |
| 52 | DOC_FILES = { |
| 53 | "why": "why-dbbasic", |
| 54 | "append-only-storage": "append-only-storage-design", |
| 55 | "per-tenant-storage": "per-tenant-storage-direction", |
| 56 | } |
| 57 | |
| 58 | REPOSITORY_URL = "https://github.com/askrobots/dbbasic-object-server.git" |
| 59 | PLACEHOLDER = "<repository-url>" |
| 60 | ORG_LINK = re.compile(r"\[([^\]\n]+)\]\(https://github\.com/askrobots/[^)\s]*\)") |
| 61 | # the same names tests/test_app_docs_package.py refuses anywhere in the package |
| 62 | BANNED = re.compile(r"\bq9\b|askrobots|\bwold\b", re.IGNORECASE) |
| 63 | |
| 64 | # page id -> (text in docs/, text on the page). Exact strings; each must be found. |
| 65 | REWORDED = { |
| 66 | "comparisons": [ |
| 67 | ("A q9-scale Django app ran", "A large Django app ran"), |
| 68 | ], |
| 69 | "design-system": [ |
| 70 | ("predecessor (q9) paired", "predecessor paired"), |
| 71 | ("the palette q9 already established", "the palette an earlier project already established"), |
| 72 | ("the successor to q9's `django_tables2`", "the successor to an earlier project's `django_tables2`"), |
| 73 | ("is the next build. q9's honest lesson", "is the next build. The earlier project's honest lesson"), |
| 74 | ("q9 itself shipped", "an earlier project itself shipped"), |
| 75 | ("why q9 accumulated", "why that earlier project accumulated"), |
| 76 | ("form engine. q9 grew", "form engine. The earlier project grew"), |
| 77 | ], |
| 78 | "object-authoring": [ |
| 79 | ("The askrobots signatures, so", "The earlier object server's signatures, so"), |
| 80 | ], |
| 81 | "site-routing": [ |
| 82 | ("h2 q9.is q9\n", "h2 example.org eg\n"), |
| 83 | ("on q9.is serves `q9_home`", "on example.org serves `eg_home`"), |
| 84 | ], |
| 85 | "shell-and-ai": [ |
| 86 | # the sentence sits above the list on the page once the title is gone |
| 87 | ("cloud voice paths above (", "cloud voice paths below ("), |
| 88 | ], |
| 89 | } |
| 90 | |
| 91 | _LINK = re.compile(r"\[([^\]\n]*(?:\n[^\]\n]*)?)\]\(([^)\s]+)\)") |
| 92 | # a file named in prose just before a closing bracket: "(see docs/dron.md)" |
| 93 | _BARE_MD = re.compile(r"(?<![`\w./-])([A-Za-z0-9_./-]+\.md)\)") |
| 94 | _PAGE_LINK = re.compile(r"\]\(/docs/([A-Za-z0-9_-]+)") |
| 95 | |
| 96 | |
| 97 | class SyncError(Exception): |
| 98 | pass |
| 99 | |
| 100 | |
| 101 | def doc_path(page_id: str) -> Path: |
| 102 | return DOCS / f"{DOC_FILES.get(page_id, page_id)}.md" |
| 103 | |
| 104 | |
| 105 | def render(page_id: str, markdown: str, page_ids: set[str]) -> str: |
| 106 | """The seeded `content` for one page, from its docs/ file's text.""" |
| 107 | lines = markdown.split("\n") |
| 108 | if not lines[0].startswith("# ") or (len(lines) > 1 and lines[1] != ""): |
| 109 | raise SyncError(f"{page_id}: docs file must start with a '# Title' line and a blank line") |
| 110 | text = "\n".join(lines[2:]) |
| 111 | stems = {DOC_FILES.get(pid, pid): pid for pid in page_ids} |
| 112 | |
| 113 | def relink(match: re.Match) -> str: |
| 114 | words, target = match.group(1), match.group(2) |
| 115 | if target.startswith(("http://", "https://", "#", "/", "mailto:")): |
| 116 | return match.group(0) |
| 117 | path, _, anchor = target.partition("#") |
| 118 | if path.endswith(".md") and "/" not in path and path[:-3] in stems: |
| 119 | return f"[{words}](/docs/{stems[path[:-3]]}{'#' + anchor if anchor else ''})" |
| 120 | return words |
| 121 | |
| 122 | text = _LINK.sub(relink, text) |
| 123 | # "git clone <url>" alone names its directory after the repository; a placeholder cannot |
| 124 | text = text.replace(f"git clone {REPOSITORY_URL}\n", f"git clone {PLACEHOLDER} dbbasic-object-server\n") |
| 125 | text = text.replace(REPOSITORY_URL, PLACEHOLDER) |
| 126 | text = ORG_LINK.sub(r"\1", text) |
| 127 | for old, new in REWORDED.get(page_id, []): |
| 128 | if old not in text: |
| 129 | raise SyncError( |
| 130 | f"{page_id}: REWORDED in scripts/sync_app_docs.py expects {old!r}, which " |
| 131 | f"{doc_path(page_id).relative_to(REPO)} no longer says; update or remove the entry" |
| 132 | ) |
| 133 | text = text.replace(old, new) |
| 134 | text = _BARE_MD.sub(r"`\1`)", text) |
| 135 | |
| 136 | banned = sorted({hit.lower() for hit in BANNED.findall(text)}) |
| 137 | if banned: |
| 138 | raise SyncError( |
| 139 | f"{page_id}: {doc_path(page_id).relative_to(REPO)} names {banned}, which the package may " |
| 140 | "not ship; add a REWORDED entry in scripts/sync_app_docs.py" |
| 141 | ) |
| 142 | if ".md)" in text: |
| 143 | raise SyncError(f"{page_id}: a raw .md link survived") |
| 144 | for slug in _PAGE_LINK.findall(text): |
| 145 | if slug not in page_ids: |
| 146 | raise SyncError(f"{page_id}: links to /docs/{slug}, which is not a seeded page") |
| 147 | return text |
| 148 | |
| 149 | |
| 150 | def read_seed(path: Path | None = None) -> list[list[str]]: |
| 151 | csv.field_size_limit(10**9) |
| 152 | with (path or SEED).open(newline="", encoding="utf-8") as handle: |
| 153 | return list(csv.reader(handle, delimiter="\t")) |
| 154 | |
| 155 | |
| 156 | def build(rows: list[list[str]]) -> tuple[list[list[str]], list[str]]: |
| 157 | """The rows as docs/ says they should be today, and the ids that changed.""" |
| 158 | header = rows[0] |
| 159 | id_col, content_col = header.index("id"), header.index("content") |
| 160 | page_ids = {row[id_col] for row in rows[1:]} |
| 161 | out, changed = [header], [] |
| 162 | for row in rows[1:]: |
| 163 | page_id = row[id_col] |
| 164 | source = doc_path(page_id) |
| 165 | if not source.is_file(): |
| 166 | raise SyncError(f"{page_id}: no {source.relative_to(REPO)}; add it to DOC_FILES or remove the row") |
| 167 | content = render(page_id, source.read_text(encoding="utf-8"), page_ids) |
| 168 | if content != row[content_col]: |
| 169 | changed.append(page_id) |
| 170 | new_row = list(row) |
| 171 | new_row[content_col] = content |
| 172 | out.append(new_row) |
| 173 | return out, changed |
| 174 | |
| 175 | |
| 176 | def dump(rows: list[list[str]]) -> str: |
| 177 | out = io.StringIO(newline="") |
| 178 | csv.writer(out, delimiter="\t", lineterminator="\n").writerows(rows) |
| 179 | return out.getvalue() |
| 180 | |
| 181 | |
| 182 | def main(argv: list[str] | None = None) -> int: |
| 183 | parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) |
| 184 | parser.add_argument("--check", action="store_true", help="change nothing; exit 1 if any page differs") |
| 185 | args = parser.parse_args(argv) |
| 186 | try: |
| 187 | rows, changed = build(read_seed()) |
| 188 | except SyncError as error: |
| 189 | print(f"sync_app_docs: {error}", file=sys.stderr) |
| 190 | return 2 |
| 191 | if args.check: |
| 192 | for page_id in changed: |
| 193 | print(f"differs from docs/: {page_id}") |
| 194 | return 1 if changed else 0 |
| 195 | if changed: |
| 196 | SEED.write_text(dump(rows), encoding="utf-8", newline="") |
| 197 | print(f"{len(changed)} page(s) rewritten" + (": " + ", ".join(changed) if changed else "")) |
| 198 | return 0 |
| 199 | |
| 200 | |
| 201 | if __name__ == "__main__": |
| 202 | sys.exit(main()) |