-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitdiffshow.bash
More file actions
executable file
·1236 lines (1063 loc) · 40.2 KB
/
gitdiffshow.bash
File metadata and controls
executable file
·1236 lines (1063 loc) · 40.2 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
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# ======================================================================
# gitdiffshow - Show context for files changed in git diff
# ======================================================================
# ----------------------------------------------------------------------
# Force NO PAGERS anywhere (important for copy/paste into AI).
# Git and bat commonly page with `less` depending on user config.
# ----------------------------------------------------------------------
# We pass these to child processes via 'env' to avoid polluting the shell
# if this script is sourced.
GITDIFFSHOW_NO_PAGER_ENV=(PAGER=cat GIT_PAGER=cat BAT_PAGER=cat BAT_PAGING=never LESS=FRX)
#
# DEFAULT BEHAVIOR:
# - For Python files (*.py): print ONLY the functions/methods that contain
# the changed lines (using print_function.sh), plus small numbered excerpts
# for any module/class-scope changes.
# - For non-Python files: print numbered excerpts around changed hunks.
#
# FLAGS:
# --printwholefile Print the entire file with line numbers (old behavior)
# --all Alias for --printwholefile (requested)
# --diff Print git diff output in addition to the function context
# --patch FILE Read diff from a patch file (or - for stdin) instead of git diff
# --binarydiff Show diff for binary files (default: skip binary files)
# --relative Only show files relative to the current directory
# --color Force ANSI color output
# --no-color Disable ANSI color (best for pasting into AI)
#
# TIP:
# Tune excerpt size with:
# export GITDIFFSHOW_CONTEXT=30
#
# Version 1.1.1 by Alan Rockefeller - March 26, 2026
#
# ======================================================================
set -euo pipefail
__gitdiffshow_find_printfunc() {
local candidates=(print_function.sh printfunction.sh print_function printfunction)
local c
for c in "${candidates[@]}"; do
if command -v "$c" >/dev/null 2>&1; then
echo "$c"
return 0
fi
done
return 1
}
__gitdiffshow_print_excerpt() {
local file="$1"
local start_line="${2:-}"
local end_line="${3:-}"
local label="${4:-}"
[[ -z "$start_line" || -z "$end_line" ]] && return 0
local color_mode="${GITDIFFSHOW_COLOR_MODE:-auto}"
local bat_color="$color_mode"
echo "--- $label (lines $start_line-$end_line) ---"
# Best: bat/batcat can show real file line numbers and syntax highlight directly.
if command -v batcat >/dev/null 2>&1; then
env "${GITDIFFSHOW_NO_PAGER_ENV[@]}" batcat --color="$bat_color" --paging=never --style=numbers --line-range "${start_line}:${end_line}" "$file"
return 0
elif command -v bat >/dev/null 2>&1; then
env "${GITDIFFSHOW_NO_PAGER_ENV[@]}" bat --color="$bat_color" --paging=never --style=numbers --line-range "${start_line}:${end_line}" "$file"
return 0
fi
# Fallback: pygmentize (we slice the file then set linenostart so numbers match)
if [[ "$color_mode" != "never" ]] && command -v pygmentize >/dev/null 2>&1; then
if sed -n "${start_line},${end_line}p" "$file" | pygmentize -g -f terminal256 -O "style=monokai,linenos=1,linenostart=${start_line}" 2>/dev/null; then
return 0
fi
sed -n "${start_line},${end_line}p" "$file" | pygmentize -g -f terminal256 -O "linenos=1,linenostart=${start_line}"
return 0
fi
# Last resort: plain numbered output
sed -n "${start_line},${end_line}p" "$file" | nl -ba -n ln -v "$start_line"
}
# __gitdiffshow_patch_helper: Unified Python-based patch parser.
# Handles all patch parsing operations via a single Python script.
#
# Usage:
# __gitdiffshow_patch_helper <command> <patch_file> [args...]
#
# Commands:
# list-files <patch_file> [<base_dir>]
# Output one line per file entry: INDEX|STATUS|OLD_PATH|NEW_PATH[|ABS_PATH]
# INDEX is the 0-based position in the parsed patch (for repeated paths).
# STATUS is one of: modified, added, deleted, renamed, copied
# When base_dir is given, a 5th field ABS_PATH is appended (realpath'd),
# and entries whose resolved path escapes base_dir are omitted.
#
# analyze <patch_file> <file_path> [local_path] [entry_index]
# Output analysis lines (same format as __gitdiffshow_analyze_file):
# HUNK|start|end|label, FUNC|qualname|start|end, NONFUNC|start|end|label, NOTE|msg
# entry_index selects which patch entry to use (for repeated paths).
#
# raw-diff <patch_file> <file_path> [entry_index]
# Output the raw diff section for a single file from the patch.
# entry_index selects which patch entry to use (for repeated paths).
#
# <patch_file> can be "-" to read from stdin (already captured to a temp file by caller).
#
__gitdiffshow_patch_helper() {
local cmd="$1"; shift
local patch_file="$1"; shift
local -a extra_args=("$@")
local stderr_target="/dev/null"
if [[ -n "${GITDIFFSHOW_DEBUG:-}" ]]; then
stderr_target="/dev/stderr"
fi
python3 - "$cmd" "$patch_file" "${extra_args[@]}" 2>"$stderr_target" <<'PYEOF'
import ast
import os
import re
import sys
import tokenize
from dataclasses import dataclass
from typing import Dict, List, Optional, Tuple
# ---------------------------------------------------------------------------
# Patch parser: split a unified diff into per-file sections
# ---------------------------------------------------------------------------
@dataclass
class PatchFile:
"""One file entry parsed from a unified diff."""
status: str # modified, added, deleted, renamed, copied
old_path: str # path on the --- side (empty for added)
new_path: str # path on the +++ side (empty for deleted)
header: str # the "diff --git ..." header line
raw_text: str # full text of this file's diff section
is_binary: bool = False
def parse_patch(patch_text: str) -> List[PatchFile]:
"""Parse a unified diff into per-file PatchFile entries."""
# Split on "diff --git" boundaries
file_re = re.compile(r"^diff --git ", re.M)
splits = file_re.split(patch_text)
# First element is anything before the first "diff --git" (usually empty)
results: List[PatchFile] = []
for section in splits[1:]:
full_section = "diff --git " + section
header_line = full_section.split("\n", 1)[0]
# Parse old/new paths from the header: diff --git a/old b/new
# Handle paths with spaces by matching "a/" prefix and " b/" separator
hdr_match = re.match(r"diff --git a/(.*?) b/(.*)", header_line)
if not hdr_match:
continue
raw_old = hdr_match.group(1)
raw_new = hdr_match.group(2)
# Determine status from the diff header block
status = "modified"
old_path = raw_old
new_path = raw_new
if re.search(r"^new file mode", full_section, re.M):
status = "added"
old_path = ""
elif re.search(r"^deleted file mode", full_section, re.M):
status = "deleted"
new_path = ""
else:
# Check for rename/copy
rename_from = re.search(r"^rename from (.+)", full_section, re.M)
rename_to = re.search(r"^rename to (.+)", full_section, re.M)
if rename_from and rename_to:
status = "renamed"
old_path = rename_from.group(1)
new_path = rename_to.group(1)
else:
copy_from = re.search(r"^copy from (.+)", full_section, re.M)
copy_to = re.search(r"^copy to (.+)", full_section, re.M)
if copy_from and copy_to:
status = "copied"
old_path = copy_from.group(1)
new_path = copy_to.group(1)
# Also check --- / +++ for /dev/null confirmation
minus_match = re.search(r"^--- (?:a/(.+)|/dev/null)", full_section, re.M)
plus_match = re.search(r"^\+\+\+ (?:b/(.+)|/dev/null)", full_section, re.M)
if minus_match and minus_match.group(1) is None and status != "added":
status = "added"
old_path = ""
if plus_match and plus_match.group(1) is None and status != "deleted":
status = "deleted"
new_path = ""
is_binary = re.search(r"^Binary files ", full_section, re.M) is not None or \
re.search(r"^GIT binary patch", full_section, re.M) is not None
results.append(PatchFile(
status=status,
old_path=old_path,
new_path=new_path,
header=header_line,
raw_text=full_section,
is_binary=is_binary,
))
return results
def find_patch_for_path(entries: List[PatchFile], target_path: str) -> Optional[PatchFile]:
"""Find the PatchFile entry whose new_path (or old_path for deletes) matches target_path."""
for e in entries:
# For display, the "current" path is new_path for non-deletes, old_path for deletes
display_path = e.new_path if e.status != "deleted" else e.old_path
if display_path == target_path:
return e
return None
# ---------------------------------------------------------------------------
# Hunk analysis (shared with git-diff mode)
# ---------------------------------------------------------------------------
CTX = int(os.environ.get("GITDIFFSHOW_CONTEXT", "20"))
hunk_re = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@", re.M)
def changed_lines_from_patch_text(patch_text: str) -> List[int]:
changed: List[int] = []
lines = patch_text.split('\n')
new_line_num = 0
in_hunk = False
for line in lines:
m = hunk_re.match(line)
if m:
new_line_num = int(m.group(3))
new_count = int(m.group(4) or "1")
if new_count == 0:
changed.append(new_line_num)
in_hunk = True
continue
if not in_hunk:
continue
if line.startswith('+'):
changed.append(new_line_num)
new_line_num += 1
elif line.startswith('-'):
changed.append(new_line_num)
elif line.startswith(' '):
new_line_num += 1 # context line, not changed
elif line.startswith('\\'):
pass # "\ No newline at end of file"
else:
in_hunk = False
return sorted(set(changed))
def merge_ranges(ranges: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
if not ranges:
return []
ranges = sorted(ranges)
out: List[List[int]] = [[ranges[0][0], ranges[0][1]]]
for s, e in ranges[1:]:
if s <= out[-1][1] + 1:
out[-1][1] = max(out[-1][1], e)
else:
out.append([s, e])
return [(a, b) for a, b in out]
def ranges_around(lines_: List[int], label: str, nlines: int) -> List[Tuple[int, int, str]]:
rs = []
for ln in lines_:
s = max(1, ln - CTX)
e = min(nlines, ln + CTX)
rs.append((s, e))
merged = merge_ranges(rs)
return [(a, b, label) for a, b in merged]
def analyze_file_with_patch_text(path: str, patch_text: str):
"""Analyze a file given its patch text. Print analysis lines to stdout."""
if not patch_text.strip():
return
if "Binary files " in patch_text:
print("NOTE|Binary diff (no text hunks)")
return
changed_lines = changed_lines_from_patch_text(patch_text)
if not changed_lines:
print("NOTE|No text hunks found")
return
if not os.path.exists(path):
print("NOTE|File not found in working tree (likely deleted)")
return
try:
with tokenize.open(path) as f:
source = f.read()
except Exception as e:
print(f"NOTE|Could not read file: {e}")
return
lines = source.splitlines(True)
nlines = len(lines)
if nlines == 0:
print("NOTE|Empty file")
return
def clamp_line(n: int) -> int:
if n < 1:
return 1
if n > nlines:
return nlines
return n
changed_lines = [clamp_line(x) for x in changed_lines]
# Always emit generic hunk-based context ranges (fallback path)
for s, e, label in ranges_around(changed_lines, "diff context", nlines):
print(f"HUNK|{s}|{e}|{label}")
# If it is not Python, stop here.
if not path.endswith(".py"):
return
@dataclass(frozen=True)
class DefSpan:
qualname: str
start: int
end: int
kind: str # "func" or "class"
def span_start_with_decorators(node: ast.AST) -> int:
start = getattr(node, "lineno", 1)
decs = getattr(node, "decorator_list", None) or []
dec_lns = [getattr(d, "lineno", None) for d in decs]
dec_lns = [x for x in dec_lns if isinstance(x, int) and x > 0]
if dec_lns:
start = min(start, min(dec_lns))
return int(start)
try:
tree = ast.parse(source, filename=path)
except SyntaxError as e:
print(f"NOTE|Python parse failed (syntax error): {e}")
return
except Exception as e:
print(f"NOTE|Python parse failed: {e}")
return
funcs: List[DefSpan] = []
classes: List[DefSpan] = []
class Extract(ast.NodeVisitor):
def __init__(self) -> None:
self.class_stack: List[str] = []
self.func_stack: List[str] = []
def _qn(self, name: str) -> str:
return ".".join(self.class_stack + self.func_stack + [name])
def visit_ClassDef(self, node: ast.ClassDef) -> None:
qn = ".".join(self.class_stack + [node.name])
start = span_start_with_decorators(node)
end = int(getattr(node, "end_lineno", getattr(node, "lineno", start)))
classes.append(DefSpan(qn, start, end, "class"))
self.class_stack.append(node.name)
try:
self.generic_visit(node)
finally:
self.class_stack.pop()
def _visit_func(self, node: ast.AST, name: str) -> None:
qn = self._qn(name)
start = span_start_with_decorators(node)
end = int(getattr(node, "end_lineno", getattr(node, "lineno", start)))
funcs.append(DefSpan(qn, start, end, "func"))
self.func_stack.append(name)
try:
self.generic_visit(node)
finally:
self.func_stack.pop()
def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
self._visit_func(node, node.name)
def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
self._visit_func(node, node.name)
Extract().visit(tree)
def innermost(spans: List[DefSpan], ln: int) -> Optional[DefSpan]:
cands = [s for s in spans if s.start <= ln <= s.end]
if not cands:
return None
cands.sort(key=lambda s: (s.end - s.start, s.start, s.qualname.count(".")))
return cands[0]
selected_funcs: Dict[str, DefSpan] = {}
nonfunc_lines_by_label: Dict[str, List[int]] = {}
for ln in changed_lines:
f = innermost(funcs, ln)
if f is not None:
selected_funcs[f.qualname] = f
continue
c = innermost(classes, ln)
if c is not None:
label = f"class {c.qualname}"
nonfunc_lines_by_label.setdefault(label, []).append(ln)
else:
nonfunc_lines_by_label.setdefault("module", []).append(ln)
for qn, sp in sorted(selected_funcs.items(), key=lambda kv: (kv[1].start, kv[1].end, kv[0])):
print(f"FUNC|{qn}|{sp.start}|{sp.end}")
for label, lns in nonfunc_lines_by_label.items():
for s, e, _ in ranges_around(sorted(set(lns)), label, nlines):
print(f"NONFUNC|{s}|{e}|{label}")
# ---------------------------------------------------------------------------
# Main dispatch
# ---------------------------------------------------------------------------
command = sys.argv[1]
patch_file = sys.argv[2]
with open(patch_file, "r") as f:
patch_text = f.read()
entries = parse_patch(patch_text)
def resolve_entry(entries, target_path, index_arg=None):
"""Look up a patch entry by index (preferred) or by path (fallback)."""
if index_arg is not None:
try:
idx = int(index_arg)
if 0 <= idx < len(entries):
return entries[idx]
except ValueError:
pass
return find_patch_for_path(entries, target_path)
if command == "list-files":
base_dir = sys.argv[3] if len(sys.argv) > 3 else None
include_binary = sys.argv[4] == "1" if len(sys.argv) > 4 else False
real_base = os.path.realpath(base_dir) if base_dir else None
for i, e in enumerate(entries):
if e.is_binary and not include_binary:
continue
line = f"{i}|{e.status}|{e.old_path}|{e.new_path}"
if real_base is not None:
dp = e.new_path if e.status != "deleted" else e.old_path
if not dp:
continue
abs_p = os.path.realpath(os.path.join(real_base, dp))
if abs_p != real_base and not abs_p.startswith(real_base + os.sep):
continue
line += f"|{abs_p}"
print(line)
elif command == "analyze":
target_path = sys.argv[3]
local_path = sys.argv[4] if len(sys.argv) > 4 else target_path
entry_index = sys.argv[5] if len(sys.argv) > 5 else None
entry = resolve_entry(entries, target_path, entry_index)
if entry is None:
print("NOTE|File not found in patch")
sys.exit(0)
analyze_file_with_patch_text(local_path, entry.raw_text)
elif command == "raw-diff":
target_path = sys.argv[3]
entry_index = sys.argv[4] if len(sys.argv) > 4 else None
entry = resolve_entry(entries, target_path, entry_index)
if entry:
print(entry.raw_text, end="")
else:
print(f"Unknown command: {command}", file=sys.stderr)
sys.exit(2)
PYEOF
}
__gitdiffshow_analyze_file() {
local file="$1"; shift
# Remaining args are passed through to `git diff`
local -a args=("$@")
# Bash heredoc is fine; feed to python for analysis.
# Default: keep stderr quiet so output stays parseable.
# Debug: set GITDIFFSHOW_DEBUG=1 to see Python errors.
local stderr_target="/dev/null"
if [[ -n "${GITDIFFSHOW_DEBUG:-}" ]]; then
stderr_target="/dev/stderr"
fi
python3 - "$file" "${args[@]}" 2>"$stderr_target" <<'PY'
import ast
import os
import re
import subprocess
import sys
import tokenize
from dataclasses import dataclass
from typing import Dict, List, Optional, Tuple
path = sys.argv[1]
git_args = sys.argv[2:]
CTX = int(os.environ.get("GITDIFFSHOW_CONTEXT", "20"))
def run_git_diff() -> str:
cmd = ["git", "diff", "--unified=0", "--no-color"]
cmd += git_args
cmd += ["--", path]
p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
return p.stdout or ""
patch = run_git_diff()
if not patch.strip():
sys.exit(0)
if "Binary files " in patch:
print("NOTE|Binary diff (no text hunks)")
sys.exit(0)
hunk_re = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@", re.M)
changed_lines: List[int] = []
for m in hunk_re.finditer(patch):
new_start = int(m.group(3))
new_count = int(m.group(4) or "1")
if new_count == 0:
changed_lines.append(new_start)
else:
changed_lines.extend(range(new_start, new_start + new_count))
changed_lines = sorted(set(changed_lines))
if not changed_lines:
print("NOTE|No text hunks found")
sys.exit(0)
if not os.path.exists(path):
print("NOTE|File not found in working tree (likely deleted)")
sys.exit(0)
try:
with tokenize.open(path) as f:
source = f.read()
except Exception as e:
print(f"NOTE|Could not read file: {e}")
sys.exit(0)
lines = source.splitlines(True)
nlines = len(lines)
if nlines == 0:
print("NOTE|Empty file")
sys.exit(0)
def clamp_line(n: int) -> int:
if n < 1:
return 1
if n > nlines:
return nlines
return n
changed_lines = [clamp_line(x) for x in changed_lines]
def merge_ranges(ranges: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
if not ranges:
return []
ranges = sorted(ranges)
out: List[List[int]] = [[ranges[0][0], ranges[0][1]]]
for s, e in ranges[1:]:
if s <= out[-1][1] + 1:
out[-1][1] = max(out[-1][1], e)
else:
out.append([s, e])
return [(a, b) for a, b in out]
def ranges_around(lines_: List[int], label: str) -> List[Tuple[int, int, str]]:
rs = []
for ln in lines_:
s = max(1, ln - CTX)
e = min(nlines, ln + CTX)
rs.append((s, e))
merged = merge_ranges([(a, b) for a, b in rs])
return [(a, b, label) for a, b in merged]
# Always emit generic hunk-based context ranges (fallback path)
for s, e, label in ranges_around(changed_lines, "diff context"):
print(f"HUNK|{s}|{e}|{label}")
# If it is not Python, stop here.
if not path.endswith(".py"):
sys.exit(0)
@dataclass(frozen=True)
class DefSpan:
qualname: str
start: int
end: int
kind: str # "func" or "class"
def span_start_with_decorators(node: ast.AST) -> int:
start = getattr(node, "lineno", 1)
decs = getattr(node, "decorator_list", None) or []
dec_lns = [getattr(d, "lineno", None) for d in decs]
dec_lns = [x for x in dec_lns if isinstance(x, int) and x > 0]
if dec_lns:
start = min(start, min(dec_lns))
return int(start)
try:
tree = ast.parse(source, filename=path)
except SyntaxError as e:
print(f"NOTE|Python parse failed (syntax error): {e}")
sys.exit(0)
except Exception as e:
print(f"NOTE|Python parse failed: {e}")
sys.exit(0)
funcs: List[DefSpan] = []
classes: List[DefSpan] = []
class Extract(ast.NodeVisitor):
def __init__(self) -> None:
self.class_stack: List[str] = []
self.func_stack: List[str] = []
def _qn(self, name: str) -> str:
return ".".join(self.class_stack + self.func_stack + [name])
def visit_ClassDef(self, node: ast.ClassDef) -> None:
qn = ".".join(self.class_stack + [node.name])
start = span_start_with_decorators(node)
end = int(getattr(node, "end_lineno", getattr(node, "lineno", start)))
classes.append(DefSpan(qn, start, end, "class"))
self.class_stack.append(node.name)
try:
self.generic_visit(node)
finally:
self.class_stack.pop()
def _visit_func(self, node: ast.AST, name: str) -> None:
qn = self._qn(name)
start = span_start_with_decorators(node)
end = int(getattr(node, "end_lineno", getattr(node, "lineno", start)))
funcs.append(DefSpan(qn, start, end, "func"))
# Always descend so we can map to nested defs too
self.func_stack.append(name)
try:
self.generic_visit(node)
finally:
self.func_stack.pop()
def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
self._visit_func(node, node.name)
def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
self._visit_func(node, node.name)
Extract().visit(tree)
def innermost(spans: List[DefSpan], ln: int) -> Optional[DefSpan]:
cands = [s for s in spans if s.start <= ln <= s.end]
if not cands:
return None
cands.sort(key=lambda s: (s.end - s.start, s.start, s.qualname.count(".")))
return cands[0]
selected_funcs: Dict[str, DefSpan] = {}
nonfunc_lines_by_label: Dict[str, List[int]] = {}
for ln in changed_lines:
f = innermost(funcs, ln)
if f is not None:
selected_funcs[f.qualname] = f
continue
c = innermost(classes, ln)
if c is not None:
label = f"class {c.qualname}"
nonfunc_lines_by_label.setdefault(label, []).append(ln)
else:
nonfunc_lines_by_label.setdefault("module", []).append(ln)
for qn, sp in sorted(selected_funcs.items(), key=lambda kv: (kv[1].start, kv[1].end, kv[0])):
print(f"FUNC|{qn}|{sp.start}|{sp.end}")
for label, lns in nonfunc_lines_by_label.items():
for s, e, _ in ranges_around(sorted(set(lns)), label):
print(f"NONFUNC|{s}|{e}|{label}")
PY
}
gitdiffshow() {
local print_wholefile=0
local show_diff=0
local use_relative=0
local include_binary=0
local color_mode="auto"
local patch_file=""
local -a revspec=()
# Two-pass arg parsing: first pass to find --patch (which consumes next arg)
local -a args_array=("$@")
local i=0
while [[ $i -lt ${#args_array[@]} ]]; do
local a="${args_array[$i]}"
case "$a" in
--patch)
if [[ $((i + 1)) -ge ${#args_array[@]} ]]; then
echo "Error: --patch requires a FILE argument (use - for stdin)" >&2
return 1
fi
patch_file="${args_array[$((i + 1))]}"
i=$((i + 2))
;;
--patch=*)
patch_file="${a#*=}"
i=$((i + 1))
;;
--printwholefile|--wholefile|--whole-file|--all)
print_wholefile=1
i=$((i + 1))
;;
--diff)
show_diff=1
i=$((i + 1))
;;
--binarydiff)
include_binary=1
i=$((i + 1))
;;
--relative)
use_relative=1
i=$((i + 1))
;;
--color)
color_mode="always"
i=$((i + 1))
;;
--color=*)
color_mode="${a#*=}"
if [[ ! "$color_mode" =~ ^(always|never|auto)$ ]]; then
echo "Error: Invalid color mode '$color_mode'. Use always, never, or auto." >&2
return 1
fi
i=$((i + 1))
;;
--no-color|--nocolor|-n)
color_mode="never"
i=$((i + 1))
;;
-h|--help)
cat <<'EOF'
gitdiffshow - Show context for files changed in git diff
USAGE:
gitdiffshow [OPTIONS] [git-diff-revspec...]
gitdiffshow --patch FILE [OPTIONS]
DEFAULT:
- Shows all changed files in the repository (regardless of current directory)
- Python files: print only affected functions/methods (via print_function.sh)
- Other files: print numbered excerpts around changed hunks
FLAGS:
--all Print entire file contents with line numbers (alias)
--printwholefile Same as --all
--diff Print git diff output in addition to the function context
--patch FILE Read diff from a patch file instead of running git diff.
Use - for stdin. Patch paths are resolved against the git
repo root (if in a repo) or the current directory.
Cannot be combined with git diff revision arguments.
--binarydiff Show diff for binary files (default: skip binary files)
--relative Only show files relative to the current directory
--color[=MODE] Color mode: always, auto, never (default: auto). Bare --color implies always.
--no-color, -n Disable ANSI color (best for pasting into AI)
EXAMPLES:
gitdiffshow
gitdiffshow --cached
gitdiffshow HEAD
gitdiffshow main..
gitdiffshow --all
gitdiffshow --relative
gitdiffshow --diff --no-color
gitdiffshow --binarydiff
# Review a GitHub PR patch file:
gitdiffshow --patch pr-123.patch
gitdiffshow --patch pr-123.patch --diff
curl -L https://github.com/OWNER/REPO/pull/123.patch | gitdiffshow --patch -
TIP: Tune excerpt size:
export GITDIFFSHOW_CONTEXT=30
EOF
return 0
;;
*)
revspec+=("$a")
i=$((i + 1))
;;
esac
done
# Mutual exclusion: --patch cannot be combined with revspecs
if [[ -n "$patch_file" && "${#revspec[@]}" -gt 0 ]]; then
echo "Error: --patch cannot be combined with git diff revision arguments" >&2
return 1
fi
# ----- Patch file mode -----
if [[ -n "$patch_file" ]]; then
# If reading from stdin, capture to a temp file
local tmp_patch=""
if [[ "$patch_file" == "-" ]]; then
tmp_patch="$(mktemp)"
cat > "$tmp_patch"
patch_file="$tmp_patch"
elif [[ ! -f "$patch_file" ]]; then
echo "Error: Patch file not found: $patch_file" >&2
return 1
fi
# Determine base directory for resolving patch paths
local base_dir
base_dir="$(git rev-parse --show-toplevel 2>/dev/null || echo "$PWD")"
# Resolve base to canonical form (collapses symlinks) once
local real_base real_cwd=""
real_base="$(cd "$base_dir" && pwd -P)"
if [[ "$use_relative" -eq 1 ]]; then
real_cwd="$(cd "$PWD" && pwd -P)"
fi
# Get file list from patch (Python normalizes paths and filters .. escapes)
local raw_list
if ! raw_list="$(__gitdiffshow_patch_helper list-files "$patch_file" "$real_base" "$include_binary")"; then
echo "Error: failed to read patch file: $patch_file" >&2
[[ -n "$tmp_patch" ]] && rm -f "$tmp_patch"
return 1
fi
local -a filenames=()
local -a patch_paths=() # paths as they appear in the patch
local -a display_labels=() # labels for display (includes status info)
local -a entry_indices=() # original patch entry index (for repeated paths)
local line
while IFS= read -r line; do
[[ -z "$line" ]] && continue
local entry_idx status old_path new_path abs_path
IFS='|' read -r entry_idx status old_path new_path abs_path <<<"$line"
# Determine the display path and patch-lookup path
local display_path="" patch_path=""
case "$status" in
modified|added|copied)
display_path="$new_path"
patch_path="$new_path"
;;
deleted)
display_path="$old_path"
patch_path="$old_path"
;;
renamed)
display_path="$new_path"
patch_path="$new_path"
;;
esac
[[ -z "$display_path" ]] && continue
# abs_path comes pre-normalized from Python (no .. components);
# entries that escape base_dir were already filtered out.
# --relative: filter to files under CWD.
# We check the parent directory exists so deleted files in valid dirs
# are kept, but paths in completely absent trees are filtered out.
if [[ "$use_relative" -eq 1 ]]; then
if [[ "$abs_path" != "$real_cwd"/* ]]; then
continue
fi
if [[ ! -d "$(dirname "$abs_path")" ]]; then
continue
fi
display_path="${abs_path#"$real_cwd"/}"
fi
filenames+=("$abs_path")
patch_paths+=("$patch_path")
entry_indices+=("$entry_idx")
local label="$display_path"
case "$status" in
added) label="$display_path (new file)" ;;
deleted) label="$display_path (deleted)" ;;
renamed) label="$new_path (renamed from $old_path)" ;;
copied) label="$new_path (copied from $old_path)" ;;
esac
display_labels+=("$label")
done <<<"$raw_list"
if [[ "${#filenames[@]}" -eq 0 ]]; then
echo "No files found in patch: $patch_file"
[[ -n "$tmp_patch" ]] && rm -f "$tmp_patch"
return 0
fi
local printfun=""
if printfun="$(__gitdiffshow_find_printfunc)"; then
:
else
printfun=""
fi
export GITDIFFSHOW_COLOR_MODE="$color_mode"
echo "Showing ${#filenames[@]} changed file(s) from patch:"
local idx
for idx in "${!display_labels[@]}"; do
echo " ${display_labels[$idx]}"
done
echo "─────────────────────────────────────────────────"
for idx in "${!filenames[@]}"; do
local f="${filenames[$idx]}"
local pp="${patch_paths[$idx]}"
local dl="${display_labels[$idx]}"
local ei="${entry_indices[$idx]}"
if [[ ! -f "$f" ]]; then
echo
echo "===== $dl ====="
echo
echo " (file not in working tree — showing patch diff)"
echo
__gitdiffshow_patch_helper raw-diff "$patch_file" "$pp" "$ei" || true
echo
continue
fi
echo
echo "===== $dl ====="
echo
if [[ "$show_diff" -eq 1 ]]; then
echo "--- Patch Diff ---"
__gitdiffshow_patch_helper raw-diff "$patch_file" "$pp" "$ei" || true
echo
fi
if [[ "$print_wholefile" -eq 1 ]]; then
if command -v batcat >/dev/null 2>&1; then
env "${GITDIFFSHOW_NO_PAGER_ENV[@]}" batcat --color="$color_mode" --paging=never --style=numbers "$f"
elif command -v bat >/dev/null 2>&1; then
env "${GITDIFFSHOW_NO_PAGER_ENV[@]}" bat --color="$color_mode" --paging=never --style=numbers "$f"
elif [[ "$color_mode" != "never" ]] && command -v pygmentize >/dev/null 2>&1; then
pygmentize -g -f terminal256 -O "style=monokai,linenos=1" "$f" 2>/dev/null || \
pygmentize -g -f terminal256 -O "linenos=1" "$f"
else
nl -ba -n ln "$f"
fi
continue
fi
local raw
raw="$(__gitdiffshow_patch_helper analyze "$patch_file" "$pp" "$f" "$ei" || true)"
local -a funcs=()
local -a nonfunc=()
local -a hunks=()
local -a notes=()
local line
while IFS= read -r line; do
[[ -z "$line" ]] && continue
IFS='|' read -r kind p2 p3 p4 <<<"$line" || true
case "$kind" in
NOTE) notes+=("$p2") ;;