Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194#!/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 theuser guides (the pages build-docs.mjs lists under "guide"), every `/command` must bedeclared somewhere in the daemon or a client, every `--flag` of an `albedo` command mustbe a flag the CLI defines, an extension called on or off by default must be so in theregistry, and a repository path in a code span must exist."""
from __future__ import annotations
import reimport sysfrom pathlib import Path
ROOT = Path(__file__).resolve().parent.parentDOCS = 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())