| #!/usr/bin/env python3 | |
| # Copyright 2026 The Fuchsia Authors | |
| # | |
| # Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 | |
| # <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT | |
| # license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. | |
| # This file may not be copied, modified, or distributed except according to | |
| # those terms. | |
| """Timeless whole-tree checker for the `docs/unstable/` feature registry. | |
| Enforces structural registry invariants without relying on wall-clock time | |
| (dated 90-day `review_by` bounds and expiry blocking live in | |
| `ci/check_pr_hygiene.py`): | |
| 1. Every `docs/unstable/<id>.toml` has a lowercase `snake_case` ID, matching | |
| `<id>.md`, valid public fields (`owners`, `tracking_issue`, `review_by`, | |
| `gate_test`), an existing `gate_test` file, and zero internal-only patterns. | |
| 2. Every `<id>.md` carries the Fuchsia license header, the experimental opt-in | |
| banner, its tracking issue URL, a limitations section, and a graduation | |
| checklist. | |
| 3. Bidirectional non-orphan parity across every unstable-feature code site: | |
| - `candidate:<id>` entries in `trusted/locks/cartridges.lock.json` | |
| - `Specs/Unstable/<id>` specification prelude modules | |
| - `theory/Anneal/Unstable/<id>` proof library modules | |
| - CLI `-Z <id>` flag tables in `cargo-anneal` (`src/unstable.rs`) | |
| - Stage-O / Stage-L capture feature tables (`CAPTURE_UNSTABLE_FEATURES`) | |
| - `tools/anneal-spec` preview-lowering tables (`PREVIEW_UNSTABLE_FEATURES`) | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import datetime | |
| import json | |
| from pathlib import Path | |
| import re | |
| import sys | |
| import tomllib | |
| from typing import Iterable | |
| FEATURE_ID_RE = re.compile(r"^[a-z][a-z0-9_]{0,63}$") | |
| HANDLE_RE = re.compile(r"^@[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$") | |
| GITHUB_ISSUE_RE = re.compile( | |
| r"^https://github\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/(?:issues|pull)/[1-9][0-9]*$" | |
| ) | |
| ISO_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$") | |
| REQUIRED_KEYS = frozenset({"owners", "tracking_issue", "review_by", "gate_test"}) | |
| HEADER_RE = re.compile( | |
| r"Copyright \d{4} The Fuchsia Authors.*" | |
| r"Licensed under a BSD-style license <LICENSE-BSD>, Apache License, " | |
| r"Version 2\.0", | |
| re.DOTALL, | |
| ) | |
| INTERNAL_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = ( | |
| ("private corporate hostname", re.compile(r"\b[A-Za-z0-9._-]+\.(?:corp|internal|local)\b")), | |
| ("workstation path", re.compile(r"(?:^|[\s'\"(`])(?:/Users/|/home/)")), | |
| ("file URI", re.compile(r"\bfile:///[A-Za-z0-9._/-]+")), | |
| ) | |
| def _load_json_no_duplicate_keys(text: str) -> object: | |
| def _reject_duplicates(pairs: list[tuple[str, object]]) -> dict[str, object]: | |
| out: dict[str, object] = {} | |
| for key, value in pairs: | |
| if key in out: | |
| raise ValueError(f"duplicate JSON key `{key}`") | |
| out[key] = value | |
| return out | |
| return json.loads(text, object_pairs_hook=_reject_duplicates) | |
| def _match_rust_raw_string(text: str, idx: int) -> int | None: | |
| """If `text[idx:]` starts a Rust raw string (`r#*"..."#*`), return end.""" | |
| n = len(text) | |
| pos = idx | |
| if pos < n and text[pos] in ("b", "c") and pos + 1 < n and text[pos + 1] == "r": | |
| pos += 1 | |
| if pos >= n or text[pos] != "r": | |
| return None | |
| pos += 1 | |
| hashes = 0 | |
| while pos < n and text[pos] == "#": | |
| hashes += 1 | |
| pos += 1 | |
| if pos >= n or text[pos] != '"': | |
| return None | |
| pos += 1 | |
| closing = '"' + "#" * hashes | |
| end = text.find(closing, pos) | |
| if end < 0: | |
| return n | |
| return end + len(closing) | |
| def _decode_rust_string_body(raw_inner: str) -> str: | |
| """Decode Rust string escape sequences (preserving non-escaped chars).""" | |
| out: list[str] = [] | |
| i = 0 | |
| n = len(raw_inner) | |
| while i < n: | |
| if raw_inner[i] == "\\" and i + 1 < n: | |
| esc = raw_inner[i + 1] | |
| if esc == "\n": | |
| i += 2 | |
| while i < n and raw_inner[i] in " \t\r": | |
| i += 1 | |
| continue | |
| if esc == "x" and i + 3 < n: | |
| try: | |
| out.append(chr(int(raw_inner[i + 2 : i + 4], 16))) | |
| i += 4 | |
| continue | |
| except ValueError: | |
| pass | |
| if esc == "u" and i + 2 < n and raw_inner[i + 2] == "{": | |
| close = raw_inner.find("}", i + 3) | |
| if close > i + 3: | |
| hex_str = raw_inner[i + 3 : close].replace("_", "") | |
| try: | |
| out.append(chr(int(hex_str, 16))) | |
| i = close + 1 | |
| continue | |
| except ValueError: | |
| pass | |
| out.append( | |
| { | |
| "n": "\n", | |
| "r": "\r", | |
| "t": "\t", | |
| "0": "\0", | |
| "\\": "\\", | |
| '"': '"', | |
| "'": "'", | |
| }.get(esc, esc) | |
| ) | |
| i += 2 | |
| continue | |
| out.append(raw_inner[i]) | |
| i += 1 | |
| return "".join(out) | |
| def _lex_rust_tokens(text: str) -> list[tuple[str, str]]: | |
| """Tokenize Rust source, stripping comments and keeping strings/chars whole. | |
| Emits `("IDENT", s)`, `("STR", decoded)`, `("CHAR", raw)`, `("PUNCT", ch)`, | |
| or `("OTHER", s)` tokens so callers never confuse comment text, string | |
| contents, or character literals (like `']'` or `'"'`) with syntax. | |
| """ | |
| tokens: list[tuple[str, str]] = [] | |
| i = 0 | |
| n = len(text) | |
| while i < n: | |
| ch = text[i] | |
| if ch.isspace(): | |
| i += 1 | |
| continue | |
| # Line comment. | |
| if ch == "/" and i + 1 < n and text[i + 1] == "/": | |
| i += 2 | |
| while i < n and text[i] != "\n": | |
| i += 1 | |
| continue | |
| # Nested block comment. | |
| if ch == "/" and i + 1 < n and text[i + 1] == "*": | |
| depth = 1 | |
| i += 2 | |
| while i < n and depth > 0: | |
| if text[i] == "/" and i + 1 < n and text[i + 1] == "*": | |
| depth += 1 | |
| i += 2 | |
| elif text[i] == "*" and i + 1 < n and text[i + 1] == "/": | |
| depth -= 1 | |
| i += 2 | |
| else: | |
| i += 1 | |
| continue | |
| # Raw string literal (`r"..."`, `r#"..."#`, `br#"..."#`, `cr#"..."#`). | |
| raw_end = _match_rust_raw_string(text, i) | |
| if raw_end is not None: | |
| tok = text[i:raw_end] | |
| first_q = tok.index('"') | |
| last_q = tok.rindex('"') | |
| tokens.append(("STR", tok[first_q + 1 : last_q])) | |
| i = raw_end | |
| continue | |
| # Byte/C normal string literal (`b"..."`, `c"..."`). | |
| if ch in ("b", "c") and i + 1 < n and text[i + 1] == '"': | |
| j = i + 2 | |
| while j < n: | |
| if text[j] == "\\": | |
| j += 2 | |
| continue | |
| if text[j] == '"': | |
| tokens.append(("STR", _decode_rust_string_body(text[i + 2 : j]))) | |
| j += 1 | |
| break | |
| j += 1 | |
| i = j | |
| continue | |
| # Normal string literal. | |
| if ch == '"': | |
| j = i + 1 | |
| while j < n: | |
| if text[j] == "\\": | |
| j += 2 | |
| continue | |
| if text[j] == '"': | |
| tokens.append(("STR", _decode_rust_string_body(text[i + 1 : j]))) | |
| j += 1 | |
| break | |
| j += 1 | |
| i = j | |
| continue | |
| # Byte character literal (`b'...'`). | |
| if ch == "b" and i + 1 < n and text[i + 1] == "'": | |
| j = i + 2 | |
| if j < n and text[j] == "\\": | |
| # Skip `\` and the escaped byte (e.g., `b'\''`, `b'\\'`). | |
| j += 2 | |
| while j < n and text[j] != "'" and text[j] != "\n": | |
| j += 1 | |
| if j < n and text[j] == "'": | |
| tokens.append(("CHAR", text[i : j + 1])) | |
| i = j + 1 | |
| continue | |
| elif j + 1 < n and text[j + 1] == "'" and text[j] != "\n": | |
| tokens.append(("CHAR", text[i : j + 2])) | |
| i = j + 2 | |
| continue | |
| # Character literal vs lifetime (`'a` / `'static`). | |
| if ch == "'" and i + 1 < n: | |
| if text[i + 1] == "\\": | |
| # Skip `\` and the escaped char (e.g., `'\''`, `'\\'`). | |
| j = i + 3 | |
| while j < n and text[j] != "'" and text[j] != "\n": | |
| j += 1 | |
| if j < n and text[j] == "'": | |
| tokens.append(("CHAR", text[i : j + 1])) | |
| i = j + 1 | |
| continue | |
| elif i + 2 < n and text[i + 2] == "'" and text[i + 1] != "\n": | |
| tokens.append(("CHAR", text[i : i + 3])) | |
| i += 3 | |
| continue | |
| # Lifetime token (consume `'ident` so it doesn't confuse char scan). | |
| j = i + 1 | |
| while j < n and (text[j].isalnum() or text[j] == "_"): | |
| j += 1 | |
| tokens.append(("OTHER", text[i:j])) | |
| i = j | |
| continue | |
| # Raw identifier `r#ident` (distinct from keywords like `const`). | |
| if ch == "r" and i + 1 < n and text[i + 1] == "#": | |
| j = i + 2 | |
| while j < n and (text[j].isalnum() or text[j] == "_"): | |
| j += 1 | |
| if j > i + 2: | |
| tokens.append(("RAW_IDENT", text[i + 2 : j])) | |
| i = j | |
| continue | |
| # Identifier. | |
| if ch.isalpha() or ch == "_": | |
| j = i + 1 | |
| while j < n and (text[j].isalnum() or text[j] == "_"): | |
| j += 1 | |
| tokens.append(("IDENT", text[i:j])) | |
| i = j | |
| continue | |
| # Number literal. | |
| if ch.isdigit(): | |
| j = i + 1 | |
| while j < n and (text[j].isalnum() or text[j] in "_."): | |
| j += 1 | |
| tokens.append(("OTHER", text[i:j])) | |
| i = j | |
| continue | |
| # Double colon `::`. | |
| if ch == ":" and i + 1 < n and text[i + 1] == ":": | |
| tokens.append(("PUNCT", "::")) | |
| i += 2 | |
| continue | |
| tokens.append(("PUNCT", ch)) | |
| i += 1 | |
| return tokens | |
| def _match_delimited_tokens( | |
| tokens: list[tuple[str, str]], open_idx: int, open_ch: str, close_ch: str | |
| ) -> tuple[list[tuple[str, str]], int] | None: | |
| """Return `(inner_tokens, close_idx)` for balanced delimiter tokens.""" | |
| if open_idx >= len(tokens) or tokens[open_idx] != ("PUNCT", open_ch): | |
| return None | |
| depth = 1 | |
| i = open_idx + 1 | |
| while i < len(tokens): | |
| if tokens[i] == ("PUNCT", open_ch): | |
| depth += 1 | |
| elif tokens[i] == ("PUNCT", close_ch): | |
| depth -= 1 | |
| if depth == 0: | |
| return tokens[open_idx + 1 : i], i | |
| i += 1 | |
| return None | |
| def _split_top_level_commas( | |
| tokens: list[tuple[str, str]] | |
| ) -> list[list[tuple[str, str]]]: | |
| """Split token sequence on top-level `,` (respecting `()`, `[]`, `{}`).""" | |
| groups: list[list[tuple[str, str]]] = [] | |
| cur: list[tuple[str, str]] = [] | |
| depth = 0 | |
| for tok in tokens: | |
| if tok[0] == "PUNCT" and tok[1] in "([{": | |
| depth += 1 | |
| cur.append(tok) | |
| elif tok[0] == "PUNCT" and tok[1] in ")]}": | |
| depth = max(0, depth - 1) | |
| cur.append(tok) | |
| elif depth == 0 and tok == ("PUNCT", ","): | |
| groups.append(cur) | |
| cur = [] | |
| else: | |
| cur.append(tok) | |
| if cur: | |
| groups.append(cur) | |
| return groups | |
| def _is_rust_path(tokens: list[tuple[str, str]]) -> bool: | |
| """True when `tokens` is a non-empty Rust path (`Foo`, `a::b::Foo`).""" | |
| if not tokens: | |
| return False | |
| idx = 0 | |
| if tokens[0] == ("PUNCT", "::"): | |
| idx = 1 | |
| if idx >= len(tokens) or tokens[idx][0] != "IDENT": | |
| return False | |
| idx += 1 | |
| while idx < len(tokens): | |
| if tokens[idx] != ("PUNCT", "::"): | |
| return False | |
| if idx + 1 >= len(tokens) or tokens[idx + 1][0] != "IDENT": | |
| return False | |
| idx += 2 | |
| return True | |
| def _parse_rust_array_element( | |
| elem: list[tuple[str, str]] | |
| ) -> tuple[str | None, str | None]: | |
| """Parse one element of an unstable-feature array; fail closed on any other shape. | |
| Returns `(feature_id, error_message)`. | |
| """ | |
| if not elem: | |
| return None, "empty element" | |
| # Plain string literal (`"mir_alloc"`). | |
| if len(elem) == 1 and elem[0][0] == "STR": | |
| return elem[0][1], None | |
| # Struct literal (`UnstableFeature { id: "mir_alloc", ... }`). | |
| if elem[-1] == ("PUNCT", "}"): | |
| # Find the matching `{` at the start of the struct body. | |
| depth = 0 | |
| open_brace: int | None = None | |
| for idx in range(len(elem) - 1, -1, -1): | |
| if elem[idx] == ("PUNCT", "}"): | |
| depth += 1 | |
| elif elem[idx] == ("PUNCT", "{"): | |
| depth -= 1 | |
| if depth == 0: | |
| open_brace = idx | |
| break | |
| if open_brace is not None and _is_rust_path(elem[:open_brace]): | |
| inner = elem[open_brace + 1 : -1] | |
| fields = _split_top_level_commas(inner) | |
| id_values: list[list[tuple[str, str]]] = [] | |
| for field in fields: | |
| if not field: | |
| continue | |
| if ( | |
| len(field) >= 2 | |
| and field[0][0] in ("IDENT", "RAW_IDENT") | |
| and field[0][1] == "id" | |
| and field[1] == ("PUNCT", ":") | |
| ): | |
| id_values.append(field[2:]) | |
| if len(id_values) != 1: | |
| return None, "struct element must declare exactly one `id: \"...\"` field" | |
| val_toks = id_values[0] | |
| if len(val_toks) != 1 or val_toks[0][0] != "STR": | |
| return None, "struct `id` field must be a string literal" | |
| return val_toks[0][1], None | |
| return ( | |
| None, | |
| "element must be a string literal or struct literal with a string-literal `id` field", | |
| ) | |
| def _has_symlink_component(repo_root: Path, rel_path: Path) -> bool: | |
| """True when any path component from `repo_root` down to `rel_path` is a symlink.""" | |
| cur = repo_root | |
| for part in rel_path.parts: | |
| cur = cur / part | |
| if cur.is_symlink(): | |
| return True | |
| return False | |
| def _extract_rust_const_ids( | |
| repo_root: Path, rel: str, const_name: str, errors: list[str] | |
| ) -> set[str]: | |
| """Extract all feature ID strings from `const`/`static <const_name>` (fail closed).""" | |
| rel_path = Path(rel) | |
| path = repo_root / rel_path | |
| if _has_symlink_component(repo_root, rel_path): | |
| errors.append(f"{rel}: symlinks are forbidden") | |
| return set() | |
| if not path.exists(): | |
| return set() | |
| if not path.is_file(): | |
| errors.append(f"{rel}: expected a regular file") | |
| return set() | |
| try: | |
| text = path.read_text(encoding="utf-8") | |
| except (OSError, UnicodeDecodeError) as exc: | |
| errors.append(f"{rel}: unreadable file: {exc}") | |
| return set() | |
| tokens = _lex_rust_tokens(text) | |
| ids: set[str] = set() | |
| n = len(tokens) | |
| i = 0 | |
| while i < n: | |
| name_idx: int | None = None | |
| if tokens[i] == ("IDENT", "const") and i + 1 < n: | |
| name_idx = i + 1 | |
| elif tokens[i] == ("IDENT", "static") and i + 1 < n: | |
| if tokens[i + 1] == ("IDENT", "mut") and i + 2 < n: | |
| name_idx = i + 2 | |
| else: | |
| name_idx = i + 1 | |
| if ( | |
| name_idx is not None | |
| and tokens[name_idx][0] in ("IDENT", "RAW_IDENT") | |
| and tokens[name_idx][1] == const_name | |
| ): | |
| # Advance to `=` outside nested delimiters (skipping the type). | |
| j = name_idx + 1 | |
| depth = 0 | |
| eq_idx: int | None = None | |
| while j < n: | |
| tok = tokens[j] | |
| if tok[0] == "PUNCT" and tok[1] in "([{<": | |
| depth += 1 | |
| elif tok[0] == "PUNCT" and tok[1] in ")]}>": | |
| depth = max(0, depth - 1) | |
| elif depth == 0 and tok == ("PUNCT", "="): | |
| eq_idx = j | |
| break | |
| elif depth == 0 and tok == ("PUNCT", ";"): | |
| break | |
| j += 1 | |
| if eq_idx is None: | |
| errors.append(f"{rel}: unable to parse const `{const_name}` assignment") | |
| i += 2 | |
| continue | |
| pos = eq_idx + 1 | |
| if pos < n and tokens[pos] == ("PUNCT", "&"): | |
| pos += 1 | |
| matched = _match_delimited_tokens(tokens, pos, "[", "]") | |
| if matched is None: | |
| errors.append( | |
| f"{rel}: const `{const_name}` must initialize an array or slice literal" | |
| ) | |
| i = pos | |
| continue | |
| body_tokens, close_idx = matched | |
| for elem_idx, elem in enumerate(_split_top_level_commas(body_tokens)): | |
| if not elem: | |
| continue | |
| fid, err = _parse_rust_array_element(elem) | |
| if err is not None: | |
| errors.append(f"{rel}: const `{const_name}`[{elem_idx}]: {err}") | |
| elif fid is not None: | |
| ids.add(fid) | |
| i = close_idx + 1 | |
| continue | |
| i += 1 | |
| return ids | |
| def _collect_dir_module_ids( | |
| repo_root: Path, rel: str, errors: list[str] | |
| ) -> set[str]: | |
| rel_path = Path(rel) | |
| dir_path = repo_root / rel_path | |
| if _has_symlink_component(repo_root, rel_path): | |
| errors.append(f"{rel}: symlinks are forbidden") | |
| return set() | |
| if not dir_path.exists(): | |
| return set() | |
| if not dir_path.is_dir(): | |
| errors.append(f"{rel}: expected a regular directory") | |
| return set() | |
| ids: set[str] = set() | |
| for child in sorted(dir_path.iterdir(), key=lambda p: p.name): | |
| if child.is_symlink(): | |
| errors.append(f"{rel}/{child.name}: symlinks are forbidden") | |
| continue | |
| if child.name.startswith("."): | |
| continue | |
| if child.is_dir(): | |
| ids.add(child.name) | |
| elif child.suffix == ".lean": | |
| ids.add(child.stem) | |
| return ids | |
| def _collect_code_site_ids( | |
| repo_root: Path, errors: list[str] | |
| ) -> dict[str, set[str]]: | |
| """Collect unstable feature IDs referenced by every code site.""" | |
| sites: dict[str, set[str]] = {} | |
| # 1. `trusted/locks/cartridges.lock.json` | |
| cart_rel = Path("trusted/locks/cartridges.lock.json") | |
| cart_lock = repo_root / cart_rel | |
| if _has_symlink_component(repo_root, cart_rel): | |
| errors.append("trusted/locks/cartridges.lock.json: symlinks are forbidden") | |
| elif cart_lock.exists(): | |
| if not cart_lock.is_file(): | |
| errors.append("trusted/locks/cartridges.lock.json: expected a regular file") | |
| else: | |
| try: | |
| data = _load_json_no_duplicate_keys(cart_lock.read_text(encoding="utf-8")) | |
| except (OSError, UnicodeDecodeError, json.JSONDecodeError, ValueError) as exc: | |
| errors.append( | |
| f"trusted/locks/cartridges.lock.json: cannot parse JSON: {exc}" | |
| ) | |
| else: | |
| if not isinstance(data, dict) or not isinstance(data.get("cartridges"), list): | |
| errors.append( | |
| "trusted/locks/cartridges.lock.json: expected object with `cartridges` list" | |
| ) | |
| else: | |
| ids: set[str] = set() | |
| for entry in data["cartridges"]: | |
| if isinstance(entry, dict): | |
| stab = entry.get("stability") | |
| if isinstance(stab, str) and stab.startswith("candidate:"): | |
| ids.add(stab[len("candidate:"):]) | |
| if ids: | |
| sites["trusted/locks/cartridges.lock.json"] = ids | |
| # 2. `theory/Anneal/Unstable/<id>` modules | |
| ids = _collect_dir_module_ids(repo_root, "theory/Anneal/Unstable", errors) | |
| if ids: | |
| sites["theory/Anneal/Unstable"] = ids | |
| # 3. `Specs/Unstable/<id>` specification prelude modules | |
| for rel in ("Specs/Unstable", "specs/Specs/Unstable"): | |
| ids = _collect_dir_module_ids(repo_root, rel, errors) | |
| if ids: | |
| sites[rel] = ids | |
| # 4. `cargo-anneal` CLI `-Z` table (pre- and post-PR 1.1 paths) | |
| for rel in ( | |
| "trusted/cargo-anneal/src/unstable.rs", | |
| "tools/cargo-anneal/cargo-anneal/src/unstable.rs", | |
| "tools/cargo-anneal/src/unstable.rs", | |
| ): | |
| ids = _extract_rust_const_ids(repo_root, rel, "UNSTABLE_FEATURES", errors) | |
| if ids: | |
| sites[rel] = ids | |
| # 5. Stage-O / Stage-L capture feature tables | |
| for rel in ( | |
| "trusted/rustc-capture/src/lib.rs", | |
| "trusted/mir-dump/src/lib.rs", | |
| "trusted/anneal-lower/src/lib.rs", | |
| ): | |
| ids = _extract_rust_const_ids( | |
| repo_root, rel, "CAPTURE_UNSTABLE_FEATURES", errors | |
| ) | |
| if ids: | |
| sites[rel] = ids | |
| # 6. `tools/anneal-spec` preview-lowering table | |
| for rel in ( | |
| "tools/anneal-spec/lower/src/parse.rs", | |
| "tools/anneal-spec/lower/src/lib.rs", | |
| ): | |
| ids = _extract_rust_const_ids( | |
| repo_root, rel, "PREVIEW_UNSTABLE_FEATURES", errors | |
| ) | |
| if ids: | |
| sites[rel] = ids | |
| return sites | |
| def _check_public_sink(rel: str, text: str, errors: list[str]) -> None: | |
| for label, pat in INTERNAL_PATTERNS: | |
| m = pat.search(text) | |
| if m: | |
| errors.append( | |
| f"{rel}: forbidden public-sink pattern ({label}: {m.group(0)!r})" | |
| ) | |
| def check_repo(repo_root: Path) -> list[str]: | |
| """Validate `docs/unstable/` registry and bidirectional code-site parity.""" | |
| errors: list[str] = [] | |
| reg_dir = repo_root / "docs/unstable" | |
| registry_ids: set[str] = set() | |
| if _has_symlink_component(repo_root, Path("docs/unstable")): | |
| return ["docs/unstable: must be a regular directory, not a symlink"] | |
| if reg_dir.exists() and not reg_dir.is_dir(): | |
| return ["docs/unstable: must be a regular directory"] | |
| if reg_dir.is_dir(): | |
| toml_stems: set[str] = set() | |
| md_stems: set[str] = set() | |
| for child in sorted(reg_dir.iterdir(), key=lambda p: p.name): | |
| rel = f"docs/unstable/{child.name}" | |
| if child.is_symlink(): | |
| errors.append(f"{rel}: symlinks are forbidden") | |
| continue | |
| if not child.is_file(): | |
| errors.append(f"{rel}: unexpected subdirectory under docs/unstable/") | |
| continue | |
| if child.name == "README.md": | |
| text = child.read_text(encoding="utf-8", errors="replace") | |
| _check_public_sink(rel, text, errors) | |
| continue | |
| if child.suffix == ".toml": | |
| fid = child.stem | |
| if not FEATURE_ID_RE.fullmatch(fid): | |
| errors.append( | |
| f"{rel}: feature ID `{fid}` must be lowercase snake_case" | |
| ) | |
| continue | |
| toml_stems.add(fid) | |
| elif child.suffix == ".md": | |
| fid = child.stem | |
| if not FEATURE_ID_RE.fullmatch(fid): | |
| errors.append( | |
| f"{rel}: page ID `{fid}` must be lowercase snake_case" | |
| ) | |
| continue | |
| md_stems.add(fid) | |
| else: | |
| errors.append( | |
| f"{rel}: only README.md and <id>.{{toml,md}} are allowed" | |
| ) | |
| for fid in sorted(toml_stems): | |
| toml_path = reg_dir / f"{fid}.toml" | |
| md_path = reg_dir / f"{fid}.md" | |
| toml_rel = f"docs/unstable/{fid}.toml" | |
| md_rel = f"docs/unstable/{fid}.md" | |
| registry_ids.add(fid) | |
| try: | |
| raw = toml_path.read_text(encoding="utf-8") | |
| data = tomllib.loads(raw) | |
| except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError) as exc: | |
| errors.append(f"{toml_rel}: invalid TOML: {exc}") | |
| continue | |
| _check_public_sink(toml_rel, raw, errors) | |
| keys = set(data.keys()) | |
| missing = sorted(REQUIRED_KEYS - keys) | |
| extra = sorted(keys - REQUIRED_KEYS) | |
| if missing: | |
| errors.append(f"{toml_rel}: missing required keys: {', '.join(missing)}") | |
| if extra: | |
| errors.append(f"{toml_rel}: unexpected keys: {', '.join(extra)}") | |
| owners = data.get("owners") | |
| if ( | |
| not isinstance(owners, list) | |
| or not owners | |
| or not all(isinstance(o, str) and HANDLE_RE.fullmatch(o) for o in owners) | |
| ): | |
| errors.append( | |
| f"{toml_rel}: `owners` must be a non-empty list of `@github-handle` strings" | |
| ) | |
| tracking = data.get("tracking_issue") | |
| if not isinstance(tracking, str) or not GITHUB_ISSUE_RE.fullmatch(tracking): | |
| errors.append( | |
| f"{toml_rel}: `tracking_issue` must be a public GitHub issue URL" | |
| ) | |
| review_by = data.get("review_by") | |
| if isinstance(review_by, datetime.date) and not isinstance( | |
| review_by, datetime.datetime | |
| ): | |
| pass | |
| elif isinstance(review_by, str) and ISO_DATE_RE.fullmatch(review_by): | |
| try: | |
| datetime.date.fromisoformat(review_by) | |
| except ValueError: | |
| errors.append( | |
| f"{toml_rel}: `review_by` is not a valid calendar date: {review_by!r}" | |
| ) | |
| else: | |
| errors.append(f"{toml_rel}: `review_by` must be an ISO date YYYY-MM-DD") | |
| gate_test = data.get("gate_test") | |
| if not isinstance(gate_test, str) or not gate_test.strip(): | |
| errors.append(f"{toml_rel}: `gate_test` must be a repo-relative file path") | |
| else: | |
| gt_path = Path(gate_test) | |
| if gt_path.is_absolute() or ".." in gt_path.parts: | |
| errors.append( | |
| f"{toml_rel}: `gate_test` must be a clean relative path: {gate_test!r}" | |
| ) | |
| else: | |
| full_gt = repo_root / gt_path | |
| if ( | |
| _has_symlink_component(repo_root, gt_path) | |
| or not full_gt.is_file() | |
| or not full_gt.resolve().is_relative_to(repo_root.resolve()) | |
| ): | |
| errors.append( | |
| f"{toml_rel}: `gate_test` file does not exist or traverses a symlink: {gate_test!r}" | |
| ) | |
| if fid not in md_stems: | |
| errors.append(f"{toml_rel}: missing matching documentation page `{md_rel}`") | |
| continue | |
| md_text = md_path.read_text(encoding="utf-8", errors="replace") | |
| _check_public_sink(md_rel, md_text, errors) | |
| head = "\n".join(md_text.splitlines()[:20]) | |
| if not HEADER_RE.search(head): | |
| errors.append(f"{md_rel}: missing Fuchsia copyright/license header") | |
| lower_md = md_text.lower() | |
| if "experimental opt-in on `main`" not in lower_md and ( | |
| "experimental opt-in on main" not in lower_md | |
| ): | |
| errors.append( | |
| f"{md_rel}: must include an `Experimental opt-in on main` badge" | |
| ) | |
| if isinstance(tracking, str) and tracking not in md_text: | |
| errors.append( | |
| f"{md_rel}: must link to `tracking_issue` ({tracking})" | |
| ) | |
| if "limitation" not in lower_md: | |
| errors.append(f"{md_rel}: must include a limitations section") | |
| if "graduation" not in lower_md: | |
| errors.append(f"{md_rel}: must include a graduation checklist") | |
| # Markdown pages without a matching TOML must be short redirect stubs. | |
| for fid in sorted(md_stems - toml_stems): | |
| md_path = reg_dir / f"{fid}.md" | |
| md_rel = f"docs/unstable/{fid}.md" | |
| md_text = md_path.read_text(encoding="utf-8", errors="replace") | |
| _check_public_sink(md_rel, md_text, errors) | |
| non_comment = [ | |
| ln.strip() | |
| for ln in md_text.splitlines() | |
| if ln.strip() | |
| and not ln.strip().startswith(("<!--", "-->", "Copyright", "Licensed", "<LICENSE", "license", "This file", "those terms")) | |
| ] | |
| if len(non_comment) > 5 or "graduated" not in md_text.lower(): | |
| errors.append( | |
| f"{md_rel}: missing matching `docs/unstable/{fid}.toml` " | |
| "(non-graduated pages require a TOML entry)" | |
| ) | |
| code_sites = _collect_code_site_ids(repo_root, errors) | |
| all_code_ids: set[str] = set() | |
| for site, ids in sorted(code_sites.items()): | |
| for fid in sorted(ids): | |
| if not FEATURE_ID_RE.fullmatch(fid): | |
| errors.append(f"{site}: invalid unstable feature ID `{fid}`") | |
| continue | |
| all_code_ids.add(fid) | |
| if fid not in registry_ids: | |
| errors.append( | |
| f"{site}: unstable feature `{fid}` has no registry entry " | |
| f"`docs/unstable/{fid}.toml`" | |
| ) | |
| for fid in sorted(registry_ids - all_code_ids): | |
| errors.append( | |
| f"docs/unstable/{fid}.toml: orphaned registry entry (referenced by no code site)" | |
| ) | |
| return errors | |
| def main(argv: Iterable[str] | None = None) -> int: | |
| parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) | |
| parser.add_argument( | |
| "--root", | |
| type=Path, | |
| default=Path(__file__).resolve().parent.parent, | |
| help="repository root (default: parent of ci/)", | |
| ) | |
| parser.add_argument("--json", action="store_true", help="emit JSON report") | |
| args = parser.parse_args(list(argv) if argv is not None else None) | |
| errors = check_repo(args.root.resolve()) | |
| if args.json: | |
| print(json.dumps({"ok": not errors, "errors": errors}, indent=2)) | |
| elif errors: | |
| for err in errors: | |
| print(f"unstable-registry: {err}", file=sys.stderr) | |
| else: | |
| print("unstable-registry: OK") | |
| return 0 if not errors else 1 | |
| if __name__ == "__main__": | |
| sys.exit(main()) |