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
1 change: 1 addition & 0 deletions .github/workflows/check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# 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.
- `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)

- G-11.6: the Finding reported every `Closeable` outside `try`-with-resources, so the per-class fixture its title asks
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion RULES.md
Original file line number Diff line number Diff line change
@@ -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 |
Expand Down
2 changes: 1 addition & 1 deletion STANDARD.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
168 changes: 102 additions & 66 deletions tools/rules.py
Original file line number Diff line number Diff line change
@@ -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:<line>: <what>` 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:<line>: <what>`
(or `RULES.md: <what>`); 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",
Expand All @@ -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

Expand Down
Loading
Loading