From c53ca61b735c374baba8bb856a12d23a25ce7427 Mon Sep 17 00:00:00 2001 From: marregui Date: Mon, 2 Nov 2026 19:45:58 +0100 Subject: [PATCH 1/2] 2.0.4: version line names the release (2.0.2 and 2.0.3 left it at 2.0.1) --- CHANGELOG.md | 5 +++++ RULES.md | 2 +- STANDARD.md | 2 +- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4432878..5e2eba5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## 2.0.4 (2026-11-02) + +- The version line of `STANDARD.md`, and with it the header of `RULES.md`, still read 2.0.1 at the 2.0.2 and 2.0.3 + tags. Both now name the release. No rule changed. + ## 2.0.3 (2026-10-31) - G-11.6: the Finding reported every `Closeable` outside `try`-with-resources, so the per-class fixture its title asks diff --git a/RULES.md b/RULES.md index 418cad0..34afb1f 100644 --- a/RULES.md +++ b/RULES.md @@ -1,6 +1,6 @@ # Rules index -Generated from [`STANDARD.md`](STANDARD.md) v2.0.1 by `tools/rules.py`; do not edit by hand. One row per +Generated from [`STANDARD.md`](STANDARD.md) v2.0.4 by `tools/rules.py`; do not edit by hand. One row per rule. Read the rule's block in the standard before applying it or reporting a finding against it. | ID | Rule | Scope | Class | Checked by | Finding | diff --git a/STANDARD.md b/STANDARD.md index d7c4541..bf21eaf 100644 --- a/STANDARD.md +++ b/STANDARD.md @@ -1,6 +1,6 @@ # Java Coding Standard -Version 2.0.1, 2026-10-30. JDK 25 baseline. +Version 2.0.4, 2026-11-02. JDK 25 baseline. This standard says how Java is written, changed and judged in the repositories that follow it. Its first readers are coding agents (Claude, Codex) that write, change and review code; its second readers are the engineers who own that From 42fdc5f9ed1d90642a75a8d4e2b8708114fcaed0 Mon Sep 17 00:00:00 2001 From: marregui Date: Tue, 3 Nov 2026 01:15:01 +0100 Subject: [PATCH 2/2] tools/rules.py brought to the Python standard, with its test in CI --- .github/workflows/check.yml | 1 + CHANGELOG.md | 2 + README.md | 2 +- tools/rules.py | 168 ++++++++++++++++++++++-------------- tools/test_rules.py | 135 +++++++++++++++++++++++++++++ 5 files changed, 241 insertions(+), 67 deletions(-) create mode 100644 tools/test_rules.py diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index f5ca957..45a5122 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -12,4 +12,5 @@ jobs: - uses: actions/setup-python@v5 with: python-version: "3.12" + - run: python3 -I tools/test_rules.py - run: python3 tools/rules.py --check diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e2eba5..13d211b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ - The version line of `STANDARD.md`, and with it the header of `RULES.md`, still read 2.0.1 at the 2.0.2 and 2.0.3 tags. Both now name the release. No rule changed. +- `tools/rules.py`: options through `argparse` (`--root` added for tests), rules as records, UTF-8 reads and writes, + failures on stderr; `tools/test_rules.py` covers it and runs in CI. `RULES.md` is generated unchanged. ## 2.0.3 (2026-10-31) diff --git a/README.md b/README.md index f04f544..49a8b79 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ is checked, whether a violation is a defect or a rule, and what counts as a find | [`RULES.md`](RULES.md) | Every rule in one table, generated from `STANDARD.md`; the file an agent loads first | | [`config/checkstyle/checkstyle.xml`](config/checkstyle/checkstyle.xml) | The checks javac cannot make (G-10.2, G-10.8, G-10.11); a repository copies the file of the tag it follows and sets `projectPackagePattern` from its Apply section | | [`CHANGELOG.md`](CHANGELOG.md) | What each version changed | -| [`tools/rules.py`](tools/rules.py) | Checks every rule block and regenerates `RULES.md`; CI runs `tools/rules.py --check` | +| [`tools/rules.py`](tools/rules.py) | Checks every rule block and regenerates `RULES.md`; CI runs its test, [`tools/test_rules.py`](tools/test_rules.py), then `tools/rules.py --check` | ## Following it in a repository diff --git a/tools/rules.py b/tools/rules.py index 2ae95eb..fbdd795 100644 --- a/tools/rules.py +++ b/tools/rules.py @@ -1,105 +1,134 @@ #!/usr/bin/env python3 """Checks STANDARD.md and writes RULES.md, the one-table index agents load first. -usage: rules.py check STANDARD.md, then write RULES.md - rules.py --check check STANDARD.md and that RULES.md is up to date; write nothing +usage: rules.py [--root DIR] check STANDARD.md, then write RULES.md + rules.py [--root DIR] --check check STANDARD.md and that RULES.md is up to date; write nothing -Exit 0 when every check passes; otherwise every failure is printed as `STANDARD.md:: ` and the exit is 1. +Reads `STANDARD.md` and `tools/released-ids.txt` under the repository root (`--root`, default the parent of this +script's folder); writes `RULES.md` there unless `--check` is given or a check fails. + +Exit 0 when every check passes; 1 when one fails, every failure printed to stderr as `STANDARD.md:: ` +(or `RULES.md: `); 2 on a usage error. The count of rules and failures goes to stdout. """ from __future__ import annotations +import argparse import re import sys +from collections.abc import Sequence +from dataclasses import dataclass, replace +from itertools import pairwise from pathlib import Path -ROOT = Path(__file__).resolve().parent.parent -STANDARD = ROOT / "STANDARD.md" -INDEX = ROOT / "RULES.md" -RELEASED = ROOT / "tools" / "released-ids.txt" +DEFAULT_ROOT = Path(__file__).resolve().parent.parent HEADING = re.compile(r"^### G-(\d+)\.(\d+) (\S.*)$") META = re.compile(r"^\*\*Scope:\*\* (.+?) · \*\*From:\*\* (.+?) · \*\*Checked by:\*\* (.+?) · \*\*Class:\*\* (.+)$") -SCOPES = {"everywhere", "everywhere except hot path", "hot path"} CONDITION_ROW = re.compile(r"^\| ([^|*]+?) \| ") -CLASSES = {"defect", "rule"} -PRINCIPLES = {f"P{n}" for n in range(1, 8)} -CHECKS = {"build", "test", "measure", "review"} - - -def conditions(lines: list[str]) -> set[str]: +CONDITION_TABLE = "| Condition (*skip unless*)" +FINDING = "**Finding:** " +SCOPES = frozenset({"everywhere", "everywhere except hot path", "hot path"}) +CLASSES = frozenset({"defect", "rule"}) +PRINCIPLES = frozenset(f"P{n}" for n in range(1, 8)) +CHECKS = frozenset({"build", "test", "measure", "review"}) +# a rule's Scope line sits within this many lines after its heading +META_REACH = 11 + + +@dataclass(frozen=True, slots=True) +class Rule: + """One rule block of the standard: its heading, where it is, and its Scope line and Finding.""" + + rule_id: str + key: tuple[int, int] + title: str + line: int + scope: str = "" + principles: str = "" + checks: str = "" + klass: str = "" + finding: str = "" + + +def conditions(lines: Sequence[str]) -> set[str]: """The skip-unless conditions defined by the table under "How to read a rule".""" - start = next(i for i, l in enumerate(lines) if l.startswith("| Condition (*skip unless*)")) + start = next(i for i, line in enumerate(lines) if line.startswith(CONDITION_TABLE)) found = set() for line in lines[start + 2:]: - m = CONDITION_ROW.match(line) - if not m: + match = CONDITION_ROW.match(line) + if not match: break - found.update(c.strip() for c in m[1].split(",")) + found.update(c.strip() for c in match[1].split(",")) return found -def parse(lines: list[str]) -> tuple[list[dict], list[str]]: +def parse(lines: Sequence[str]) -> tuple[list[Rule], list[str]]: """The rule blocks of the standard, outside fenced code, and every format failure found.""" - rules, failures, fenced = [], [], False + rules: list[Rule] = [] + failures: list[str] = [] + fenced = False allowed = SCOPES | {f"skip unless {c}" for c in conditions(lines)} for i, line in enumerate(lines): if line.startswith("```"): fenced = not fenced continue - m = HEADING.match(line) - if fenced or not m: + heading = HEADING.match(line) + if fenced or not heading: continue - rule = {"id": f"G-{m[1]}.{m[2]}", "key": (int(m[1]), int(m[2])), "title": m[3], "line": i + 1} - rest = [l for l in lines[i + 1:i + 12]] - nonblank = [l for l in rest if l.strip()] - if "Withdrawn in" in (nonblank[0] if nonblank else ""): - rule.update(scope="withdrawn", principles="", checks="", klass="", finding=nonblank[0].strip("*_ ")) - rules.append(rule) + rule = Rule(f"G-{heading[1]}.{heading[2]}", (int(heading[1]), int(heading[2])), heading[3], i + 1) + nonblank = [n for n in lines[i + 1:i + 1 + META_REACH] if n.strip()] + if nonblank and "Withdrawn in" in nonblank[0]: + rules.append(replace(rule, scope="withdrawn", finding=nonblank[0].strip("*_ "))) continue meta = META.match(nonblank[0]) if nonblank else None if not meta: - failures.append(f"STANDARD.md:{i + 1}: {rule['id']} has no Scope · From · Checked by · Class line") + failures.append(f"STANDARD.md:{i + 1}: {rule.rule_id} has no Scope · From · Checked by · Class line") continue scope, principles, checks, klass = meta[1], meta[2], meta[3], meta[4] if klass not in CLASSES: - failures.append(f"STANDARD.md:{i + 1}: {rule['id']} has an unknown class '{klass}'") + failures.append(f"STANDARD.md:{i + 1}: {rule.rule_id} has an unknown class '{klass}'") if scope not in allowed: - failures.append(f"STANDARD.md:{i + 1}: {rule['id']} has an unknown scope '{scope}'") + failures.append(f"STANDARD.md:{i + 1}: {rule.rule_id} has an unknown scope '{scope}'") if not {p.strip() for p in principles.split(",")} <= PRINCIPLES: - failures.append(f"STANDARD.md:{i + 1}: {rule['id']} names an unknown principle in '{principles}'") + failures.append(f"STANDARD.md:{i + 1}: {rule.rule_id} names an unknown principle in '{principles}'") if not {c.strip() for c in checks.split(",")} <= CHECKS: - failures.append(f"STANDARD.md:{i + 1}: {rule['id']} has an unknown check in '{checks}'") + failures.append(f"STANDARD.md:{i + 1}: {rule.rule_id} has an unknown check in '{checks}'") start = lines.index(nonblank[1], i + 1) if len(nonblank) > 1 else -1 - if start < 0 or not lines[start].startswith("**Finding:** "): - failures.append(f"STANDARD.md:{i + 1}: {rule['id']} has no Finding line after its Scope line") + if start < 0 or not lines[start].startswith(FINDING): + failures.append(f"STANDARD.md:{i + 1}: {rule.rule_id} has no Finding line after its Scope line") continue - finding = [] - for l in lines[start:]: - if not l.strip(): + finding: list[str] = [] + for text in lines[start:]: + if not text.strip(): break - finding.append(l.strip()) - rule.update(scope=scope, principles=principles, checks=checks, klass=klass, - finding=" ".join(finding)[len("**Finding:** "):]) - rules.append(rule) + finding.append(text.strip()) + rules.append(replace(rule, scope=scope, principles=principles, checks=checks, klass=klass, + finding=" ".join(finding)[len(FINDING):])) return rules, failures -def check(rules: list[dict]) -> list[str]: +def check(rules: Sequence[Rule], released: Sequence[str]) -> list[str]: """IDs unique, in order, and every released ID still present.""" - failures, seen = [], {} - for prev, rule in zip([None] + rules, rules): - if rule["id"] in seen: - failures.append(f"STANDARD.md:{rule['line']}: {rule['id']} also at line {seen[rule['id']]}") - seen[rule["id"]] = rule["line"] - if prev and rule["key"] <= prev["key"]: - failures.append(f"STANDARD.md:{rule['line']}: {rule['id']} comes after {prev['id']}") - for rid in RELEASED.read_text().split(): - if rid not in seen: - failures.append(f"STANDARD.md: released rule {rid} is missing; withdraw it, never remove it") + failures: list[str] = [] + seen: dict[str, int] = {} + for rule in rules: + if rule.rule_id in seen: + failures.append(f"STANDARD.md:{rule.line}: {rule.rule_id} also at line {seen[rule.rule_id]}") + seen[rule.rule_id] = rule.line + for prev, rule in pairwise(rules): + if rule.key <= prev.key: + failures.append(f"STANDARD.md:{rule.line}: {rule.rule_id} comes after {prev.rule_id}") + failures.extend(f"STANDARD.md: released rule {rid} is missing; withdraw it, never remove it" + for rid in released if rid not in seen) return failures -def render(rules: list[dict], version: str) -> str: +def version_of(lines: Sequence[str]) -> str: + """The release the version line names, `v2.0.4` for `Version 2.0.4, 2026-11-02`; empty without one.""" + return next((line.split(",")[0].replace("Version ", "v") for line in lines if line.startswith("Version ")), "") + + +def render(rules: Sequence[Rule], version: str) -> str: """RULES.md: one row per rule, in the standard's order.""" out = [ "# Rules index", @@ -110,25 +139,32 @@ def render(rules: list[dict], version: str) -> str: "| ID | Rule | Scope | Class | Checked by | Finding |", "|---|---|---|---|---|---|", ] - for r in rules: - cells = [r["id"], r["title"], r["scope"], r["klass"], r["checks"], r["finding"]] + for rule in rules: + cells = [rule.rule_id, rule.title, rule.scope, rule.klass, rule.checks, rule.finding] out.append("| " + " | ".join(c.replace("|", "\\|") for c in cells) + " |") return "\n".join(out) + "\n" -def main() -> int: - lines = STANDARD.read_text().splitlines() - version = next((l.split(",")[0].replace("Version ", "v") for l in lines if l.startswith("Version ")), "") +def main(argv: Sequence[str] | None = None) -> int: + """Checks the standard under the root; writes its index, or with `--check` compares it. Returns the exit code.""" + parser = argparse.ArgumentParser(description="Check STANDARD.md and write RULES.md, its one-table index.") + parser.add_argument("--check", action="store_true", help="also check RULES.md is up to date; write nothing") + parser.add_argument("--root", type=Path, default=DEFAULT_ROOT, + help="the repository root holding STANDARD.md (default: the parent of tools/)") + args = parser.parse_args(argv) + index = args.root / "RULES.md" + lines = (args.root / "STANDARD.md").read_text(encoding="utf-8").splitlines() + released = (args.root / "tools" / "released-ids.txt").read_text(encoding="utf-8").split() rules, failures = parse(lines) - failures += check(rules) - text = render(rules, version) - if "--check" in sys.argv[1:]: - if not INDEX.exists() or INDEX.read_text() != text: + failures += check(rules, released) + text = render(rules, version_of(lines)) + if args.check: + if not index.exists() or index.read_text(encoding="utf-8") != text: failures.append("RULES.md: out of date; run tools/rules.py") elif not failures: - INDEX.write_text(text) - for f in failures: - print(f) + index.write_text(text, encoding="utf-8") + for failure in failures: + print(failure, file=sys.stderr) print(f"{len(rules)} rules, {len(failures)} failure(s)") return 1 if failures else 0 diff --git a/tools/test_rules.py b/tools/test_rules.py new file mode 100644 index 0000000..18b8bae --- /dev/null +++ b/tools/test_rules.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +"""Tests of rules.py on small standards written to temporary repository roots. + +usage: python3 -I tools/test_rules.py (exit 0 when every test passes, 1 otherwise) +""" +from __future__ import annotations + +import contextlib +import importlib.util +import io +import sys +import tempfile +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +SPEC = importlib.util.spec_from_file_location("rules", HERE / "rules.py") +rules = importlib.util.module_from_spec(SPEC) +sys.modules["rules"] = rules +SPEC.loader.exec_module(rules) + +HEAD = """# Standard + +Version 9.9.1, 2026-11-03 + +| Condition (*skip unless*) | Meaning | +|---|---| +| native memory, native code | the code holds memory outside the heap | + +""" + +FIRST = """### G-1.1 First rule + +**Scope:** everywhere · **From:** P1 · **Checked by:** build · **Class:** rule + +**Finding:** A thing that +wraps onto a second line. +""" + +SECOND = """### G-1.2 Second rule + +**Scope:** skip unless native code · **From:** P2, P3 · **Checked by:** review, test · **Class:** defect + +**Finding:** A cell with a | pipe. +""" + +WITHDRAWN = """### G-1.3 Gone rule + +*Withdrawn in 2.0.0: merged into G-1.1.* +""" + +FENCED = """```markdown +### G-0.1 An example heading inside fenced code +``` +""" + + +class RulesTest(unittest.TestCase): + """rules.main: checks a standard, writes its index, and compares it with --check.""" + + def root(self, standard: str, released: str = "G-1.1\n") -> Path: + """A repository root holding `standard` as STANDARD.md and `released` as the released IDs.""" + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + root = Path(tmp.name) + (root / "tools").mkdir() + (root / "STANDARD.md").write_text(standard, encoding="utf-8") + (root / "tools" / "released-ids.txt").write_text(released, encoding="utf-8") + return root + + def run_main(self, *argv: str) -> tuple[int, str, str]: + """The exit code, stdout and stderr of one run.""" + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + code = rules.main(list(argv)) + return code, out.getvalue(), err.getvalue() + + def test_writes_one_row_per_rule_and_then_checks_clean(self) -> None: + root = self.root(HEAD + FENCED + FIRST + "\n" + SECOND + "\n" + WITHDRAWN) + + code, out, err = self.run_main("--root", str(root)) + self.assertEqual((code, err), (0, "")) + self.assertEqual(out, "3 rules, 0 failure(s)\n") + index = (root / "RULES.md").read_text(encoding="utf-8") + self.assertIn("[`STANDARD.md`](STANDARD.md) v9.9.1 by", index) + rows = [line for line in index.splitlines() if line.startswith("| G-")] + self.assertEqual(rows, [ + "| G-1.1 | First rule | everywhere | rule | build | A thing that wraps onto a second line. |", + "| G-1.2 | Second rule | skip unless native code | defect | review, test | A cell with a \\| pipe. |", + "| G-1.3 | Gone rule | withdrawn | | | Withdrawn in 2.0.0: merged into G-1.1. |", + ]) + self.assertEqual(self.run_main("--root", str(root), "--check")[0], 0) + + def test_check_reports_a_stale_index_and_writes_nothing(self) -> None: + root = self.root(HEAD + FIRST) + (root / "RULES.md").write_text("stale\n", encoding="utf-8") + + code, _, err = self.run_main("--root", str(root), "--check") + self.assertEqual(code, 1) + self.assertEqual(err, "RULES.md: out of date; run tools/rules.py\n") + self.assertEqual((root / "RULES.md").read_text(encoding="utf-8"), "stale\n") + + def test_each_broken_standard_fails_with_its_line_and_writes_no_index(self) -> None: + cases = [ + ("duplicate id", HEAD + FIRST + "\n" + FIRST, "G-1.1", + "STANDARD.md:16: G-1.1 also at line 9"), + ("out of order", HEAD + SECOND + "\n" + FIRST, "", + "STANDARD.md:15: G-1.1 comes after G-1.2"), + ("released id missing", HEAD + FIRST, "G-1.1 G-1.9", + "STANDARD.md: released rule G-1.9 is missing; withdraw it, never remove it"), + ("unknown class", HEAD + FIRST.replace("**Class:** rule", "**Class:** hint"), "G-1.1", + "STANDARD.md:9: G-1.1 has an unknown class 'hint'"), + ("unknown scope", HEAD + FIRST.replace("everywhere", "skip unless tuesday"), "G-1.1", + "STANDARD.md:9: G-1.1 has an unknown scope 'skip unless tuesday'"), + ("unknown principle", HEAD + FIRST.replace("**From:** P1", "**From:** P1, P8"), "G-1.1", + "STANDARD.md:9: G-1.1 names an unknown principle in 'P1, P8'"), + ("unknown check", HEAD + FIRST.replace("**Checked by:** build", "**Checked by:** build, hope"), "G-1.1", + "STANDARD.md:9: G-1.1 has an unknown check in 'build, hope'"), + ("no Scope line", HEAD + "### G-1.1 First rule\n\nJust prose.\n", "G-1.1", + "STANDARD.md:9: G-1.1 has no Scope · From · Checked by · Class line"), + ("no Finding line", HEAD + FIRST.replace("**Finding:** ", "Found: "), "G-1.1", + "STANDARD.md:9: G-1.1 has no Finding line after its Scope line"), + ] + for name, standard, released, failure in cases: + with self.subTest(name): + root = self.root(standard, released) + code, out, err = self.run_main("--root", str(root)) + self.assertEqual(code, 1) + self.assertIn(failure + "\n", err) + self.assertRegex(out, r"^\d+ rules, [1-9]\d* failure\(s\)\n$") + self.assertFalse((root / "RULES.md").exists()) + + +if __name__ == "__main__": + unittest.main()