Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(cli): report git's message for an unknown ref in `repowise risk` (#3622)
Columbus Labsa0ad0098f306
diff --git a/packages/cli/src/repowise/cli/commands/risk_cmd.py b/packages/cli/src/repowise/cli/commands/risk_cmd.pyindex 19c7aa286..fa7e3ad24 100644--- a/packages/cli/src/repowise/cli/commands/risk_cmd.py+++ b/packages/cli/src/repowise/cli/commands/risk_cmd.py@@ -33,6 +33,7 @@ Examples:from __future__ import annotationsimport json+import subprocessfrom dataclasses import dataclassfrom pathlib import Path@@ -614,6 +615,7 @@ def _score() -> ChangeRiskResult:"""Score the change, or exit 2 when it cannot be read or, gated, ranked."""status = ci_notices(subject.fmt)+ _verify_revision(subject)if baseline and subject.fmt == "table":status.print(f"[dim]Sampling up to {baseline} recent commits…[/dim]")try:@@ -629,7 +631,8 @@ def _score(cannot_evaluate(subject.fmt,"change_unreadable",- f"Could not read change {subject.revspec or 'HEAD'!r} in {subject.repo_path}: {exc}",+ f"Could not read change {subject.revspec or 'HEAD'!r} in {subject.repo_path}: "+ f"{_git_error_detail(exc)}",)if subject.fail_above is not None and result.percentile is None:from repowise.core.analysis.change_risk.render import unranked_reason@@ -643,6 +646,59 @@ def _score(return result+def _git_error_detail(exc: Exception) -> str:+ """Git's own message for a failed git call, else the exception text."""+ stderr = exc.stderr if isinstance(exc, subprocess.CalledProcessError) else None+ if isinstance(stderr, bytes):+ stderr = stderr.decode(errors="replace")+ lines = [line.strip() for line in (stderr or "").splitlines() if line.strip()]+ return lines[0] if lines else str(exc)+++def _verify_revision(subject: _Subject) -> None:+ """Exit 2 with git's message when a single-commit revspec does not resolve.++ Checked before the sampling notice so an unknown ref is reported first and+ alone. Ranges and the working tree are left to the scorer.+ """+ revspec = subject.revspec+ if not revspec or ".." in revspec:+ return+ try:+ commit = f"{revspec}^{{commit}}"+ subprocess.run(+ ["git", "rev-parse", "--verify", "--quiet", "--end-of-options", commit],+ cwd=subject.repo_path,+ check=True,+ capture_output=True,+ text=True,+ )+ except subprocess.CalledProcessError:+ # --quiet suppresses the message; ask git again for the human one.+ probe = subprocess.run(+ ["git", "rev-parse", "--end-of-options", revspec],+ cwd=subject.repo_path,+ capture_output=True,+ text=True,+ )+ if probe.returncode == 0:+ detail = f"{revspec!r} does not name a commit"+ elif "unknown revision" in probe.stderr:+ detail = _git_error_detail(+ subprocess.CalledProcessError(probe.returncode, probe.args, stderr=probe.stderr)+ )+ else:+ # Not a repository, or some other git failure: the scorer reports it.+ return+ cannot_evaluate(+ subject.fmt,+ "change_unreadable",+ f"Could not read change {revspec!r} in {subject.repo_path}: {detail}",+ )+ except OSError:+ return++def _print_change(subject: _Subject, result: ChangeRiskResult, failed: bool) -> None:"""The table rendering of a scored change."""_print_size(result, subject.fail_above, failed)diff --git a/tests/unit/cli/test_risk_cmd.py b/tests/unit/cli/test_risk_cmd.pyindex 344ef6c1f..2f6c62a3c 100644--- a/tests/unit/cli/test_risk_cmd.py+++ b/tests/unit/cli/test_risk_cmd.py@@ -319,3 +319,26 @@ def test_target_mode_refuses_ci_formats_and_the_gate(tmp_path: Path) -> None:gate = _gate(repo, "--target", "src/f0.py", "--fail-above-percentile", "90")assert gate.exit_code == 2assert "gates a change" in gate.output+++def test_an_unknown_ref_reports_gits_message_not_the_exception(tmp_path: Path) -> None:+ repo = _ranked_repo(tmp_path)++ table = _gate(repo, "nosuchref")+ assert table.exit_code == 2, table.output+ assert "unknown revision" in table.output+ assert "returned non-zero exit status" not in table.output+ assert "Sampling" not in table.output++ machine = _gate(repo, "nosuchref", "--format", "json")+ assert machine.exit_code == 2, machine.output+ assert json.loads(machine.stdout)["error"] == "change_unreadable"+ assert "unknown revision" in machine.output+++def test_a_valid_ref_is_unaffected_by_the_ref_check(tmp_path: Path) -> None:+ repo = _ranked_repo(tmp_path)++ result = _gate(repo, "HEAD", "--format", "json")+ assert result.exit_code == 0, result.output+ assert json.loads(result.stdout)["ref"] == "HEAD"