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): accept only commit ids from state.json before handing them to git (#3039)
Raghav Chamadiyad92120113965
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/session_start.py b/packages/cli/src/repowise/cli/commands/augment_cmd/session_start.pyindex a270e54cc..96538b94a 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd/session_start.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/session_start.py@@ -26,6 +26,8 @@ from __future__ import annotationsimport jsonfrom pathlib import Path+from repowise.cli.helpers import as_commit_id+from ._shared import _find_repo_root, emitting_buildfrom .bash_staleness import _read_in_flight_markerfrom .decision_inject import _session_decision_block@@ -144,9 +146,11 @@ def _changed_file_count(repo_path: Path, indexed: str, live: str) -> int | None:"""Files changed between the indexed commit and live HEAD, or None."""import subprocess+ if as_commit_id(indexed) is None or as_commit_id(live) is None:+ return Nonetry:out = subprocess.run(- ["git", "diff", "--name-only", indexed, live],+ ["git", "diff", "--name-only", "--end-of-options", indexed, live],cwd=str(repo_path),capture_output=True,text=True,diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.pyindex 49be1ba4d..c6e4d5f3e 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py@@ -19,6 +19,7 @@ from typing import Anyimport structlogfrom repowise.cli.helpers import (+ as_commit_id,console,head_commit_ts,load_config,@@ -355,6 +356,8 @@ def resolve_repair_base(from_commit = marker.get("from_commit") if isinstance(marker, dict) else Noneif not from_commit or from_commit == base_ref:return base_ref, None+ if as_commit_id(from_commit) is None or as_commit_id(base_ref) is None:+ return base_ref, Nonedef _git(*args: str) -> subprocess.CompletedProcess:return subprocess.run(@@ -362,7 +365,7 @@ def resolve_repair_base()try:- if _git("merge-base", "--is-ancestor", from_commit, base_ref).returncode != 0:+ if _git("merge-base", "--is-ancestor", "--end-of-options", from_commit, base_ref).returncode != 0:# Non-zero covers both "not an ancestor" (rebased, force-pushed,# branch switched) and "cannot resolve that object" (gc'd, or a# shallow clone that never fetched it), and git does not@@ -371,7 +374,7 @@ def resolve_repair_base(f"the recorded commit {from_commit[:8]} is not an ancestor of this ""branch's history, or is not present in this clone")- counted = _git("rev-list", "--count", f"{from_commit}..{head or 'HEAD'}")+ counted = _git("rev-list", "--count", "--end-of-options", f"{from_commit}..{head or 'HEAD'}")if counted.returncode == 0 and int(counted.stdout.strip() or 0) > _REPAIR_MAX_COMMITS:return base_ref, (f"the range has grown past {_REPAIR_MAX_COMMITS} commits, which is "diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.pyindex 06b8f6ef1..86e3bf93a 100644--- a/packages/cli/src/repowise/cli/helpers.py+++ b/packages/cli/src/repowise/cli/helpers.py@@ -6,6 +6,7 @@ import asyncioimport contextlibimport jsonimport os+import reimport sysfrom dataclasses import dataclassfrom pathlib import Path@@ -611,12 +612,14 @@ def _pending_commit_still_ahead(return Falseimport subprocess+ if as_commit_id(indexed_head) is None or as_commit_id(pending_head) is None:+ return Falsetry:# ``indexed_head`` is an ancestor of ``pending_head`` => pending is# newer than what we indexed and worth keeping. A non-zero exit# (including an unresolvable pending commit) means "not ahead".result = subprocess.run(- ["git", "merge-base", "--is-ancestor", indexed_head, pending_head],+ ["git", "merge-base", "--is-ancestor", "--end-of-options", indexed_head, pending_head],cwd=str(repo_path),capture_output=True,timeout=10,@@ -689,6 +692,22 @@ def rotate_update_log_if_needed(repo_path: Path) -> None:# ---------------------------------------------------------------------------+_COMMIT_ID_RE = re.compile(r"[0-9a-fA-F]{7,40}")+++def as_commit_id(value: object) -> str | None:+ """*value* when it is a full or abbreviated hex commit id, else ``None``.++ Commit ids read back from ``.repowise/state.json`` (or a file beside it)+ can be edited by anyone who can commit that file, so they are checked+ before they reach a ``git`` argument list, where a leading ``-`` would be+ read as an option.+ """+ if isinstance(value, str) and _COMMIT_ID_RE.fullmatch(value):+ return value+ return None++def get_head_commit(repo_path: Path) -> str | None:"""Return the HEAD commit SHA or ``None`` if not a git repo.diff --git a/packages/cli/src/repowise/cli/worktree.py b/packages/cli/src/repowise/cli/worktree.pyindex 280111e41..68d9ddffe 100644--- a/packages/cli/src/repowise/cli/worktree.py+++ b/packages/cli/src/repowise/cli/worktree.py@@ -16,7 +16,7 @@ import timeimport uuidfrom pathlib import Path-from repowise.cli.helpers import console, warn+from repowise.cli.helpers import as_commit_id, console, warn_SEED_TEMPDIR_STALENESS_SECS = 3600@@ -203,8 +203,10 @@ def seed_index_from_base(breaktry:+ if as_commit_id(last_sync_commit) is None:+ raise subprocess.CalledProcessError(1, "git merge-base")subprocess.check_call(- ["git", "merge-base", "--is-ancestor", last_sync_commit, "HEAD"],+ ["git", "merge-base", "--is-ancestor", "--end-of-options", last_sync_commit, "HEAD"],cwd=r_path,stderr=subprocess.DEVNULL,)diff --git a/tests/unit/cli/test_augment_session_start.py b/tests/unit/cli/test_augment_session_start.pyindex 61c76c65c..cac32937d 100644--- a/tests/unit/cli/test_augment_session_start.py+++ b/tests/unit/cli/test_augment_session_start.py@@ -149,3 +149,27 @@ def test_temp_root_repowise_is_ignored(tmp_path, monkeypatch) -> None:repo = fake_tmp / "checkout"(repo / ".repowise").mkdir(parents=True)assert _shared._find_repo_root(repo) == repo.resolve()++[email protected]("bad", ["--output=/tmp/x", "-p", "--no-index", "HEAD~1", "abc", "g" * 40, ""])+def test_changed_file_count_rejects_non_commit_ids(tmp_path, monkeypatch, bad) -> None:+ import subprocess++ calls: list = []+ monkeypatch.setattr(subprocess, "run", lambda *a, **k: calls.append(a))+ assert session_start._changed_file_count(tmp_path, bad, _LIVE) is None+ assert calls == []+++def test_changed_file_count_valid_id_passes_end_of_options(tmp_path, monkeypatch) -> None:+ import subprocess++ seen: list = []++ def fake_run(argv, **kwargs):+ seen.append(argv)+ return subprocess.CompletedProcess(argv, 0, stdout="a.py\nb.py\n", stderr="")++ monkeypatch.setattr(subprocess, "run", fake_run)+ assert session_start._changed_file_count(tmp_path, "AbC1234", _LIVE) == 2+ assert seen == [["git", "diff", "--name-only", "--end-of-options", "AbC1234", _LIVE]]diff --git a/tests/unit/cli/test_worktree.py b/tests/unit/cli/test_worktree.pyindex 7b37b23ee..8e4edf3a9 100644--- a/tests/unit/cli/test_worktree.py+++ b/tests/unit/cli/test_worktree.py@@ -110,3 +110,12 @@ def test_adopting_identity_rekeys_the_repo_level_pages(tmp_path: Path) -> None:assert ("module_page:src", "src", "repo_overview:feature-tree") in pagesassert versions == [("repo_overview:feature-tree",)]assert fts == [("repo_overview:feature-tree", "feature-tree")]+++def test_as_commit_id_accepts_only_hex_commit_ids() -> None:+ from repowise.cli.helpers import as_commit_id++ assert as_commit_id("a" * 40) == "a" * 40+ assert as_commit_id("DeadBee") == "DeadBee"+ for bad in ("--output=x", "-abcdef0", "abc123", "a" * 41, "HEAD", "", None, 7):+ assert as_commit_id(bad) is None