#!/usr/bin/env python3 """Checks docs/ against the tree, so a renamed command, flag, file or heading fails here. python3 test/docs_drift.py Every relative link must reach a file, and its #anchor a heading of that page. In the user guides (the pages build-docs.mjs lists under "guide"), every `/command` must be declared somewhere in the daemon or a client, every `--flag` of an `albedo` command must be a flag the CLI defines, an extension called on or off by default must be so in the registry, and a repository path in a code span must exist. """ from __future__ import annotations import re import sys from pathlib import Path ROOT = Path(__file__).resolve().parent.parent DOCS = ROOT / "docs" REGISTRY = ROOT / "apps/albedo/src/albedo/composition/extensions.gleam" # Where a slash command or a CLI flag is declared: the daemon, its extensions, and the clients. COMMAND_SOURCES = [ "apps/albedo/src", "extensions", "packages", "cli/internal", "web/src", ] FLAG_SOURCES = ["cli/internal/cli", "cli/cmd"] # Written as examples, not as commands that exist. PLACEHOLDERS = {"/skill", "/skill-name"} # Flags of other programs that the guides show next to `albedo`, and the one cobra adds itself. FOREIGN_FLAGS = {"--prefix", "--data-binary", "--help"} REPO_DIRS = ( "apps/", "cli/", "extensions/", "native/", "packages/", "python/", "release/", "scripts/", "site/", "test/", "web/", ) def slug(heading: str) -> str: """The id site/build-docs.mjs gives a heading.""" text = re.sub(r"<[^>]+>", "", heading.lower().strip()) text = re.sub(r"[^\w\s-]", "", text, flags=re.UNICODE) return re.sub(r"\s", "-", text) def anchors(page: Path) -> set[str]: seen: dict[str, int] = {} found = set() fenced = False for line in page.read_text().splitlines(): if line.startswith("```"): fenced = not fenced match = None if fenced else re.match(r"#{2,6}\s+(.*)", line) if not match: continue # Links and code in a heading contribute their text only. text = re.sub(r"\[([^\]]*)\]\([^)]*\)", r"\1", match.group(1)).replace("`", "") base = slug(text) count = seen.get(base, 0) seen[base] = count + 1 found.add(f"{base}-{count}" if count else base) return found def prose(page: Path) -> str: """The page without fenced code, so a shell comment is not read as a heading or a link.""" return re.sub(r"^```.*?^```", "", page.read_text(), flags=re.S | re.M) def guide_pages() -> list[Path]: listed = re.findall( r"file: '([^']+)',\s*(?:out: '[^']+',\s*)?group: 'guide'", (ROOT / "site/build-docs.mjs").read_text(), ) return [DOCS / name for name in listed if name != "readme.md"] def corpus(roots: list[str], suffixes: tuple[str, ...]) -> str: parts = [] for root in roots: for path in (ROOT / root).rglob("*"): if ( path.suffix in suffixes and "node_modules" not in path.parts and "build" not in path.parts ): parts.append(path.read_text(errors="replace")) return "\n".join(parts) def default_extensions() -> set[str]: """The names in the registry's default list, the last list of strings in its file.""" lists = re.findall(r"\[\s*((?:\"[a-z0-9-]+\",?\s*)+)\]", REGISTRY.read_text()) return set(re.findall(r'"([a-z0-9-]+)"', lists[-1])) def check_links(problems: list[str]) -> None: for page in sorted(DOCS.glob("*.md")): for target, anchor in re.findall( r"\]\(([^)#\s]*)(?:#([^)\s]*))?\)", prose(page) ): if re.match(r"[a-z]+:", target): continue file = (page.parent / target).resolve() if target else page if not file.exists(): problems.append(f"{page.name}: link to {target}, which does not exist") elif anchor and file.suffix == ".md" and anchor not in anchors(file): problems.append( f"{page.name}: link to {target or page.name}#{anchor}, which has no such heading" ) def check_guides(problems: list[str]) -> None: commands = corpus(COMMAND_SOURCES, (".gleam", ".go", ".ts", ".svelte")) flags = corpus(FLAG_SOURCES, (".go",)) defaults = default_extensions() for page in guide_pages(): text = page.read_text() for command in sorted( set(re.findall(r"`(/[a-z][a-z-]*)(?=[`\s])", text)) - PLACEHOLDERS ): if f'"{command}"' not in commands and f'"{command[1:]}"' not in commands: problems.append( f"{page.name}: {command} is not a command the daemon or a client declares" ) for line in text.splitlines(): if "albedo" not in line: continue for flag in set(re.findall(r"(--[a-z][a-z-]+)", line)) - FOREIGN_FLAGS: if f'"{flag[2:]}"' not in flags: problems.append( f"{page.name}: {flag} is not a flag the CLI defines" ) for sentence in re.split(r"(?<=[.:])\s+", re.sub(r"\s+", " ", prose(page))): if re.search( r"off by default|[Ee]nable `[a-z-]+` in `/extensions`", sentence ): named = set( re.findall( r"[Ee]nable `([a-z-]+)` in `/extensions`|`([a-z-]+)` extension is off", sentence, ) ) for name in {n for pair in named for n in pair if n} & defaults: problems.append( f"{page.name}: says to enable {name}, which is on by default" ) for stated in re.findall( r"((?:`[a-z0-9-]+`(?:,? and |, )?)+)(?: extensions?)? \(?(?:is |are )?enabled by default", sentence, ): for name in set(re.findall(r"`([a-z0-9-]+)`", stated)) - defaults: problems.append( f"{page.name}: says {name} is enabled by default, and it is not" ) for path in set( re.findall( r"`((?:%s)[\w./-]+)`" % "|".join(re.escape(d) for d in REPO_DIRS), text ) ) | set( re.findall( r"^((?:%s)[\w./-]+)" % "|".join(re.escape(d) for d in REPO_DIRS), text, flags=re.M, ) ): if not (ROOT / path).exists(): problems.append(f"{page.name}: names {path}, which does not exist") def main() -> int: problems: list[str] = [] check_links(problems) check_guides(problems) for problem in problems: print(problem) print(f"docs drift: {len(problems)} problem(s)" if problems else "docs drift: none") return 1 if problems else 0 if __name__ == "__main__": sys.exit(main())