| 1 | #!/usr/bin/env python3 |
| 2 | """Fail on feature-row docs drift or stale version references in live docs. |
| 3 | |
| 4 | `docs/features.toml` is the machine-readable statement of what the product |
| 5 | does. The feature-registry test already checks that every `docs` and `owner` |
| 6 | path exists; this check adds the content half for the commits in a range: |
| 7 | |
| 8 | - a row whose `owner` path changed must also change its `summary`, unless |
| 9 | every commit in the range that touched the owner carries a |
| 10 | `No-behaviour-change:` statement; |
| 11 | - a row whose `owner` changed and that has a `flag` must have a `docs` page |
| 12 | that mentions that flag. Row ids are registry slugs user docs do not use, so |
| 13 | a row without a flag skips this half. |
| 14 | |
| 15 | It also scans live `README*.md`, `docs/`, and `web/gt-catalog/` against the |
| 16 | live `[workspace.package].version` in `Cargo.toml` for stale pinned GitHub |
| 17 | URLs (`blob/v0.x.y/`, `tree/v0.x.y/`), stale Docker image tags |
| 18 | (`ghcr.io/.../codewhale:v0.x.y`), and stale version-framing phrases. |
| 19 | |
| 20 | Usage: |
| 21 | scripts/check-docs-drift.py [--warn-only] [--version-drift-only] [base] [head] |
| 22 | scripts/check-docs-drift.py [--warn-only] --range base..head |
| 23 | |
| 24 | Defaults: base = BEFORE_SHA when set, else the merge base with origin/main; |
| 25 | head = HEAD. |
| 26 | """ |
| 27 | |
| 28 | from __future__ import annotations |
| 29 | |
| 30 | import argparse |
| 31 | import os |
| 32 | import re |
| 33 | import subprocess |
| 34 | import sys |
| 35 | import tomllib |
| 36 | from pathlib import Path |
| 37 | |
| 38 | FEATURES = "docs/features.toml" |
| 39 | NO_CHANGE_RE = re.compile(r"^No-behaviour-change:\s*\S", re.MULTILINE) |
| 40 | EXCLUDED_VERSION_FILES = frozenset( |
| 41 | { |
| 42 | "CHANGELOG.md", |
| 43 | "docs/CHANGELOG_ARCHIVE.md", |
| 44 | "docs/CONTRIBUTORS.md", |
| 45 | "docs/REBRAND.md", |
| 46 | "docs/public-surface-facts.json", |
| 47 | } |
| 48 | ) |
| 49 | EXCLUDED_VERSION_DIRS = ( |
| 50 | "docs/design/", |
| 51 | "docs/releases/", |
| 52 | "docs/rfcs/", |
| 53 | ) |
| 54 | BINARY_EXTENSIONS = frozenset( |
| 55 | { |
| 56 | ".png", |
| 57 | ".jpg", |
| 58 | ".jpeg", |
| 59 | ".gif", |
| 60 | ".webp", |
| 61 | ".svg", |
| 62 | ".pdf", |
| 63 | ".ico", |
| 64 | ".woff", |
| 65 | ".woff2", |
| 66 | ".ttf", |
| 67 | ".zip", |
| 68 | ".tar", |
| 69 | ".gz", |
| 70 | } |
| 71 | ) |
| 72 | GITHUB_PINNED_RE = re.compile( |
| 73 | r"(?:https?://github\.com/(?P<org>[^/\s\"')`]+)/[^/\s\"')`]+/)?(?:blob|tree)/v(?P<ver>\d+\.\d+\.\d+)/", |
| 74 | re.IGNORECASE, |
| 75 | ) |
| 76 | DOCKER_TAG_RE = re.compile( |
| 77 | r"ghcr\.io/[^\s\"')`\\]+/codewhale:v(?P<ver>\d+\.\d+\.\d+)\b", |
| 78 | re.IGNORECASE, |
| 79 | ) |
| 80 | VERSION_FRAMING_RE = re.compile( |
| 81 | r"\b(?:" |
| 82 | r"(?:(?:introduced|added|shipped|available|landed|tightened|changed|removed|deprecated)\s+(?:in|with|since|as of)" |
| 83 | r"|new(?:\s+(?:in|with|since|as of))?" |
| 84 | r"|as of|since|starting\s+(?:in|with|from))\s+v?(?P<ver>\d+\.\d+(?:\.\d+)?)" |
| 85 | r"|from\s+(?:v(?P<from_v>\d+\.\d+(?:\.\d+)?)|(?P<from_patch>\d+\.\d+\.\d+))" |
| 86 | r")\b", |
| 87 | re.IGNORECASE, |
| 88 | ) |
| 89 | SCREENSHOT_CAPTURE_RE = re.compile( |
| 90 | r"\b(?:captured|screenshot|real session on published)\b", |
| 91 | re.IGNORECASE, |
| 92 | ) |
| 93 | CODEWHALE_ORGS = frozenset({"codewhale-hq", "hmbown"}) |
| 94 | |
| 95 | ROOT = Path( |
| 96 | os.environ.get("CODEWHALE_REPO_ROOT", Path(__file__).resolve().parents[1]) |
| 97 | ).resolve() |
| 98 | |
| 99 | |
| 100 | def git(*args: str) -> str: |
| 101 | result = subprocess.run( |
| 102 | ["git", *args], cwd=ROOT, capture_output=True, text=True, check=False |
| 103 | ) |
| 104 | if result.returncode != 0: |
| 105 | sys.exit( |
| 106 | f"check-docs-drift: git {' '.join(args)} failed: {result.stderr.strip()}" |
| 107 | ) |
| 108 | return result.stdout |
| 109 | |
| 110 | |
| 111 | def default_base() -> str: |
| 112 | before = os.environ.get("BEFORE_SHA", "").strip() |
| 113 | if before and set(before) != {"0"}: |
| 114 | return before |
| 115 | return git("merge-base", "HEAD", "origin/main").strip() |
| 116 | |
| 117 | |
| 118 | def load_rows(text: str) -> list[dict]: |
| 119 | try: |
| 120 | data = tomllib.loads(text) |
| 121 | except tomllib.TOMLDecodeError as err: |
| 122 | sys.exit(f"check-docs-drift: {FEATURES} is not valid TOML: {err}") |
| 123 | return data.get("feature", []) |
| 124 | |
| 125 | |
| 126 | def owner_commits_state_no_change(base: str, head: str, owner: str) -> bool: |
| 127 | raw = git( |
| 128 | "log", "--no-merges", "--format=%x1e%b", f"{base}..{head}", "--", owner.rstrip("/") |
| 129 | ) |
| 130 | bodies = raw.split("\x1e")[1:] |
| 131 | return bool(bodies) and all(NO_CHANGE_RE.search(body) for body in bodies) |
| 132 | |
| 133 | |
| 134 | def owner_touched(owner: str, changed: set[str]) -> bool: |
| 135 | owner = owner.rstrip("/") |
| 136 | return any(path == owner or path.startswith(owner + "/") for path in changed) |
| 137 | |
| 138 | |
| 139 | def parse_version(raw: str) -> tuple[int, ...]: |
| 140 | core = raw.strip().lstrip("vV").split("-", 1)[0].split("+", 1)[0] |
| 141 | parts = core.split(".") |
| 142 | if len(parts) not in (2, 3) or not all(part.isdigit() for part in parts): |
| 143 | raise ValueError(f"invalid version: {raw!r}") |
| 144 | return tuple(int(part) for part in parts) |
| 145 | |
| 146 | |
| 147 | def load_workspace_version(root: Path) -> tuple[str, tuple[int, int, int]]: |
| 148 | cargo_toml = root / "Cargo.toml" |
| 149 | try: |
| 150 | data = tomllib.loads(cargo_toml.read_text(encoding="utf-8")) |
| 151 | except (OSError, tomllib.TOMLDecodeError) as err: |
| 152 | sys.exit(f"check-docs-drift: failed to read {cargo_toml}: {err}") |
| 153 | version = data.get("workspace", {}).get("package", {}).get("version") |
| 154 | if not isinstance(version, str) or not version.strip(): |
| 155 | sys.exit( |
| 156 | f"check-docs-drift: {cargo_toml} is missing [workspace.package].version" |
| 157 | ) |
| 158 | parsed = parse_version(version) |
| 159 | if len(parsed) != 3: |
| 160 | sys.exit( |
| 161 | f"check-docs-drift: [workspace.package].version {version!r} must be X.Y.Z" |
| 162 | ) |
| 163 | return version.strip(), (parsed[0], parsed[1], parsed[2]) |
| 164 | |
| 165 | |
| 166 | def is_older_version(candidate: str, current: tuple[int, int, int]) -> bool: |
| 167 | parsed = parse_version(candidate) |
| 168 | if len(parsed) == 2: |
| 169 | return parsed < current[:2] |
| 170 | return parsed < current |
| 171 | |
| 172 | |
| 173 | def iter_live_doc_paths(root: Path) -> list[Path]: |
| 174 | candidates: set[Path] = set() |
| 175 | for readme in root.glob("README*.md"): |
| 176 | if readme.is_file(): |
| 177 | candidates.add(readme) |
| 178 | for subdir in (root / "docs", root / "web" / "gt-catalog"): |
| 179 | if not subdir.is_dir(): |
| 180 | continue |
| 181 | for path in subdir.rglob("*"): |
| 182 | if path.is_file(): |
| 183 | candidates.add(path) |
| 184 | result: list[Path] = [] |
| 185 | for path in sorted(candidates): |
| 186 | if path.suffix.lower() in BINARY_EXTENSIONS: |
| 187 | continue |
| 188 | rel = path.relative_to(root).as_posix() |
| 189 | if rel in EXCLUDED_VERSION_FILES or rel.startswith(EXCLUDED_VERSION_DIRS): |
| 190 | continue |
| 191 | result.append(path) |
| 192 | return result |
| 193 | |
| 194 | |
| 195 | def scan_version_drift(root: Path) -> tuple[str, list[str]]: |
| 196 | version_str, current = load_workspace_version(root) |
| 197 | findings: list[str] = [] |
| 198 | for path in iter_live_doc_paths(root): |
| 199 | try: |
| 200 | text = path.read_text(encoding="utf-8") |
| 201 | except UnicodeDecodeError: |
| 202 | continue |
| 203 | rel = path.relative_to(root).as_posix() |
| 204 | for lineno, line in enumerate(text.splitlines(), 1): |
| 205 | for match in GITHUB_PINNED_RE.finditer(line): |
| 206 | org = match.group("org") |
| 207 | if org and org.lower() not in CODEWHALE_ORGS: |
| 208 | continue |
| 209 | if is_older_version(match.group("ver"), current): |
| 210 | findings.append( |
| 211 | f"{rel}:{lineno}: stale pinned GitHub URL '{match.group(0)}' " |
| 212 | f"(current {version_str})" |
| 213 | ) |
| 214 | for match in DOCKER_TAG_RE.finditer(line): |
| 215 | if is_older_version(match.group("ver"), current): |
| 216 | findings.append( |
| 217 | f"{rel}:{lineno}: stale Docker image tag '{match.group(0)}' " |
| 218 | f"(current {version_str})" |
| 219 | ) |
| 220 | if SCREENSHOT_CAPTURE_RE.search(line): |
| 221 | continue |
| 222 | for match in VERSION_FRAMING_RE.finditer(line): |
| 223 | ver = ( |
| 224 | match.group("ver") |
| 225 | or match.group("from_v") |
| 226 | or match.group("from_patch") |
| 227 | ) |
| 228 | if ver and is_older_version(ver, current): |
| 229 | findings.append( |
| 230 | f"{rel}:{lineno}: stale version framing '{match.group(0)}' " |
| 231 | f"(current {version_str})" |
| 232 | ) |
| 233 | return version_str, findings |
| 234 | |
| 235 | |
| 236 | def main(argv: list[str]) -> int: |
| 237 | parser = argparse.ArgumentParser( |
| 238 | description="Check feature-row docs drift and stale version references in live docs." |
| 239 | ) |
| 240 | parser.add_argument("base", nargs="?", help="range base (default: BEFORE_SHA or origin/main merge base)") |
| 241 | parser.add_argument("head", nargs="?", default="HEAD", help="range head (default: HEAD)") |
| 242 | parser.add_argument("--range", dest="range_spec", help="BASE..HEAD") |
| 243 | parser.add_argument( |
| 244 | "--warn-only", |
| 245 | action="store_true", |
| 246 | help="print the findings but exit 0 (preflight and the release-candidate report)", |
| 247 | ) |
| 248 | parser.add_argument( |
| 249 | "--version-drift-only", |
| 250 | action="store_true", |
| 251 | help="check only live docs/README/catalog version drift against Cargo.toml", |
| 252 | ) |
| 253 | args = parser.parse_args(argv) |
| 254 | |
| 255 | feature_failures: list[str] = [] |
| 256 | checked = 0 |
| 257 | base = "" |
| 258 | head = args.head |
| 259 | |
| 260 | if not args.version_drift_only: |
| 261 | if args.range_spec: |
| 262 | if ".." not in args.range_spec: |
| 263 | parser.error("--range must be BASE..HEAD") |
| 264 | base, head = args.range_spec.split("..", 1) |
| 265 | else: |
| 266 | base = args.base or default_base() |
| 267 | head = args.head |
| 268 | |
| 269 | head_rows = load_rows((ROOT / FEATURES).read_text(encoding="utf-8")) |
| 270 | try: |
| 271 | base_rows = load_rows(git("show", f"{base}:{FEATURES}")) |
| 272 | except SystemExit: |
| 273 | base_rows = [] |
| 274 | base_by_id = {row.get("id"): row for row in base_rows} |
| 275 | changed = set(git("diff", "--name-only", f"{base}..{head}").splitlines()) |
| 276 | |
| 277 | for row in head_rows: |
| 278 | row_id = row.get("id", "<unnamed>") |
| 279 | owner = row.get("owner") |
| 280 | if not owner or not owner_touched(owner, changed): |
| 281 | continue |
| 282 | checked += 1 |
| 283 | old_summary = base_by_id.get(row_id, {}).get("summary") |
| 284 | if row.get("summary") == old_summary and not owner_commits_state_no_change( |
| 285 | base, head, owner |
| 286 | ): |
| 287 | feature_failures.append( |
| 288 | f"{row_id}: owner {owner} changed but the summary did not; " |
| 289 | "update the summary or add a 'No-behaviour-change:' line" |
| 290 | ) |
| 291 | docs = row.get("docs") |
| 292 | if not docs: |
| 293 | continue |
| 294 | page = docs.split("#", 1)[0] |
| 295 | page_path = ROOT / page |
| 296 | if not page_path.is_file(): |
| 297 | feature_failures.append(f"{row_id}: docs page {page} does not exist") |
| 298 | continue |
| 299 | token = row.get("flag") |
| 300 | if token and token not in page_path.read_text(encoding="utf-8"): |
| 301 | feature_failures.append( |
| 302 | f"{row_id}: docs page {page} does not mention {token}; " |
| 303 | "the page no longer describes the feature the row names" |
| 304 | ) |
| 305 | |
| 306 | version_str = "" |
| 307 | version_failures: list[str] = [] |
| 308 | if args.version_drift_only or (ROOT / "Cargo.toml").is_file(): |
| 309 | version_str, version_failures = scan_version_drift(ROOT) |
| 310 | |
| 311 | if feature_failures: |
| 312 | print( |
| 313 | f"check-docs-drift: {len(feature_failures)} feature row(s) changed without " |
| 314 | f"their docs or summary ({base[:12]}..{head}):", |
| 315 | file=sys.stderr, |
| 316 | ) |
| 317 | for failure in feature_failures: |
| 318 | print(f" - {failure}", file=sys.stderr) |
| 319 | |
| 320 | if version_failures: |
| 321 | print( |
| 322 | f"check-docs-drift: {len(version_failures)} stale version reference(s) " |
| 323 | f"in live docs (current {version_str}):", |
| 324 | file=sys.stderr, |
| 325 | ) |
| 326 | for failure in version_failures: |
| 327 | print(f" - {failure}", file=sys.stderr) |
| 328 | |
| 329 | if feature_failures or version_failures: |
| 330 | return 0 if args.warn_only else 1 |
| 331 | |
| 332 | if not args.version_drift_only: |
| 333 | print( |
| 334 | f"check-docs-drift: {checked} touched feature row(s) keep their summary " |
| 335 | f"and docs aligned ({base[:12]}..{head})" |
| 336 | ) |
| 337 | if version_str: |
| 338 | print( |
| 339 | f"check-docs-drift: live docs have no stale version references " |
| 340 | f"(current {version_str})" |
| 341 | ) |
| 342 | return 0 |
| 343 | |
| 344 | |
| 345 | if __name__ == "__main__": |
| 346 | raise SystemExit(main(sys.argv[1:])) |
| 347 |