Repository navigation
Expand file tree
/
Copy pathgit-reset-hunk
More file actions
executable file
·73 lines (55 loc) · 2.08 KB
/
Copy pathgit-reset-hunk
File metadata and controls
executable file
·73 lines (55 loc) · 2.08 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/env python3
import os, sys, subprocess
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
import git_hunk_utils
USAGE = """\
usage: git reset-hunk <file> <hunk-id>...
Selectively unstage hunks from the index.
Hunk IDs use the NEW file side of the @@ header: +offset,count
Example: @@ -10,5 +12,7 @@ → hunk ID is +12,7 (NOT -10,5)
Run 'git diff --cached <file>' to see available hunk IDs."""
def main():
if len(sys.argv) < 3:
print(USAGE, file=sys.stderr)
sys.exit(1)
filepath = sys.argv[1]
requested_ids = set(sys.argv[2:])
text = git_hunk_utils.run_git_diff([filepath], cached=True)
if not text.strip():
print(f"no staged changes in {filepath}", file=sys.stderr)
sys.exit(1)
files = git_hunk_utils.parse_diff(text)
if not files:
print(f"no staged changes in {filepath}", file=sys.stderr)
sys.exit(1)
file_diff = files[0]
available_ids = {h.id for h in file_diff.hunks}
unknown = requested_ids - available_ids
if unknown:
for uid in sorted(unknown):
print(f"error: unknown hunk ID: {uid}", file=sys.stderr)
if uid.startswith("-"):
print(f" hint: '{uid}' is the OLD file side; use the NEW file side (+offset,count) instead", file=sys.stderr)
print(f"\navailable hunk IDs for {filepath}:", file=sys.stderr)
for h in file_diff.hunks:
print(f" {h.id}", file=sys.stderr)
sys.exit(1)
selected = [h for h in file_diff.hunks if h.id in requested_ids]
patch = reassemble_patch(file_diff.header, selected)
proc = subprocess.run(
["git", "apply", "--cached", "--reverse"],
input=patch,
text=True,
capture_output=True,
)
if proc.returncode != 0:
print(proc.stderr, file=sys.stderr, end="")
sys.exit(proc.returncode)
def reassemble_patch(file_header, hunks):
parts = [file_header]
for h in hunks:
parts.append(h.header_line + "\n")
parts.append(h.body + "\n")
return "".join(parts)
if __name__ == "__main__":
main()