"""Check that every code and test anchor of the invariants ledger exists at a git ref. usage: python -I ledger_check.py [] A ledger row is a table line whose first cell holds `INV-...`. In its cells, a backticked token that ends in .go is a FILE; a backticked identifier (or Type.Method) is a SYMBOL of the nearest file named before it in the same cell, or, in the test cell, of any file named in that cell. A file must exist at the ref; a symbol must occur in its file as a whole word (for a test: `func Name(`). A symbol with no file in its cell is looked up in the whole tree. A file may be a glob (`volume_lock*.go`). A lower-case token with an underscore (a build tag, a JSON key, a reason string) is not a Go symbol and is not checked. Prints one line per missing anchor and a summary. It reads; it changes nothing. Exit: 0 when every anchor exists; 1 when one is missing; 2 when git fails or no row or anchor was found (an error is never read as a pass). """ import re import subprocess import sys def git(repo, *args): """git's output. A git failure ends the check with exit 2: an error must never read as "no anchors". `git grep` finding nothing (exit 1) is not one.""" r = subprocess.run(["git", "-C", repo] + list(args), capture_output=True, text=True, encoding="utf-8", errors="replace") if r.returncode != 0 and not (args and args[0] == "grep" and r.returncode == 1): print("ledger_check: git %s failed (exit %d): %s" % (" ".join(args[:2]), r.returncode, r.stderr.strip()[:300]), file=sys.stderr) sys.exit(2) return r.stdout def main(): repo, ref = sys.argv[1], sys.argv[2] ledger = sys.argv[3] if len(sys.argv) > 3 else "docs/design/invariants.md" text = git(repo, "show", "%s:%s" % (ref, ledger)) files = set(git(repo, "ls-tree", "-r", "--name-only", ref).split("\n")) cache = {} def body(path): if path not in cache: cache[path] = git(repo, "show", "%s:%s" % (ref, path)) return cache[path] def resolve(tok): """A file token may be a full path or a bare file name.""" if tok in files: return [tok] if "*" in tok: rx = re.compile("^(.*/)?" + "[^/]*".join(re.escape(x) for x in tok.split("*")) + "$") return [f for f in files if rx.match(f)] if "/" not in tok: return [f for f in files if f.endswith("/" + tok)] # a path with a directory matches whole path components only return [f for f in files if f.endswith("/" + tok)] ident = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?(\(\))?$") go_all = None rows = missing = anchors = 0 for n, line in enumerate(text.split("\n"), 1): if not line.startswith("|"): continue cells = [c.strip() for c in line.strip().strip("|").split("|")] m = re.match(r"`(INV-[A-Z0-9-]+)`", cells[0]) if cells else None if not m or len(cells) < 6: continue rows += 1 inv, status = m.group(1), cells[-1] if "ARCHIVED" in status: continue for ci, kind in ((3, "code"), (4, "test")): toks = re.findall(r"`([^`]+)`", cells[ci]) cell_files = [] for t in toks: if t.endswith(".go"): cell_files.append(t) cur = None for t in toks: if t.endswith(".go"): cur = t anchors += 1 if not resolve(t): missing += 1 print("%s (line %d, %s, %s): file %s does not exist" % (inv, n, kind, status, t)) continue if not ident.match(t): continue sym = t.rstrip("()").split(".")[-1] if sym in ("nil", "true", "false") or sym.isupper() or len(sym) < 3: continue if "_" in sym and sym == sym.lower(): # a build tag, a JSON key or a reason string: not a Go symbol continue scope = [cur] if (cur and kind == "code") else cell_files paths = [p for f in scope for p in resolve(f)] anchors += 1 if kind == "test" and sym.startswith(("Test", "Fuzz", "Benchmark")): pat = re.compile(r"func %s\(" % re.escape(sym)) else: pat = re.compile(r"\b%s\b" % re.escape(sym)) if paths: ok = any(pat.search(body(p)) for p in paths) else: if go_all is None: go_all = git(repo, "grep", "-h", "-E", r"^(func|type|var|const|\s+[A-Za-z_]+\s)", ref, "--", "*.go") ok = bool(pat.search(go_all)) if not ok: missing += 1 where = ", ".join(scope) if scope else "the tree" print("%s (line %d, %s, %s): %s not found in %s" % (inv, n, kind, status, t, where)) print("%d rows, %d anchors, %d missing at %s" % (rows, anchors, missing, ref)) if rows == 0 or anchors == 0: print("ledger_check: no ledger rows or anchors found: refusing to pass", file=sys.stderr) sys.exit(2) sys.exit(1 if missing else 0) if __name__ == "__main__": main()