Skip to main content

Check a repository

This tutorial runs the static check on a sample repository and breaks it in three ways. Every cell is live: it builds the repository in a temporary directory and calls the babregen command line.

import subprocess
import sys
import tempfile
from pathlib import Path

from babregen import make_sample_repo

tmp = tempfile.TemporaryDirectory()
root = make_sample_repo(Path(tmp.name) / "demo")


def babregen(*args, drop=None):
    """Run `babregen` in the sample repository; show the call and its output."""
    done = subprocess.run(
        [sys.executable, "-m", "babregen", *args],
        cwd=root,
        capture_output=True,
        text=True,
        check=False,
    )
    print("$ babregen", *args)
    lines = (done.stdout + done.stderr).splitlines()
    print("\n".join(x for x in lines if not (drop and drop in x)))
    print(f"[exit {done.returncode}]")
    return done

Definition 1 (The static check) babregen check loads the whole regen/ tree, runs every check (architecture, each unit, each decision), prints one line per finding and a summary, and exits 1 if an error was found. It is deterministic and cheap, so it is the first step of make guard.

A clean repository

Example 1 (No findings)  

done = babregen("check")
assert (done.returncode, done.stdout) == (0, "regen check: 1 units, 0 errors, 0 warnings\n")
$ babregen check
regen check: 1 units, 0 errors, 0 warnings
[exit 0]

The summary line is stable. A consistent repository prints nothing but the summary.

A hidden consumer

Example 2 (DELETE01: a file depends on the unit without being declared) A script imports the unit. Nothing in regen/units/core.calc.toml says so, so a regeneration of the unit could break it unnoticed.

(root / "scripts").mkdir()
(root / "scripts" / "use_it.py").write_text("from samplepkg.core import calc\n")
done = babregen("check")
assert done.returncode == 1 and "DELETE01" in done.stdout
$ babregen check
regen/units/core.calc.toml:1: error DELETE01 scripts/use_it.py depends on the unit but is not a declared consumer
regen check: 1 units, 1 errors, 0 warnings
[exit 1]

A finding line is {path}:{line}: {level} {id} {message}. babregen explain DELETE01 says what the ID means. The fix is to declare the script as a consumer of the unit or to remove the import. add-consumer appends the [[consumers]] block and infers the kind from the path:

done = babregen("add-consumer", "core.calc", "scripts/use_it.py", "--note", "demo")
done = babregen("check")
assert done.returncode == 0
$ babregen add-consumer core.calc scripts/use_it.py --note demo
wrote regen/units/core.calc.toml
next: run babregen check
[exit 0]
$ babregen check
regen check: 1 units, 0 errors, 0 warnings
[exit 0]

A forbidden import

Example 3 (COMPILE02 and COMPILE04: the architecture is violated) regen/architecture.toml allows app to import core and nothing else. A new module in core that imports app breaks the rule, and closes an import cycle as well.

(root / "src" / "samplepkg" / "core" / "bad.py").write_text("from samplepkg.app import main\n")
done = babregen("check")
assert done.returncode == 1 and "COMPILE02" in done.stdout and "COMPILE04" in done.stdout
$ babregen check
src/samplepkg/core/bad.py:1: error COMPILE02 'core' imports 'samplepkg.app', but architecture.toml allows only []
regen/architecture.toml:12: error COMPILE04 new import cycle between 'app' and 'core' (not in known_cycles)
regen check: 1 units, 2 errors, 0 warnings
[exit 1]

Warnings and --strict

Example 4 (COMPACT07: a consumer that no longer references the unit) Warnings ask for attention. They fail the check only with --strict.

(root / "src" / "samplepkg" / "core" / "bad.py").unlink()
(root / "docs" / "guide.qmd").write_text("The guide no longer mentions the unit.\n")
done = babregen("check")
assert done.returncode == 0 and "COMPACT07" in done.stdout
done = babregen("check", "--strict")
assert done.returncode == 1
$ babregen check
regen/units/core.calc.toml:21: warning COMPACT07 consumer docs/guide.qmd no longer references the unit
regen check: 1 units, 0 errors, 1 warnings
[exit 0]
$ babregen check --strict
regen/units/core.calc.toml:21: warning COMPACT07 consumer docs/guide.qmd no longer references the unit
regen check: 1 units, 0 errors, 1 warnings
[exit 1]

Read a suggestion

A name that matches nothing is the commonest error of a hand-written record. For an evaluation (EVAL03), a decision (PROV01, PROV02), a public name (COMPILE06) and a depends_on entry (COMPILE08) the finding is placed on the line of the wrong name and ends with the name that was probably meant:

unit = root / "regen" / "units" / "core.calc.toml"
text = unit.read_text()
unit.write_text(text.replace('evaluations = ["test_add"]', 'evaluations = [\n  "test_ad",\n]'))
done = babregen("check")
assert "EVAL03" in done.stdout and "a similar name exists: 'test_add'" in done.stdout
unit.write_text(text)
$ babregen check
regen/units/core.calc.toml:13: error EVAL03 intent C-1: evaluation 'test_ad' not found; a similar name exists: 'test_add'
tests/test_regen_eval_calc.py:8: warning COMPACT05 samplepkg.core.calc: evaluation 'test_add' is not linked to any intent item
regen/units/core.calc.toml:23: warning COMPACT07 consumer docs/guide.qmd no longer references the unit
regen check: 1 units, 1 errors, 2 warnings
[exit 1]
498

The fix is to take the suggested name. The same suffix ends the error for an unknown key of a record (unknown key 'pase' in a unit record; a similar name exists: 'pace'); the check then stops with exit code 2.

For CI: JSON output

--format json prints the same findings as one JSON document, with the line and the suggestion as fields of their own (see JSON output). The exit code is the same, so a CI job needs only the exit code to fail and the document to report. The format number is part of the stability contract.

import json

(root / "src" / "samplepkg" / "core" / "bad.py").write_text("from samplepkg.app import main\n")
done = babregen("check", "--format", "json")
report = json.loads(done.stdout)
assert report["format"] == 1 and done.returncode == 1
assert report["summary"]["errors"] == len(
    [f for f in report["findings"] if f["level"] == "error"]
)
for finding in report["findings"]:
    print(f"{finding['path']}:{finding['line']} {finding['id']}")
$ babregen check --format json
{
  "format": 1,
  "summary": {
    "units": 1,
    "errors": 2,
    "warnings": 1
  },
  "findings": [
    {
      "path": "src/samplepkg/core/bad.py",
      "line": 1,
      "level": "error",
      "id": "COMPILE02",
      "message": "'core' imports 'samplepkg.app', but architecture.toml allows only []",
      "suggestion": null
    },
    {
      "path": "regen/architecture.toml",
      "line": 12,
      "level": "error",
      "id": "COMPILE04",
      "message": "new import cycle between 'app' and 'core' (not in known_cycles)",
      "suggestion": null
    },
    {
      "path": "regen/units/core.calc.toml",
      "line": 21,
      "level": "warning",
      "id": "COMPACT07",
      "message": "consumer docs/guide.qmd no longer references the unit",
      "suggestion": null
    }
  ]
}
[exit 1]
src/samplepkg/core/bad.py:1 COMPILE02
regen/architecture.toml:12 COMPILE04
regen/units/core.calc.toml:21 COMPACT07
TipExit codes

0 means no error (no finding at all with --strict), 1 means errors, 2 means that the spec itself is malformed: invalid TOML, a value outside a vocabulary or a missing regen/architecture.toml. See the schema page for every ID.

(root / "regen" / "units" / "core.calc.toml").write_text("unit = [")
done = babregen("check")
assert done.returncode == 2
$ babregen check
babregen: /private/var/folders/dw/pvtj6mt91znd0hftcztqb0k00000gn/T/tmp4erzycws/demo/regen/units/core.calc.toml: invalid TOML (Invalid value (at end of document))
[exit 2]

Next: the deletion test.