diff --git a/repo_contract/README.md b/repo_contract/README.md index 3187e70..28e10f5 100644 --- a/repo_contract/README.md +++ b/repo_contract/README.md @@ -42,7 +42,7 @@ Rules (all machine-checked): python3 ~/src/utils/repo_contract/check.py --repo # 0 pass / 1 violations / 2 unreadable python3 ~/src/utils/repo_contract/bootstrap.py --repo # print proposal python3 ~/src/utils/repo_contract/bootstrap.py --repo --write -python3 ~/src/utils/repo_contract/sweep.py # ~/data/claude-scratch/repo-contract/SWEEP.md +python3 ~/src/utils/repo_contract/sweep.py # ~/data/claude-scratch/repo-contract/SWEEP.md; --dry-run prints it instead, --out PATH writes elsewhere ``` Bootstrap never overwrites: it appends the section (or inserts missing lines at diff --git a/repo_contract/sweep.py b/repo_contract/sweep.py index 1754fe6..09be8bd 100644 --- a/repo_contract/sweep.py +++ b/repo_contract/sweep.py @@ -2,6 +2,7 @@ from __future__ import annotations +import argparse import sys from collections import Counter from dataclasses import dataclass @@ -82,19 +83,46 @@ def render(results: list[Result]) -> str: return "\n".join(out) + "\n" +def parse_args(argv: list[str] | None, default_out: Path) -> argparse.Namespace: + """Parse argv; argparse exits 0 on --help and 2 on bad args before any walk.""" + parser = argparse.ArgumentParser( + prog="sweep.py", + description=( + "Run the repo contract check over every git repo directly under ~/src " + "and ~ and write a markdown report (SWEEP.md)." + ), + ) + parser.add_argument( + "--dry-run", + action="store_true", + help="walk and check, print the report to stdout, write nothing", + ) + parser.add_argument( + "--out", + type=Path, + default=default_out, + help=f"report path (default: {default_out})", + ) + return parser.parse_args(argv) + + def main( argv: list[str] | None = None, roots: list[Path] | None = None, out: Path = OUT ) -> int: - """Sweep, write the report, print the summary line. Always exit 0.""" - del argv + """Sweep, write (or with --dry-run print) the report, print the summary. Exit 0.""" + args = parse_args(argv, out) home = Path.home() results = [run_one(r) for r in find_repos(roots or [home / "src", home])] - out.parent.mkdir(parents=True, exist_ok=True) - out.write_text(render(results), encoding="utf-8") + report = render(results) passed = sum(r.passed for r in results) - print( - f"repo-contract sweep: {len(results)} repos, {passed} pass, {len(results) - passed} fail -> {out}" - ) + summary = f"repo-contract sweep: {len(results)} repos, {passed} pass, {len(results) - passed} fail" + if args.dry_run: + sys.stdout.write(report) + print(f"{summary} (dry run, nothing written)", file=sys.stderr) + return 0 + args.out.parent.mkdir(parents=True, exist_ok=True) + args.out.write_text(report, encoding="utf-8") + print(f"{summary} -> {args.out}") return 0 diff --git a/repo_contract/tests/test_sweep.py b/repo_contract/tests/test_sweep.py index 66b22fc..cb613b7 100644 --- a/repo_contract/tests/test_sweep.py +++ b/repo_contract/tests/test_sweep.py @@ -40,6 +40,81 @@ def test_run_one_and_render(tmp_path: Path) -> None: def test_main_writes_report(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: make_repo(tmp_path / "r") out = tmp_path / "out" / "SWEEP.md" - assert main(roots=[tmp_path], out=out) == 0 + assert main([], roots=[tmp_path], out=out) == 0 assert "1 repos, 0 pass, 1 fail" in capsys.readouterr().out assert out.is_file() + + +@pytest.fixture +def no_walk(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + """Redirect HOME and make any walk fail loudly; return the default out path.""" + monkeypatch.setenv("HOME", str(tmp_path / "home")) + + def boom(roots: list[Path]) -> list[Path]: + raise AssertionError(f"walked {roots}") + + monkeypatch.setattr("repo_contract.sweep.find_repos", boom) + return tmp_path / "default" / "SWEEP.md" + + +def test_help_exits_0_without_walk_or_write( + no_walk: Path, capsys: pytest.CaptureFixture[str] +) -> None: + with pytest.raises(SystemExit) as exc: + main(["--help"], out=no_walk) + assert exc.value.code == 0 + text = capsys.readouterr().out + assert "~/src" in text and "SWEEP.md" in text + assert "--dry-run" in text and "--out" in text + assert not no_walk.exists() + + +def test_unknown_arg_exits_2_without_walk_or_write( + no_walk: Path, capsys: pytest.CaptureFixture[str] +) -> None: + with pytest.raises(SystemExit) as exc: + main(["--bogus"], out=no_walk) + assert exc.value.code == 2 + assert "usage:" in capsys.readouterr().err + assert not no_walk.exists() + + +def test_dry_run_prints_report_and_writes_nothing( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + monkeypatch.setenv("HOME", str(tmp_path / "home")) + make_repo(tmp_path / "src" / "r") + out = tmp_path / "default" / "SWEEP.md" + assert main(["--dry-run"], roots=[tmp_path / "src"], out=out) == 0 + cap = capsys.readouterr() + assert cap.out.startswith("# Repo contract sweep") + assert "| r | FAIL |" in cap.out + assert "1 repos, 0 pass, 1 fail" in cap.err and "dry run" in cap.err + assert not out.exists() and not out.parent.exists() + + +def test_out_flag_writes_given_path( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + monkeypatch.setenv("HOME", str(tmp_path / "home")) + make_repo(tmp_path / "src" / "r") + default = tmp_path / "default" / "SWEEP.md" + given = tmp_path / "x" / "SWEEP.md" + assert main(["--out", str(given)], roots=[tmp_path / "src"], out=default) == 0 + assert given.read_text(encoding="utf-8").startswith("# Repo contract sweep") + assert not default.exists() + assert f"-> {given}" in capsys.readouterr().out + + +def test_cli_help_runs_as_script(tmp_path: Path) -> None: + script = Path(__file__).resolve().parents[1] / "sweep.py" + env = {"HOME": str(tmp_path), "PATH": "/usr/bin:/bin"} + proc = subprocess.run( + ["python3", str(script), "--help"], + check=False, + capture_output=True, + text=True, + env=env, + ) + assert proc.returncode == 0 and "--dry-run" in proc.stdout + assert not (tmp_path / "data").exists()