Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions src/devscope/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
generate_json_summary,
generate_markdown_summary,
)
from devscope.index import RepositoryIndexer
from devscope.index.git_reader import GitError
from devscope.models import (
AnalysisResult,
CIResult,
Expand Down Expand Up @@ -375,6 +377,33 @@ def cli() -> None:
pass


@cli.command(name="index")
@click.argument("path", type=click.Path(exists=True, file_okay=False, path_type=Path), default=".")
@click.option("--rebuild", is_flag=True, help="Discard and safely rebuild the local history index")
@click.option("--since", help="Git date expression for the history window (default: 3 years ago)")
def index_command(path: Path, rebuild: bool, since: Optional[str]) -> None:
"""Build the external Git-history and bug-introduction index."""
try:
indexer = RepositoryIndexer(path, since=since)
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console,
transient=True,
) as progress:
progress.add_task("Indexing local Git history…", total=None)
result = indexer.build(rebuild=rebuild)
except (GitError, RuntimeError, OSError) as error:
raise click.ClickException(str(error)) from error

action = "Rebuilt" if result.rebuilt else "Updated"
console.print(f"[green]✓[/green] {action} history index at [dim]{result.path}[/dim]")
console.print(
f" {result.total_commits:,} commits · {result.indexed_commits:,} new · "
f"{result.bug_intro_rows:,} bug-introduction records"
)


@cli.command()
@click.argument("path", type=click.Path(exists=True, file_okay=False), default=".")
@click.option("--base", required=True, help="Target branch/ref; compares from its merge base")
Expand Down
5 changes: 5 additions & 0 deletions src/devscope/index/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
"""Local Git-history index used by Devscope's evidence engine."""

from devscope.index.incremental import IndexResult, RepositoryIndexer

__all__ = ["IndexResult", "RepositoryIndexer"]
267 changes: 267 additions & 0 deletions src/devscope/index/git_reader.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,267 @@
"""Small, offline-only Git subprocess adapter for the history index."""

import os
import subprocess
from collections.abc import Sequence
from dataclasses import dataclass
from pathlib import Path
from typing import Optional


class GitError(RuntimeError):
"""Raised when a Git operation cannot be completed safely."""


@dataclass(frozen=True)
class CommitInfo:
"""Metadata needed by the indexer for one commit."""

sha: str
parents: tuple[str, ...]
author_name: str
author_email: str
authored_at: int
committed_at: int
message: str


@dataclass(frozen=True)
class FileChange:
"""One numstat entry."""

path: str
old_path: Optional[str]
additions: int
deletions: int


class GitReader:
"""Read a local repository without hooks, network access, or GitPython."""

def __init__(self, path: Path) -> None:
self.root = Path(self.run(path, "rev-parse", "--show-toplevel").strip()).resolve()
common = self.run(self.root, "rev-parse", "--path-format=absolute", "--git-common-dir")
self.common_dir = Path(common.strip()).resolve()

@staticmethod
def run(cwd: Path, *args: str, input_text: Optional[str] = None) -> str:
"""Run Git with prompts, lazy fetching, hooks, and external diffs disabled."""
env = os.environ.copy()
env.update(
{
"GIT_TERMINAL_PROMPT": "0",
"GIT_NO_LAZY_FETCH": "1",
"GIT_CONFIG_NOSYSTEM": "1",
}
)
command = [
"git",
"-c",
"core.hooksPath=/dev/null",
"-c",
"diff.external=",
"-c",
"filter.lfs.smudge=",
*args,
]
completed = subprocess.run(
command,
cwd=cwd,
env=env,
input=input_text,
text=True,
capture_output=True,
check=False,
)
if completed.returncode != 0:
detail = completed.stderr.strip() or "Git command failed"
raise GitError(detail)
return completed.stdout

def head(self) -> str:
"""Return the current commit."""
return self.run(self.root, "rev-parse", "--verify", "HEAD").strip()

def is_ancestor(self, older: str, newer: str) -> bool:
"""Return whether older is reachable from newer."""
try:
self.run(self.root, "merge-base", "--is-ancestor", older, newer)
except GitError:
return False
return True

def revisions(self, *, since: Optional[str], max_count: int) -> list[str]:
"""Return the selected history oldest first."""
args = ["rev-list", "--topo-order", f"--max-count={max_count}"]
if since:
args.append(f"--since={since}")
args.append("HEAD")
return list(reversed(self.run(self.root, *args).splitlines()))

def commit_info(self, sha: str) -> CommitInfo:
"""Read commit metadata with record separators that are forbidden in refs."""
payload = self.run(
self.root,
"show",
"-s",
"--no-show-signature",
"--format=%H%x1f%P%x1f%an%x1f%ae%x1f%at%x1f%ct%x1f%B%x1e",
sha,
)
fields = payload.rstrip("\n\x1e").split("\x1f", 6)
if len(fields) != 7:
raise GitError(f"Could not parse commit {sha}")
return CommitInfo(
sha=fields[0],
parents=tuple(fields[1].split()),
author_name=fields[2],
author_email=fields[3],
authored_at=int(fields[4]),
committed_at=int(fields[5]),
message=fields[6].strip(),
)

def commit_infos(self, revisions: Sequence[str]) -> dict[str, CommitInfo]:
"""Read commit metadata in one subprocess for cold-index performance."""
if not revisions:
return {}
payload = self.run(
self.root,
"log",
"--no-walk=unsorted",
"--stdin",
"-z",
"--no-show-signature",
"--format=%H%x00%P%x00%an%x00%ae%x00%at%x00%ct%x00%B",
input_text="\n".join(revisions),
)
fields = payload.rstrip("\0").split("\0")
if len(fields) % 7:
raise GitError("Could not parse batched commit metadata")
result: dict[str, CommitInfo] = {}
for offset in range(0, len(fields), 7):
sha, parents, name, email, authored_at, committed_at, message = fields[
offset : offset + 7
]
result[sha] = CommitInfo(
sha=sha,
parents=tuple(parents.split()),
author_name=name,
author_email=email,
authored_at=int(authored_at),
committed_at=int(committed_at),
message=message.strip(),
)
return result

def changes(self, sha: str) -> list[FileChange]:
"""Read rename-aware numstat entries for one commit."""
raw = self.run(
self.root,
"diff-tree",
"--root",
"--no-commit-id",
"-r",
"-M",
"--numstat",
"-z",
sha,
)
return self._parse_changes(raw)

def changes_many(self, revisions: Sequence[str]) -> dict[str, list[FileChange]]:
"""Read rename-aware numstat for many commits in one Git process."""
if not revisions:
return {}
payload = self.run(
self.root,
"log",
"--no-walk=unsorted",
"--stdin",
"--root",
"-M",
"-z",
"--format=%x1e%H",
"--numstat",
input_text="\n".join(revisions),
)
result: dict[str, list[FileChange]] = {}
for record in payload.split("\x1e"):
if not record:
continue
sha, separator, raw = record.partition("\0")
if not separator:
raise GitError("Could not parse batched file changes")
result[sha] = self._parse_changes(raw.lstrip("\n"))
return result

@staticmethod
def _parse_changes(raw: str) -> list[FileChange]:
"""Parse Git's NUL-delimited rename-aware numstat format."""
parts = raw.split("\0")
result: list[FileChange] = []
index = 0
while index < len(parts) and parts[index]:
fields = parts[index].split("\t", 2)
index += 1
if len(fields) != 3:
continue
added, deleted, path = fields
old_path: Optional[str] = None
if not path and index + 1 < len(parts):
old_path, path = parts[index], parts[index + 1]
index += 2
result.append(
FileChange(
path=path,
old_path=old_path,
additions=0 if added == "-" else int(added),
deletions=0 if deleted == "-" else int(deleted),
)
)
return result

def text(self, revision: str, path: str) -> list[str]:
"""Read a text blob, returning no lines for binary or missing content."""
try:
value = self.run(self.root, "show", f"{revision}:{path}")
except GitError:
return []
if "\x00" in value:
return []
return value.splitlines()

def diff(self, parent: str, child: str, paths: Sequence[str]) -> str:
"""Return a zero-context diff for selected paths."""
return self.run(
self.root,
"diff",
"--no-ext-diff",
"--no-textconv",
"-M",
"--unified=0",
parent,
child,
"--",
*paths,
)

def blame(self, revision: str, path: str, ranges: Sequence[tuple[int, int]]) -> str:
"""Blame several inclusive ranges in one move/copy-aware call."""
args = ["blame", "--line-porcelain", "-w", "-M", "-C"]
ignore_revs = self.root / ".git-blame-ignore-revs"
for start, end in ranges:
args.append(f"-L{start},{end}")
if not ignore_revs.is_file():
return self.run(self.root, *args, revision, "--", path)
try:
return self.run(
self.root,
*args,
"--ignore-revs-file=.git-blame-ignore-revs",
revision,
"--",
path,
)
except GitError:
return self.run(self.root, *args, revision, "--", path)
Loading
Loading