""" Git inspection and integration helpers for TIMELORD. Safe against non-git directories. """ import subprocess from pathlib import Path from typing import Any, Dict, List, Optional def is_git_repository(path: Path) -> bool: try: res = subprocess.run( ["git", "-C", str(path), "rev-parse", "--is-inside-work-tree"], capture_output=True, text=True, check=False, ) return res.returncode == 0 and res.stdout.strip() == "true" except Exception: return False def get_git_state(path: Path) -> Dict[str, Any]: """Extracts git metadata: current branch, commit, dirty status, diff summaries.""" if not is_git_repository(path): return { "is_git": False, "branch": None, "head_sha": None, "head_message": None, "is_dirty": False, "staged_files": [], "unstaged_files": [], "untracked_files": [], "stash_count": 0, } def _run_git(args: List[str]) -> str: res = subprocess.run( ["git", "-C", str(path)] + args, capture_output=True, text=True, check=False, ) return res.stdout.strip() if res.returncode == 0 else "" # Branch branch = _run_git(["branch", "--show-current"]) if not branch: branch = _run_git(["rev-parse", "--short", "HEAD"]) or "HEAD" # HEAD commit head_sha = _run_git(["rev-parse", "HEAD"]) head_msg = _run_git(["log", "-1", "--pretty=%B"]) # Status porcelein status_raw = _run_git(["status", "--porcelain"]) staged = [] unstaged = [] untracked = [] for line in status_raw.splitlines(): if not line: continue code = line[:2] filename = line[3:].strip() if code[0] in ("M", "A", "D", "R", "C"): staged.append(filename) if code[1] in ("M", "D"): unstaged.append(filename) if code == "??": untracked.append(filename) # Stash count stash_raw = _run_git(["stash", "list"]) stash_count = len(stash_raw.splitlines()) if stash_raw else 0 return { "is_git": True, "branch": branch, "head_sha": head_sha[:8] if head_sha else None, "head_sha_full": head_sha, "head_message": head_msg.splitlines()[0] if head_msg else None, "is_dirty": bool(staged or unstaged or untracked), "staged_files": staged, "unstaged_files": unstaged, "untracked_files": untracked, "stash_count": stash_count, } def get_git_diff(path: Path, staged: bool = False) -> str: """Returns the git diff for staged or unstaged changes.""" if not is_git_repository(path): return "" args = ["git", "-C", str(path), "diff"] if staged: args.append("--staged") res = subprocess.run(args, capture_output=True, text=True, check=False) return res.stdout if res.returncode == 0 else ""