-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit.py
More file actions
53 lines (40 loc) · 1.58 KB
/
Copy pathgit.py
File metadata and controls
53 lines (40 loc) · 1.58 KB
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
from __future__ import annotations
import subprocess
from dataclasses import dataclass
from pathlib import Path
@dataclass(frozen=True)
class GitChange:
path: str
status: str = "modified"
def _run_git(args: list[str], root: str | Path = ".") -> str:
try:
return subprocess.check_output(["git", *args], cwd=str(root), text=True, stderr=subprocess.DEVNULL)
except Exception:
return ""
def staged_files(root: str | Path = ".") -> list[GitChange]:
out = _run_git(["diff", "--cached", "--name-status", "--diff-filter=ACMR"], root)
changes: list[GitChange] = []
for line in out.splitlines():
if not line.strip():
continue
parts = line.split(maxsplit=1)
if len(parts) == 2:
changes.append(GitChange(path=parts[1], status=parts[0]))
return changes
def changed_files(root: str | Path = ".", base_ref: str = "main") -> list[GitChange]:
out = _run_git(["diff", "--name-status", "--diff-filter=ACMR", f"{base_ref}...HEAD"], root)
changes: list[GitChange] = []
for line in out.splitlines():
if not line.strip():
continue
parts = line.split(maxsplit=1)
if len(parts) == 2:
changes.append(GitChange(path=parts[1], status=parts[0]))
return changes
def staged_hunks(root: str | Path = ".", path: str | None = None) -> str:
args = ["diff", "--cached", "--unified=0"]
if path:
args.extend(["--", path])
return _run_git(args, root)
def paths_from_changes(changes: list[GitChange]) -> list[str]:
return sorted({c.path for c in changes})