Skip to content

The agent that grows with you

fix(code-health): --json prints JSON on every return path

Teknium15274dfb41b2
diff --git a/scripts/code_health/cli.py b/scripts/code_health/cli.py
index 91ef3b3825e..c783a7960c1 100644
--- a/scripts/code_health/cli.py
+++ b/scripts/code_health/cli.py
@@ -58,17 +58,24 @@ def _report(repo: Path, head: str | None) -> int:
return 0
+def _skipped(why: str, as_json: bool) -> None:
+ """A run that measured nothing: an empty findings list for --json, the reason for humans."""
+ if as_json:
+ print("[]")
+ print(why, file=sys.stderr if as_json else sys.stdout)
+
+
def run(repo: Path, base: str, head: str | None, as_json: bool = False) -> int:
started = time.monotonic()
mode = enforcement(repo, base)
if mode == "off":
- print(f"code health: off (ENFORCEMENT in {_SWITCH_FILE} on {base[:12]})")
+ _skipped(f"code health: off (ENFORCEMENT in {_SWITCH_FILE} on {base[:12]})", as_json)
return 0
changes = gitio.changed_files(repo, base, head)
head_paths = sorted({c.new for c in changes if c.new and in_scope(c.new)})
base_paths = sorted({c.old for c in changes if c.old and in_scope(c.old)})
if not head_paths:
- print("code health: no measured files changed")
+ _skipped("code health: no measured files changed", as_json)
return 0
# Base files are measured too: a deleted .py still needs ruff on the base side.
needs_ruff = any(p.endswith(".py") for p in (*head_paths, *base_paths))
diff --git a/tests/scripts/test_code_health_cli.py b/tests/scripts/test_code_health_cli.py
index c28f3e51a84..2a52405a24c 100644
--- a/tests/scripts/test_code_health_cli.py
+++ b/tests/scripts/test_code_health_cli.py
@@ -131,3 +131,23 @@ def test_valid_selector_runs_its_check_and_keeps_its_status(tmp_path):
_git(repo, "add", "--", "pkg/c.py")
proc = _check(repo, "--staged", "--only", "health,shebangs", "--base", "HEAD")
assert proc.returncode == 1 and "2 checks, FAILED: health" in proc.stdout, proc.stdout
+
+
+# --- JSON output on every return path ----------------------------------------------------------
+
+
[email protected]("case, switch, files, code, findings", [
+ ("no measured change", None, {"README.md": "docs\n"}, 0, 0),
+ ("enforcement off", 'ENFORCEMENT = "off"\n', {"pkg/a.py": _GROWN}, 0, 0),
+ ("findings", None, {"pkg/a.py": _GROWN}, 1, 1),
+ ("clean measured diff", None, {"pkg/b.py": "def b():\n return 2\n"}, 0, 0),
+])
+def test_json_stdout_is_json_on_every_path(tmp_path, capsys, case, switch, files, code, findings):
+ repo, base = _ratchet_repo(tmp_path, switch)
+ head = _commit(repo, files)
+ assert cli.run(repo, base, head, as_json=True) == code, case
+ out, err = capsys.readouterr()
+ data = json.loads(out)
+ assert isinstance(data, list) and len(data) == findings, (case, out)
+ if case in ("no measured change", "enforcement off"):
+ assert "code health:" in err # the human explanation moves to stderr