Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

refactor(core): one git runner for analysis, doc drift and edit capture (#3980)

Raghav Chamadiya56a2ba219b4a
diff --git a/packages/core/src/repowise/core/analysis/change_health/sources.py b/packages/core/src/repowise/core/analysis/change_health/sources.py
index 4dc50c2a5..75e6cbd06 100644
--- a/packages/core/src/repowise/core/analysis/change_health/sources.py
+++ b/packages/core/src/repowise/core/analysis/change_health/sources.py
@@ -8,7 +8,6 @@ checks out, resets, or writes to the caller's tree.
from __future__ import annotations
-import subprocess
from collections.abc import Iterator
from dataclasses import dataclass, field
from pathlib import Path
@@ -16,7 +15,7 @@ from typing import Protocol
from ..changed_lines import FileDiff, is_shallow_root, parse_unified_diff, untracked_diffs
from ..git_cat_file import cat_file_batch
-from ..git_cli import path_filter, split_revspec, untracked_paths
+from ..git_cli import path_filter, run_git, split_revspec, untracked_paths
GIT_TIMEOUT_SECONDS = 120
@@ -130,15 +129,7 @@ class RevisionSource(Protocol):
def _git(args: list[str], repo_path: str, *, check: bool = True) -> str:
- proc = subprocess.run(
- ["git", "-C", repo_path, *args],
- capture_output=True,
- text=True,
- encoding="utf-8",
- errors="replace",
- stdin=subprocess.DEVNULL,
- timeout=GIT_TIMEOUT_SECONDS,
- )
+ proc = run_git(["-C", repo_path, *args], timeout=GIT_TIMEOUT_SECONDS)
if check and proc.returncode != 0:
raise ValueError((proc.stderr or "").strip() or f"git {args[0]} failed")
return proc.stdout
diff --git a/packages/core/src/repowise/core/analysis/doc_drift/live.py b/packages/core/src/repowise/core/analysis/doc_drift/live.py
index 609e060c1..1c1181222 100644
--- a/packages/core/src/repowise/core/analysis/doc_drift/live.py
+++ b/packages/core/src/repowise/core/analysis/doc_drift/live.py
@@ -17,13 +17,13 @@ from pathlib import Path
from repowise.core.ingestion.traverser import REPOWISE_IGNORE_FILENAME, load_extra_ignore_spec
+from ..git_cli import run_git
from .analyzer import DocDriftAnalyzer
from .constants import MANIFEST_NAMES, MAX_DOC_BYTES
from .extractor import is_checkable_document
from .models import DocDriftReport
from .symbols import SymbolOptions
-_GIT_TIMEOUT_SECONDS = 60
_GITLINK_MODE = "160000"
@@ -46,13 +46,7 @@ class LiveInputs:
def _git(root: Path, *args: str) -> bytes:
"""stdout of one git call; :class:`LiveTreeError` on any failure."""
try:
- proc = subprocess.run(
- ["git", "-C", str(root), *args],
- capture_output=True,
- stdin=subprocess.DEVNULL,
- timeout=_GIT_TIMEOUT_SECONDS,
- check=False,
- )
+ proc = run_git(["-C", str(root), *args], text=False)
except OSError as exc:
raise LiveTreeError(f"git is not available: {exc}") from exc
except subprocess.TimeoutExpired as exc:
diff --git a/packages/core/src/repowise/core/analysis/doc_drift/suggest.py b/packages/core/src/repowise/core/analysis/doc_drift/suggest.py
index 99da797f5..1cd6a90b8 100644
--- a/packages/core/src/repowise/core/analysis/doc_drift/suggest.py
+++ b/packages/core/src/repowise/core/analysis/doc_drift/suggest.py
@@ -26,6 +26,7 @@ from functools import cache
from pathlib import Path
from typing import Literal
+from ..git_cli import run_git
from .constants import SuggestionBasis
from .models import DocReference, DriftKind
from .renderer import github_slug
@@ -254,14 +255,12 @@ def git_run(
"""
env = {**os.environ, "GIT_NO_LAZY_FETCH": "1", "GIT_LITERAL_PATHSPECS": "1"}
try:
- proc = subprocess.run(
- ["git", "-C", str(root), "-c", "core.quotePath=false", *args],
- capture_output=True,
+ proc = run_git(
+ ["-C", str(root), "-c", "core.quotePath=false", *args],
+ text=False,
input=stdin,
- stdin=None if stdin is not None else subprocess.DEVNULL,
env=env,
timeout=timeout,
- check=False,
)
except (OSError, subprocess.SubprocessError, ValueError):
return None
diff --git a/packages/core/src/repowise/core/analysis/git_cli.py b/packages/core/src/repowise/core/analysis/git_cli.py
index 5a55c53a7..3b4d16cca 100644
--- a/packages/core/src/repowise/core/analysis/git_cli.py
+++ b/packages/core/src/repowise/core/analysis/git_cli.py
@@ -9,7 +9,7 @@ baseline and, through it, GitPython.
from __future__ import annotations
import subprocess
-from collections.abc import Callable
+from collections.abc import Callable, Mapping, Sequence
from pathlib import Path
import pathspec
@@ -63,21 +63,40 @@ def path_filter(
return counts
-def _git(args: list[str], cwd: str, *, check: bool = True) -> str:
- # stdin=DEVNULL: on MCP stdio transport a child that inherits the JSON-RPC
- # pipe handles can wedge the session (same failure mode _meta.py guards
- # against). check=True so a bad revspec raises instead of yielding empty
- # stdout, which used to score as a zero-feature "low risk" change.
- proc = subprocess.run(
+def run_git(
+ args: Sequence[str],
+ cwd: str | Path | None = None,
+ *,
+ text: bool = True,
+ input: str | bytes | None = None,
+ env: Mapping[str, str] | None = None,
+ timeout: float | None = GIT_TIMEOUT_SECONDS,
+) -> subprocess.CompletedProcess:
+ """One ``git`` call with output captured and the exit code left to the caller.
+
+ ``text`` decodes as utf-8 with replacement (git writes utf-8; the locale
+ codec fails on Windows); ``text=False`` returns bytes. stdin is DEVNULL
+ unless *input* is given: on MCP stdio transport a child that inherits the
+ JSON-RPC pipe can wedge the session. Spawn errors and timeouts propagate.
+ """
+ decode = {"text": True, "encoding": "utf-8", "errors": "replace"} if text else {}
+ return subprocess.run(
["git", *args],
cwd=cwd,
+ input=input,
+ stdin=None if input is not None else subprocess.DEVNULL,
capture_output=True,
- text=True,
- encoding="utf-8",
- errors="replace",
- stdin=subprocess.DEVNULL,
- timeout=GIT_TIMEOUT_SECONDS,
+ env=env,
+ timeout=timeout,
+ check=False,
+ **decode,
)
+
+
+def _git(args: list[str], cwd: str, *, check: bool = True) -> str:
+ # check=True so a bad revspec raises instead of yielding empty stdout,
+ # which used to score as a zero-feature "low risk" change.
+ proc = run_git(args, cwd)
if check and proc.returncode != 0:
raise subprocess.CalledProcessError(
proc.returncode, proc.args, output=proc.stdout, stderr=proc.stderr
diff --git a/packages/core/src/repowise/core/analysis/history_scan.py b/packages/core/src/repowise/core/analysis/history_scan.py
index c39dbf09c..f8d8eb3f1 100644
--- a/packages/core/src/repowise/core/analysis/history_scan.py
+++ b/packages/core/src/repowise/core/analysis/history_scan.py
@@ -41,6 +41,7 @@ from pathlib import Path
from typing import Any
from repowise.core.analysis.git_cat_file import cat_file_batch
+from repowise.core.analysis.git_cli import run_git
from repowise.core.analysis.secret_allowlist import secret_path_allowlist
from repowise.core.analysis.security_gate import _KEY_SHAPE_KINDS, fingerprint_of
from repowise.core.analysis.security_scan import (
@@ -59,21 +60,7 @@ def _run_git(repo_path: Path, args: list[str], *, timeout: float = 30.0) -> str:
scan rather than a crash).
"""
try:
- result = subprocess.run(
- ["git", *args],
- cwd=str(repo_path),
- capture_output=True,
- stdin=subprocess.DEVNULL,
- text=True,
- # git writes utf-8. ``text=True`` alone decodes with the locale
- # codec, so on a default Windows install a commit subject holding
- # an em dash raised UnicodeDecodeError. That is a ValueError, which
- # the handler below does not catch, so the scan died rather than
- # degrading to "".
- encoding="utf-8",
- errors="replace",
- timeout=timeout,
- )
+ result = run_git(args, str(repo_path), timeout=timeout)
except (OSError, subprocess.SubprocessError):
return ""
if result.returncode != 0:
diff --git a/packages/core/src/repowise/core/edit_capture/binder.py b/packages/core/src/repowise/core/edit_capture/binder.py
index 5e17ae776..1869e6a6d 100644
--- a/packages/core/src/repowise/core/edit_capture/binder.py
+++ b/packages/core/src/repowise/core/edit_capture/binder.py
@@ -29,12 +29,12 @@ from __future__ import annotations
import os
import re
-import subprocess
import time
from collections import Counter
from pathlib import Path
from typing import Any
+from ..analysis.git_cli import run_git
from .edits import CapturedCall, FileEdit
from .hashing import is_substantive, line_hash, opaque_id
from .store import (
@@ -87,16 +87,8 @@ def event_rows(
def _git(repo: Path, *args: str) -> str:
- result = subprocess.run(
- ["git", "-c", "core.quotepath=false", *args],
- cwd=repo,
- capture_output=True,
- text=True,
- encoding="utf-8",
- errors="replace",
- stdin=subprocess.DEVNULL,
- check=False,
- )
+ # Ceiling: no timeout; a wedged git blocks this call.
+ result = run_git(["-c", "core.quotepath=false", *args], repo, timeout=None)
return result.stdout if result.returncode == 0 else ""
diff --git a/packages/core/src/repowise/core/edit_capture/notes.py b/packages/core/src/repowise/core/edit_capture/notes.py
index f2d3066fd..690f8e3e7 100644
--- a/packages/core/src/repowise/core/edit_capture/notes.py
+++ b/packages/core/src/repowise/core/edit_capture/notes.py
@@ -27,6 +27,7 @@ import secrets
import subprocess
from pathlib import Path
+from ..analysis.git_cli import run_git
from .store import NOTES_LEDGER, append_jsonl, load_state, read_jsonl, save_state, sidecar_dir
NOTES_REF = "refs/notes/ai"
@@ -36,17 +37,8 @@ FETCH_REFSPEC = f"+{NOTES_REF}:{NOTES_REF}"
def _git(repo: Path, *args: str, stdin: str | None = None) -> subprocess.CompletedProcess[str]:
- return subprocess.run(
- ["git", *args],
- cwd=repo,
- input=stdin,
- capture_output=True,
- text=True,
- encoding="utf-8",
- errors="replace",
- stdin=None if stdin is not None else subprocess.DEVNULL,
- check=False,
- )
+ # Ceiling: no timeout; a wedged git blocks this call.
+ return run_git(args, repo, input=stdin, timeout=None)
def session_key(tool: str, session: str) -> str: