summaryrefslogtreecommitdiff
path: root/timelord/utils/git_helper.py
blob: 94c23ec6ae770fba6d384d10b70d24b731b30459 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
"""
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 ""