Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 87 additions & 6 deletions ci_kit/declared_literal.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,16 @@

THE POLICY IS THE CALLER'S. The kit ships no pattern, no declared file and no message. A rule is
opened by `--rule LABEL`; the `--pattern` (Python `re`, repeatable, OR'd), `--example TEXT`
(repeatable, REQUIRED), `--declared PATH` (repo-relative, repeatable) and `--message TEXT` flags
after it belong to it. Flags before any `--rule` belong to one implicit rule. `--exempt-suffix
(repeatable, REQUIRED), `--declared PATH` (repo-relative, repeatable), `--exempt-prefix DIR/`
(repeatable) and `--message TEXT` flags after it belong to it. Flags before any `--rule` belong to one implicit rule. `--exempt-suffix
.EXT` (every rule) exempts a file kind from findings, e.g. `.md` when prose may name the value.

AN EXEMPT PREFIX EXPIRES ITSELF. `--exempt-prefix DIR/` (one rule, a directory ending `/`) excuses
that rule's matches under DIR -- a tree imported whole that will be repointed later, say. It is
debt, so it must be able to end: the files under it are still READ, every excused line is counted
and named in the summary, and a prefix that holds no tracked file (a wrong path) or no live match
any more (the debt is paid) is exit 2 until the flag is deleted. It never excuses another rule.

A RULE MUST PROVE IT CAN FIRE. A pattern that cannot match the value it guards (a stray trailing
space, a doubled backslash) would scan the tree and report clean forever. So: every `--example`
must be flagged as a live line by the rule, and every `--pattern` must match at least one example;
Expand Down Expand Up @@ -83,7 +89,7 @@
POWERSHELL_SUFFIXES = frozenset({".ps1", ".psm1", ".psd1"})
DEFAULT_MESSAGE = "Read the value from the declared source instead; a comment line may keep it for history."
VALUE_FLAGS = frozenset({"--root", "--rule", "--pattern", "--example", "--declared", "--message",
"--exempt-suffix", "--comment-prefix"})
"--exempt-suffix", "--comment-prefix", "--exempt-prefix"})

#: The openers the predecessor honoured in EVERY file. Each family below is a subset of it.
OLD_OPENERS = ("#", "//", "<!--", ";", "*", "--")
Expand Down Expand Up @@ -123,12 +129,17 @@ class Rule:
patterns: list[str] = dataclasses.field(default_factory=list)
examples: list[str] = dataclasses.field(default_factory=list)
declared: list[str] = dataclasses.field(default_factory=list)
exempt_prefixes: list[str] = dataclasses.field(default_factory=list)
message: str = ""
compiled: list[re.Pattern[str]] = dataclasses.field(default_factory=list)

def hits(self, code: str) -> bool:
return any(p.search(code) for p in self.compiled)

def exempt_by(self, rel: str) -> str | None:
"""The `--exempt-prefix` excusing this rule at `rel`, or None."""
return next((p for p in self.exempt_prefixes if rel.startswith(p)), None)


# ---------------------------------------------------------------- the policy (argv + args files)
def _rules(ns: argparse.Namespace) -> list[Rule]:
Expand All @@ -143,7 +154,8 @@ def __call__(self, parser, ns, value, option_string=None): # type: ignore[overr


class _ToRule(argparse.Action):
"""`--pattern` / `--example` / `--declared` / `--message` attach to the rule opened last."""
"""`--pattern` / `--example` / `--declared` / `--exempt-prefix` / `--message` attach to the
rule opened last."""

def __call__(self, parser, ns, value, option_string=None): # type: ignore[override]
rules = _rules(ns)
Expand Down Expand Up @@ -228,9 +240,20 @@ def compile_rules(rules: list[Rule], comments: Mapping[str, tuple[str, ...]] | N
rule.compiled.append(rx)
_prove(rule, comments or {})
rule.declared = [d.replace("\\", "/").removeprefix("./") for d in rule.declared]
rule.exempt_prefixes = [_prefix(name, p) for p in rule.exempt_prefixes]
return rules


def _prefix(name: str, value: str) -> str:
"""A repo-relative DIRECTORY prefix ending `/` -- never the whole tree, never outside it."""
p = value.replace("\\", "/").removeprefix("./")
if (not p.endswith("/") or p == "/" or p.startswith("/") or ".." in p.split("/")
or p != p.strip() or "//" in p):
raise ConfigError(f"{name}: --exempt-prefix {value!r} is not a repo-relative directory "
f"ending '/' (like vendor/): a bare name would also excuse vendored.sh")
return p


def _prove(rule: Rule, comments: Mapping[str, tuple[str, ...]]) -> None:
"""The rule's own must-fire proof: every example is a finding, every pattern fires on one."""
name = f"rule {rule.label!r}"
Expand Down Expand Up @@ -358,7 +381,7 @@ def findings_in(text: str, rel: str, rules: Sequence[Rule],
"""[(line, rule label, the line)] for each live line a rule matches outside its declared files.

Lines are numbered by LF; each is split again at every other line break and judged per piece."""
live = [r for r in rules if rel not in r.declared]
live = [r for r in rules if rel not in r.declared and r.exempt_by(rel) is None]
if not live:
return []
table = COMMENT_FAMILIES if comments is None else comments
Expand Down Expand Up @@ -390,6 +413,8 @@ class Scan:
exempt: int = 0
declared_only: int = 0
skipped: int = 0
# (rule label, prefix) -> [tracked files under it, live matches it excused]
excused: dict[tuple[str, str], list[int]] = dataclasses.field(default_factory=dict)


def tracked_all(root: pathlib.Path) -> list[str]:
Expand Down Expand Up @@ -421,6 +446,7 @@ def readings(data: bytes) -> list[str]:
def scan(root: pathlib.Path, rules: Sequence[Rule], exempt_suffixes: frozenset[str],
comments: Mapping[str, tuple[str, ...]]) -> Scan:
out = Scan()
out.excused = {(r.label, p): [0, 0] for r in rules for p in r.exempt_prefixes}
blind: list[str] = []
for rel in tracked_all(root):
path = root / rel
Expand Down Expand Up @@ -455,6 +481,14 @@ def scan(root: pathlib.Path, rules: Sequence[Rule], exempt_suffixes: frozenset[s
if (ln, label) not in seen:
seen.add((ln, label))
out.findings.append((rel, ln, label, line))
_count_excused(out, rel, texts, rules, comments)
for (label, prefix), (files, lines) in out.excused.items():
if not files:
blind.append(f"rule {label!r}: --exempt-prefix {prefix} holds no tracked file read by the "
f"rule -- a wrong path; delete the flag")
elif not lines:
blind.append(f"rule {label!r}: --exempt-prefix {prefix} excuses nothing any more ({files} "
f"file(s), 0 live matches) -- the debt is paid; delete the flag")
if blind:
print(f"{GATE}: DID NOT FINISH LOOKING -- {len(blind)} problem(s):", file=sys.stderr)
for b in blind[:20]:
Expand All @@ -463,12 +497,27 @@ def scan(root: pathlib.Path, rules: Sequence[Rule], exempt_suffixes: frozenset[s
return out


def _count_excused(out: Scan, rel: str, texts: list[str], rules: Sequence[Rule],
comments: Mapping[str, tuple[str, ...]]) -> None:
"""Judge an excused file under its rule as if it were not excused, and count what was let off."""
for r in rules:
prefix = r.exempt_by(rel)
if prefix is None or rel in r.declared:
continue
tally = out.excused[(r.label, prefix)]
tally[0] += 1
probe = Rule(label=r.label, compiled=r.compiled)
tally[1] += len({ln for t in texts for ln, _, _ in findings_in(t, rel, [probe], comments)})


def _summary(seen: Scan, rules: Sequence[Rule], root: pathlib.Path) -> str:
present = sum(1 for r in rules for d in r.declared if (root / d).is_file())
declared = sum(len(r.declared) for r in rules)
return (f"{seen.read} tracked file(s) read ({seen.exempt} exempt by suffix, {seen.declared_only} "
f"declared-only, {seen.skipped} directory/gitlink/dangling link skipped); {len(rules)} rule(s) loaded: "
f"{', '.join(r.label for r in rules)}; {present}/{declared} declared file(s) present")
f"{', '.join(r.label for r in rules)}; {present}/{declared} declared file(s) present"
+ "".join(f"; [{label}] {lines} line(s) in {files} file(s) EXCUSED under {prefix}"
for (label, prefix), (files, lines) in seen.excused.items()))


def _report(seen: Scan, rules: Sequence[Rule], root: pathlib.Path) -> None:
Expand Down Expand Up @@ -575,6 +624,37 @@ def _cases(tmp: pathlib.Path) -> list[str]:
rc, _ = _run_quiet(_repo(tmp, "empty", {}), _SELF_RULES)
if rc != 2:
fails.append(f"zero tracked files: exit {rc} (want 2 -- it did not look)")
return fails + _prefix_cases(tmp)


def _prefix_cases(tmp: pathlib.Path) -> list[str]:
"""`--exempt-prefix`: excuses its own rule under its directory only, and expires itself."""
fails: list[str] = []
other = ["--rule", "other", "--pattern", "OTHERVAL", "--example", "X=OTHERVAL"]
files = {"conf/values.env": f"GATEWAY={NET}1\n", "a.sh": "GW=$GATEWAY\n",
"vendor/v.sh": f"GW={NET}1\n# {NET}2 history\n", "vendored.sh": "x=1\n"}
tree = _repo(tmp, "prefix", files)
rc, out = _run_quiet(tree, [*_SELF_RULES, "--exempt-prefix", "vendor/"])
if rc != 0 or "1 line(s) in 1 file(s) EXCUSED under vendor/" not in out:
fails.append(f"--exempt-prefix vendor/: exit {rc} (want 0, 1 line excused): {out.strip()[-200:]}")
rc, out = _run_quiet(tree, _SELF_RULES)
if rc != 1 or "vendor/v.sh:1" not in out:
fails.append(f"no --exempt-prefix: exit {rc} (want 1, vendor/v.sh:1 flagged)")
loud = _repo(tmp, "prefix-other", {**files, "vendor/o.sh": "Y=OTHERVAL\n"})
rc, out = _run_quiet(loud, [*_SELF_RULES, "--exempt-prefix", "vendor/", *other])
if rc != 1 or "vendor/o.sh:1: [other]" not in out:
fails.append(f"a prefix excused ANOTHER rule: exit {rc} (want 1, vendor/o.sh:1 [other])")
paid = _repo(tmp, "prefix-paid", {**files, "vendor/v.sh": "GW=$GATEWAY\n"})
for label, root, args in (
("prefix with no live match left", paid, [*_SELF_RULES, "--exempt-prefix", "vendor/"]),
("prefix holding no tracked file", tree, [*_SELF_RULES, "--exempt-prefix", "nope/"]),
("prefix without a trailing /", tree, [*_SELF_RULES, "--exempt-prefix", "vendor"]),
("prefix that is the whole tree", tree, [*_SELF_RULES, "--exempt-prefix", "/"]),
("prefix climbing out", tree, [*_SELF_RULES, "--exempt-prefix", "../vendor/"]),
):
rc, out = _run_quiet(root, args)
if rc != 2:
fails.append(f"{label}: exit {rc} (want 2): {out.strip()[:200]}")
return fails


Expand Down Expand Up @@ -614,6 +694,7 @@ def _parser() -> argparse.ArgumentParser:
p.add_argument("--pattern", dest="patterns", action=_ToRule, metavar="REGEX")
p.add_argument("--example", dest="examples", action=_ToRule, metavar="TEXT")
p.add_argument("--declared", dest="declared", action=_ToRule, metavar="PATH")
p.add_argument("--exempt-prefix", dest="exempt_prefixes", action=_ToRule, metavar="DIR/")
p.add_argument("--message", dest="message", action=_ToRule, metavar="TEXT")
p.add_argument("--exempt-suffix", type=_suffix, action="append", default=[], metavar=".EXT")
p.add_argument("--comment-prefix", type=_comment_prefix, action="append", default=[], metavar="KEY=PREFIX")
Expand Down
4 changes: 4 additions & 0 deletions docs/gates/secrets.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,10 @@ nets
bad or empty-matching regex, or zero files read is exit 2.
- Several `--rule` blocks may share one file, each with its own declared set. `--exempt-suffix` is
matched as written: `.md` does not exempt `NOTES.MD`.
- **An exempt prefix expires itself** (v1.96.0). `--exempt-prefix DIR/` inside a rule excuses that
rule only, under that directory only (a tree imported whole, to be repointed later). The files
are still read: the summary names how many lines it excused, and a prefix holding no tracked file
or no live match any more is exit 2 until the flag is deleted -- the debt cannot outlive itself.
- **Comments.** Comment lines are exempt, never more than the predecessor gate exempted (a
differential test holds it). Comment openers depend on the file kind, each a subset of the
predecessor's six; `--comment-prefix .j2={#` adds one (`*` = every file but PowerShell, whose
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "ci-kit"
version = "1.95.0"
version = "1.96.0"
description = "Reusable CI gates: the doc-reference gate, the secret-argv lint, the hidden-Unicode gate, the consumer-word purity gate, the armed-PR updater and its heal ladder, the merge train, the pin-drift check, the agent-manual lint, the guard self-proof gate, the hand .env-read ratchet, the unread-config-field ratchet, the line-cap, function-clone, test-standin, untested-module, guards-have-tests, HTTP-client and SQL-placement ratchets, the blind-parse, quarantine, cog, image-PR-filter, migration-number per-stage dependency-closure and per-stage reachable-import (`lock` extra) gates, the duplicate-code gate (jscpd behind a shrink-only baseline), the OpenAPI breaking-change gate (oasdiff), the skip-green CI aggregate gate and the setup-uv pin gate (`workflow` extra), the pre-merge model review gate (`review` extra), the self-hosted runner capacity kit (`runners` extra: schema, budgets, render, the jq admission rule and its Python twin), the GitHub App audit (`apps` extra: a declared App manifest held to live) and the pr-token record reader, the lint-gate kit (ratchet, discover, site_lint), and parsed-SQL gates and the code-edge reader behind the `sql` extra. Every gate exits 0 clean / 1 findings / 2 could-not-look."
readme = "README.md"
license = "MIT"
Expand Down
2 changes: 1 addition & 1 deletion uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.