"""Minimal read-only Git helpers used by adoption assess/plan/apply/verify. Adoption never commits, pushes, clones or touches remotes; these helpers only ever call read-only `git` subcommands, plus `git init` for `repoctl init --git-init`. """ from __future__ import annotations import subprocess from pathlib import Path def _run(args: list[str], cwd: Path) -> subprocess.CompletedProcess[str]: return subprocess.run( ["git", *args], cwd=cwd, capture_output=True, text=True, check=False ) def head_revision(root: Path) -> str: result = _run(["rev-parse", "HEAD"], root) if result.returncode != 0: return "unborn" return result.stdout.strip() def is_dirty(root: Path) -> bool: result = _run(["status", "--porcelain"], root) return bool(result.stdout.strip()) def tracked_files(root: Path) -> set[str]: result = _run(["ls-files"], root) if result.returncode != 0: return set() return {line.strip() for line in result.stdout.splitlines() if line.strip()} def dirty_paths(root: Path) -> set[str]: """Return every repository-relative path with staged, unstaged or untracked changes. `is_dirty` collapses this to a bool; adoption needs the paths themselves so `apply` can refuse to write into a file the user is already editing. Uses ``-z`` so paths containing spaces or non-ASCII are neither quoted nor mangled, and so rename entries split reliably: a rename emits the destination path, then a second NUL-terminated field holding the original path. """ result = _run(["status", "--porcelain", "-z"], root) if result.returncode != 0: return set() fields = [field for field in result.stdout.split("\0") if field] paths: set[str] = set() index = 0 while index < len(fields): entry = fields[index] index += 1 if len(entry) < 4: continue status, path = entry[:2], entry[3:] paths.add(path) if ("R" in status or "C" in status) and index < len(fields): paths.add(fields[index]) index += 1 return paths def ignored(root: Path, relative_paths: list[str]) -> set[str]: """Return the subset of ``relative_paths`` that Git ignores. Used to keep the secret-shaped scan quiet about gitignored material and to avoid walking large ignored trees. Returns an empty set when Git is unavailable, so callers degrade to reporting everything rather than nothing. """ if not relative_paths: return set() # `check-ignore` needs the candidates on stdin; `_run` does not pipe input, # so issue the call directly here rather than widening the shared helper. result = subprocess.run( ["git", "check-ignore", "-z", "--stdin"], cwd=root, input="\0".join(relative_paths), capture_output=True, text=True, check=False, ) if result.returncode not in (0, 1): return set() return {field for field in result.stdout.split("\0") if field}