diff --git a/src/devscope/cli.py b/src/devscope/cli.py index 2ee7408..125e44c 100644 --- a/src/devscope/cli.py +++ b/src/devscope/cli.py @@ -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, @@ -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") diff --git a/src/devscope/index/__init__.py b/src/devscope/index/__init__.py new file mode 100644 index 0000000..6c4b85d --- /dev/null +++ b/src/devscope/index/__init__.py @@ -0,0 +1,5 @@ +"""Local Git-history index used by Devscope's evidence engine.""" + +from devscope.index.incremental import IndexResult, RepositoryIndexer + +__all__ = ["IndexResult", "RepositoryIndexer"] diff --git a/src/devscope/index/git_reader.py b/src/devscope/index/git_reader.py new file mode 100644 index 0000000..04854db --- /dev/null +++ b/src/devscope/index/git_reader.py @@ -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) diff --git a/src/devscope/index/incremental.py b/src/devscope/index/incremental.py new file mode 100644 index 0000000..316c595 --- /dev/null +++ b/src/devscope/index/incremental.py @@ -0,0 +1,280 @@ +"""Incremental Git history indexing and local SZZ extraction.""" + +import json +import multiprocessing +import os +from concurrent.futures import ProcessPoolExecutor +from dataclasses import dataclass +from pathlib import Path +from typing import Optional + +from devscope.index.git_reader import CommitInfo, FileChange, GitReader +from devscope.index.store import IndexStore, cache_path +from devscope.szz.blame import added_lines, parse_blame, removed_ranges +from devscope.szz.filters import is_ignored_line, is_source_path, is_test_path +from devscope.szz.fix_detector import is_fix_message + +DEFAULT_SINCE = "3 years ago" +DEFAULT_MAX_COMMITS = 5_000 +ENGINE_VERSION = 2 +MAX_FIX_FILES = 50 +MAX_FIX_LINES = 5_000 + + +@dataclass(frozen=True) +class IndexResult: + path: Path + head: str + indexed_commits: int + total_commits: int + bug_intro_rows: int + rebuilt: bool + + +@dataclass(frozen=True) +class _SzzJob: + root: Path + fix_sha: str + parent: str + fix_ts: int + change: FileChange + + +@dataclass(frozen=True) +class _SzzEvidence: + intro_sha: str + fix_sha: str + path: str + intro_path: str + line: int + fix_ts: int + + +def _run_szz_job(job: _SzzJob) -> list[_SzzEvidence]: + """Extract SZZ evidence for one fixed file in an isolated worker.""" + git = GitReader(job.root) + old_path = job.change.old_path or job.change.path + diff = git.diff(job.parent, job.fix_sha, [old_path, job.change.path]) + moved_code = added_lines(diff) + parent_lines = git.text(job.parent, old_path) + evidence: list[_SzzEvidence] = [] + ranges = removed_ranges(diff) + if not ranges: + return [] + for blamed in parse_blame(git.blame(job.parent, old_path, ranges), old_path): + content = ( + parent_lines[blamed.original_line - 1] + if blamed.original_line <= len(parent_lines) + else "" + ) + if ( + is_ignored_line(content, old_path) + or content.strip() in moved_code + or blamed.sha.startswith("0000000") + ): + continue + evidence.append( + _SzzEvidence( + blamed.sha, + job.fix_sha, + job.change.path, + blamed.path, + blamed.original_line, + job.fix_ts, + ) + ) + return evidence + + +class RepositoryIndexer: + """Maintain the repository's external, transactional evidence index.""" + + def __init__( + self, + path: Path, + *, + since: Optional[str] = None, + max_commits: int = DEFAULT_MAX_COMMITS, + max_workers: Optional[int] = None, + ) -> None: + self.git = GitReader(path) + self.since = since or DEFAULT_SINCE + self.max_commits = max_commits + self.max_workers = max_workers or min(8, os.cpu_count() or 1) + self.path = cache_path(self.git.common_dir) + self._commit_infos: dict[str, CommitInfo] = {} + self._changes: dict[str, list[FileChange]] = {} + self._szz_jobs: list[_SzzJob] = [] + + def build(self, *, rebuild: bool = False) -> IndexResult: + head = self.git.head() + revisions = self.git.revisions(since=self.since, max_count=self.max_commits) + settings = json.dumps( + {"since": self.since, "max_commits": self.max_commits}, sort_keys=True + ) + with IndexStore(self.path) as store: + previous_head = store.get_meta("head") + stored_engine_version = store.get_meta("engine_version") + needs_rebuild = rebuild or stored_engine_version != str(ENGINE_VERSION) + if previous_head and not self.git.is_ancestor(previous_head, head): + needs_rebuild = True + existing = {str(row[0]) for row in store.rows("SELECT sha FROM commits")} + try: + store.connection.execute("BEGIN") + if needs_rebuild: + store.clear() + existing.clear() + else: + stale = existing.difference(revisions) + store.prune_commits(stale) + existing.difference_update(stale) + pending = [revision for revision in revisions if revision not in existing] + self._commit_infos = self.git.commit_infos(pending) + self._changes = self.git.changes_many(pending) + self._szz_jobs = [] + for sha in pending: + self._index_commit(store, sha) + self._flush_szz(store) + self._rebuild_cochange(store) + store.set_meta("head", head) + store.set_meta("settings", settings) + store.set_meta("engine_version", str(ENGINE_VERSION)) + store.connection.commit() + except Exception: + store.connection.rollback() + raise + total = int(store.connection.execute("SELECT COUNT(*) FROM commits").fetchone()[0]) + bug_rows = int(store.connection.execute("SELECT COUNT(*) FROM bug_intro").fetchone()[0]) + return IndexResult(self.path, head, len(pending), total, bug_rows, needs_rebuild) + + def _index_commit(self, store: IndexStore, sha: str) -> None: + info = self._commit_infos.get(sha) or self.git.commit_info(sha) + changes = self._changes[sha] if sha in self._changes else self.git.changes(sha) + additions = sum(change.additions for change in changes) + deletions = sum(change.deletions for change in changes) + fix = is_fix_message(info.message) + store.connection.execute( + "INSERT INTO commits " + "(sha, authored_at, committed_at, author_name, author_email, message, is_fix, " + "is_merge, files_changed, additions, deletions, parents) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + ( + sha, + info.authored_at, + info.committed_at, + info.author_name, + info.author_email, + info.message, + int(fix), + int(len(info.parents) > 1), + len(changes), + additions, + deletions, + json.dumps(info.parents), + ), + ) + for change in changes: + store.connection.execute( + "INSERT INTO file_changes VALUES (?, ?, ?, ?, ?, ?, ?)", + ( + sha, + change.path, + change.old_path, + change.additions, + change.deletions, + int(is_source_path(change.path)), + int(is_test_path(change.path)), + ), + ) + if ( + fix + and len(info.parents) == 1 + and len(changes) <= MAX_FIX_FILES + and additions + deletions <= MAX_FIX_LINES + ): + self._szz_jobs.extend( + _SzzJob(self.git.root, sha, info.parents[0], info.committed_at, change) + for change in changes + if change.deletions and is_source_path(change.old_path or change.path) + ) + + def _flush_szz(self, store: IndexStore) -> None: + if not self._szz_jobs: + return + if self.max_workers == 1: + batches = [_run_szz_job(job) for job in self._szz_jobs] + else: + with ProcessPoolExecutor( + max_workers=self.max_workers, + mp_context=multiprocessing.get_context("spawn"), + ) as executor: + batches = list(executor.map(_run_szz_job, self._szz_jobs, chunksize=4)) + evidence = [item for batch in batches for item in batch] + intro_metadata = { + str(row[0]): (int(row[1]), int(row[2])) + for row in store.rows("SELECT sha, committed_at, files_changed FROM commits") + } + missing = sorted({item.intro_sha for item in evidence}.difference(intro_metadata)) + missing_infos = self.git.commit_infos(missing) + missing_changes = self.git.changes_many(missing) + for sha, info in missing_infos.items(): + changes = missing_changes[sha] if sha in missing_changes else self.git.changes(sha) + intro_metadata[sha] = (info.committed_at, len(changes)) + + evidence = [item for item in evidence if intro_metadata[item.intro_sha][1] <= MAX_FIX_FILES] + + grouped: dict[tuple[str, str, str, str, int], list[int]] = {} + for item in evidence: + key = (item.intro_sha, item.fix_sha, item.path, item.intro_path, item.fix_ts) + grouped.setdefault(key, []).append(item.line) + store.connection.executemany( + "INSERT OR IGNORE INTO bug_intro VALUES (?, ?, ?, ?, ?, ?, ?)", + ( + ( + intro_sha, + fix_sha, + path, + intro_path, + json.dumps(sorted(set(lines))), + intro_metadata[intro_sha][0], + fix_ts, + ) + for (intro_sha, fix_sha, path, intro_path, fix_ts), lines in grouped.items() + ), + ) + + @staticmethod + def _rebuild_cochange(store: IndexStore) -> None: + store.connection.execute("DELETE FROM cochange") + file_counts = { + str(row[0]): int(row[1]) + for row in store.rows( + "SELECT path, COUNT(*) FROM file_changes WHERE is_source = 1 GROUP BY path" + ) + } + pairs: dict[tuple[str, str], tuple[int, str]] = {} + commits = store.rows( + "SELECT f.commit_sha FROM file_changes f JOIN commits c ON c.sha = f.commit_sha " + "GROUP BY f.commit_sha HAVING COUNT(*) <= 30 ORDER BY c.committed_at, f.commit_sha" + ) + for commit in commits: + paths = [ + str(row[0]) + for row in store.rows( + "SELECT path FROM file_changes WHERE commit_sha = ? AND is_source = 1 ORDER BY path", + (commit[0],), + ) + ] + for path in paths: + for partner in paths: + if path != partner: + support, _ = pairs.get((path, partner), (0, "")) + pairs[(path, partner)] = (support + 1, str(commit[0])) + store.connection.executemany( + "INSERT INTO cochange(path, partner, support, confidence, last_sha) " + "VALUES (?, ?, ?, ?, ?)", + ( + (path, partner, support, support / file_counts[path], last_sha) + for (path, partner), (support, last_sha) in pairs.items() + ), + ) diff --git a/src/devscope/index/store.py b/src/devscope/index/store.py new file mode 100644 index 0000000..af7f26d --- /dev/null +++ b/src/devscope/index/store.py @@ -0,0 +1,124 @@ +"""Versioned SQLite storage for the local history index.""" + +import hashlib +import os +import sqlite3 +from collections.abc import Iterator +from pathlib import Path +from typing import Optional + +from platformdirs import user_cache_path + +SCHEMA_VERSION = 2 + + +def cache_path(common_git_dir: Path) -> Path: + """Return a stable external cache path for a repository.""" + digest = hashlib.sha256(str(common_git_dir).encode()).hexdigest()[:20] + override = os.environ.get("DEVSCOPE_CACHE_DIR") + base = Path(override) if override else user_cache_path("devscope") + return base / digest / "index.sqlite" + + +class IndexStore: + """Own the SQLite connection and schema lifecycle.""" + + def __init__(self, path: Path) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + self.path = path + self.connection = sqlite3.connect(path) + self.connection.row_factory = sqlite3.Row + self.connection.execute("PRAGMA foreign_keys=ON") + self.connection.execute("PRAGMA journal_mode=WAL") + self.connection.execute("PRAGMA busy_timeout=5000") + self._migrate() + + def __enter__(self) -> "IndexStore": + return self + + def __exit__(self, *_args: object) -> None: + self.connection.close() + + def _migrate(self) -> None: + version = int(self.connection.execute("PRAGMA user_version").fetchone()[0]) + if version > SCHEMA_VERSION: + raise RuntimeError("This index was created by a newer Devscope version") + if version == 0: + self.connection.executescript( + """ + CREATE TABLE commits ( + sha TEXT PRIMARY KEY, authored_at INTEGER NOT NULL, + committed_at INTEGER NOT NULL, author_name TEXT NOT NULL, + author_email TEXT NOT NULL, message TEXT NOT NULL, + is_fix INTEGER NOT NULL, is_merge INTEGER NOT NULL, + files_changed INTEGER NOT NULL, additions INTEGER NOT NULL, + deletions INTEGER NOT NULL, parents TEXT NOT NULL + ); + CREATE TABLE file_changes ( + commit_sha TEXT NOT NULL REFERENCES commits(sha) ON DELETE CASCADE, + path TEXT NOT NULL, old_path TEXT, additions INTEGER NOT NULL, + deletions INTEGER NOT NULL, is_source INTEGER NOT NULL, + is_test INTEGER NOT NULL, + PRIMARY KEY (commit_sha, path) + ); + CREATE TABLE bug_intro ( + intro_sha TEXT NOT NULL, fix_sha TEXT NOT NULL, + path TEXT NOT NULL, intro_path TEXT NOT NULL, + lines TEXT NOT NULL, intro_ts INTEGER NOT NULL, fix_ts INTEGER NOT NULL, + PRIMARY KEY (intro_sha, fix_sha, path, lines) + ); + CREATE TABLE cochange ( + path TEXT NOT NULL, partner TEXT NOT NULL, + support INTEGER NOT NULL, confidence REAL NOT NULL, + last_sha TEXT NOT NULL, + PRIMARY KEY (path, partner) + ); + CREATE TABLE imports ( + path TEXT NOT NULL, imported_path TEXT NOT NULL, + PRIMARY KEY (path, imported_path) + ); + CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL); + CREATE INDEX bug_intro_path_idx ON bug_intro(path); + CREATE INDEX file_changes_path_idx ON file_changes(path); + PRAGMA user_version = 2; + """ + ) + self.connection.commit() + elif version == 1: + self.connection.executescript( + """ + ALTER TABLE commits ADD COLUMN parents TEXT NOT NULL DEFAULT '[]'; + ALTER TABLE cochange ADD COLUMN last_sha TEXT NOT NULL DEFAULT ''; + PRAGMA user_version = 2; + """ + ) + self.connection.commit() + + def clear(self) -> None: + """Clear indexed data while retaining the schema.""" + for table in ("bug_intro", "cochange", "imports", "file_changes", "commits", "meta"): + self.connection.execute(f"DELETE FROM {table}") + + def prune_commits(self, shas: set[str]) -> None: + """Remove commits that aged out of the selected history window.""" + if not shas: + return + values = [(sha,) for sha in shas] + self.connection.executemany("DELETE FROM bug_intro WHERE fix_sha = ?", values) + self.connection.executemany("DELETE FROM file_changes WHERE commit_sha = ?", values) + self.connection.executemany("DELETE FROM commits WHERE sha = ?", values) + + def get_meta(self, key: str) -> Optional[str]: + row = self.connection.execute("SELECT value FROM meta WHERE key = ?", (key,)).fetchone() + return None if row is None else str(row[0]) + + def set_meta(self, key: str, value: str) -> None: + self.connection.execute( + "INSERT INTO meta(key, value) VALUES(?, ?) " + "ON CONFLICT(key) DO UPDATE SET value=excluded.value", + (key, value), + ) + + def rows(self, sql: str, values: tuple[object, ...] = ()) -> Iterator[sqlite3.Row]: + """Yield rows for tests and downstream feature readers.""" + yield from self.connection.execute(sql, values) diff --git a/src/devscope/szz/__init__.py b/src/devscope/szz/__init__.py new file mode 100644 index 0000000..8a9fed7 --- /dev/null +++ b/src/devscope/szz/__init__.py @@ -0,0 +1,5 @@ +"""SZZ bug-introduction evidence extraction.""" + +from devscope.szz.fix_detector import is_fix_message + +__all__ = ["is_fix_message"] diff --git a/src/devscope/szz/blame.py b/src/devscope/szz/blame.py new file mode 100644 index 0000000..a695137 --- /dev/null +++ b/src/devscope/szz/blame.py @@ -0,0 +1,55 @@ +"""Diff and blame parsing helpers for SZZ.""" + +from __future__ import annotations + +import re +from dataclasses import dataclass + +HUNK = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+\d+(?:,\d+)? @@") +BLAME_HEADER = re.compile(r"^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$") + + +@dataclass(frozen=True) +class BlamedLine: + sha: str + original_line: int + path: str + + +def removed_ranges(diff: str) -> list[tuple[int, int]]: + """Extract deleted-line ranges from a zero-context single-file diff.""" + ranges: list[tuple[int, int]] = [] + for line in diff.splitlines(): + match = HUNK.match(line) + if not match: + continue + start = int(match.group(1)) + count = int(match.group(2) or "1") + if count: + ranges.append((start, start + count - 1)) + return ranges + + +def added_lines(diff: str) -> set[str]: + """Return normalized added code, used to reject moved-only evidence.""" + return { + line[1:].strip() + for line in diff.splitlines() + if line.startswith("+") and not line.startswith("+++") and line[1:].strip() + } + + +def parse_blame(output: str, fallback_path: str) -> list[BlamedLine]: + """Parse line-porcelain output, retaining original file paths.""" + result: list[BlamedLine] = [] + current: BlamedLine | None = None + for line in output.splitlines(): + header = BLAME_HEADER.match(line) + if header: + current = BlamedLine(header.group(1), int(header.group(2)), fallback_path) + elif line.startswith("filename ") and current: + current = BlamedLine(current.sha, current.original_line, line[9:]) + elif line.startswith("\t") and current: + result.append(current) + current = None + return result diff --git a/src/devscope/szz/filters.py b/src/devscope/szz/filters.py new file mode 100644 index 0000000..c089aa9 --- /dev/null +++ b/src/devscope/szz/filters.py @@ -0,0 +1,60 @@ +"""Conservative file and line filters for SZZ evidence.""" + +from __future__ import annotations + +from pathlib import PurePosixPath + +SOURCE_EXTENSIONS = { + ".c", + ".cc", + ".cpp", + ".cs", + ".go", + ".h", + ".hpp", + ".java", + ".js", + ".jsx", + ".kt", + ".kts", + ".m", + ".mm", + ".php", + ".py", + ".rb", + ".rs", + ".scala", + ".swift", + ".ts", + ".tsx", +} + + +def is_test_path(path: str) -> bool: + """Identify conventional test paths without substring false positives.""" + candidate = PurePosixPath(path) + parts = {part.lower() for part in candidate.parts[:-1]} + stem = candidate.stem.lower() + return bool(parts & {"test", "tests", "spec", "specs", "__tests__"}) or ( + stem.startswith("test_") or stem.endswith(("_test", ".test", ".spec")) + ) + + +def is_source_path(path: str) -> bool: + candidate = PurePosixPath(path) + lowered = {part.lower() for part in candidate.parts} + return ( + candidate.suffix.lower() in SOURCE_EXTENSIONS + and not is_test_path(path) + and not lowered.intersection({"docs", "doc", ".github", "vendor", "generated"}) + ) + + +def is_ignored_line(line: str, path: str = "") -> bool: + """Drop blank and unambiguously comment-only lines.""" + stripped = line.strip() + if not stripped or stripped.startswith(("//", "/*", "*", "