-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiff_tool.py
More file actions
executable file
·499 lines (417 loc) · 15.8 KB
/
diff_tool.py
File metadata and controls
executable file
·499 lines (417 loc) · 15.8 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
#!/usr/bin/env python3
"""File and directory diff tool with colored output."""
import argparse
import os
import sys
import difflib
import stat
# ANSI color codes
RED = "\033[31m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
CYAN = "\033[36m"
BOLD = "\033[1m"
DIM = "\033[2m"
RESET = "\033[0m"
NO_COLOR = os.environ.get("NO_COLOR") is not None
def c(text, color):
"""Wrap text in color codes unless NO_COLOR is set."""
if NO_COLOR or not sys.stdout.isatty():
return text
return f"{color}{text}{RESET}"
def is_binary(filepath):
"""Check if a file is binary by reading first 8192 bytes."""
try:
with open(filepath, "rb") as f:
chunk = f.read(8192)
if b"\x00" in chunk:
return True
return False
except (IOError, OSError):
return False
def read_lines(filepath):
"""Read file lines, handling encoding errors."""
try:
with open(filepath, "r", encoding="utf-8", errors="replace") as f:
return f.readlines()
except (IOError, OSError) as e:
print(f"Error reading {filepath}: {e}", file=sys.stderr)
return None
def normalize_line(line, ignore_whitespace=False, ignore_case=False):
"""Normalize a line based on comparison options."""
if ignore_case:
line = line.lower()
if ignore_whitespace:
line = " ".join(line.split())
return line
def unified_diff(file1, file2, lines1, lines2, context=3):
"""Generate unified diff output."""
diff = difflib.unified_diff(
lines1, lines2,
fromfile=file1, tofile=file2,
lineterm=""
)
output = []
for line in diff:
if line.startswith("---"):
output.append(c(line, BOLD + RED))
elif line.startswith("+++"):
output.append(c(line, BOLD + GREEN))
elif line.startswith("@@"):
output.append(c(line, CYAN))
elif line.startswith("-"):
output.append(c(line, RED))
elif line.startswith("+"):
output.append(c(line, GREEN))
else:
output.append(line)
return output
def side_by_side(lines1, lines2, width=80):
"""Generate side-by-side diff output."""
half = (width - 3) // 2
output = []
matcher = difflib.SequenceMatcher(None, lines1, lines2)
for tag, i1, i2, j1, j2 in matcher.get_opcodes():
if tag == "equal":
for i in range(i1, i2):
left = lines1[i].rstrip()[:half].ljust(half)
right = lines2[i - i1 + j1].rstrip()[:half]
output.append(f"{left} | {right}")
elif tag == "replace":
max_len = max(i2 - i1, j2 - j1)
for k in range(max_len):
left = lines1[i1 + k].rstrip()[:half].ljust(half) if i1 + k < i2 else " " * half
right = lines2[j1 + k].rstrip()[:half] if j1 + k < j2 else ""
lc = RED if i1 + k < i2 else ""
rc = GREEN if j1 + k < j2 else ""
left_s = c(left, lc) if lc else left
right_s = c(right, rc) if rc else right
output.append(f"{left_s} {'|' if not lc and not rc else c('!', YELLOW)} {right_s}")
elif tag == "delete":
for i in range(i1, i2):
left = lines1[i].rstrip()[:half].ljust(half)
output.append(f"{c(left, RED)} {c('<', YELLOW)} ")
elif tag == "insert":
for j in range(j1, j2):
right = lines2[j].rstrip()[:half]
output.append(f"{' ' * half} {c('>', YELLOW)} {c(right, GREEN)}")
return output
def word_diff(lines1, lines2):
"""Generate word-level diff output."""
text1 = "".join(lines1)
text2 = "".join(lines2)
words1 = text1.split()
words2 = text2.split()
matcher = difflib.SequenceMatcher(None, words1, words2)
output_parts = []
for tag, i1, i2, j1, j2 in matcher.get_opcodes():
if tag == "equal":
output_parts.append(" ".join(words1[i1:i2]))
elif tag == "replace":
output_parts.append(c("[-" + " ".join(words1[i1:i2]) + "-]", RED))
output_parts.append(c("{+" + " ".join(words2[j1:j2]) + "+}", GREEN))
elif tag == "delete":
output_parts.append(c("[-" + " ".join(words1[i1:i2]) + "-]", RED))
elif tag == "insert":
output_parts.append(c("{+" + " ".join(words2[j1:j2]) + "+}", GREEN))
return [" ".join(output_parts)]
def diff_stats(lines1, lines2):
"""Calculate diff statistics."""
matcher = difflib.SequenceMatcher(None, lines1, lines2)
added = removed = changed = 0
for tag, i1, i2, j1, j2 in matcher.get_opcodes():
if tag == "replace":
changed += max(i2 - i1, j2 - j1)
elif tag == "delete":
removed += i2 - i1
elif tag == "insert":
added += j2 - j1
return {"added": added, "removed": removed, "changed": changed}
def diff_files(file1, file2, mode="unified", ignore_whitespace=False,
ignore_case=False, width=120):
"""Compare two files and return diff output."""
if not os.path.isfile(file1):
print(f"Error: {file1} is not a file", file=sys.stderr)
return 1
if not os.path.isfile(file2):
print(f"Error: {file2} is not a file", file=sys.stderr)
return 1
if is_binary(file1) or is_binary(file2):
s1 = os.path.getsize(file1)
s2 = os.path.getsize(file2)
if s1 == s2:
with open(file1, "rb") as f1, open(file2, "rb") as f2:
if f1.read() == f2.read():
print(f"Binary files {file1} and {file2} are identical")
return 0
print(f"Binary files {file1} ({s1} bytes) and {file2} ({s2} bytes) differ")
return 1
lines1 = read_lines(file1)
lines2 = read_lines(file2)
if lines1 is None or lines2 is None:
return 1
if ignore_whitespace or ignore_case:
cmp1 = [normalize_line(l, ignore_whitespace, ignore_case) for l in lines1]
cmp2 = [normalize_line(l, ignore_whitespace, ignore_case) for l in lines2]
else:
cmp1, cmp2 = lines1, lines2
if cmp1 == cmp2:
print(f"Files {file1} and {file2} are identical")
return 0
if mode == "unified":
output = unified_diff(file1, file2, lines1, lines2)
elif mode == "side":
output = side_by_side(lines1, lines2, width=width)
elif mode == "word":
output = word_diff(lines1, lines2)
else:
output = unified_diff(file1, file2, lines1, lines2)
for line in output:
print(line.rstrip("\n"))
stats = diff_stats(cmp1, cmp2)
print(f"\n{c('---', DIM)}")
print(f"{c(f'+{stats[\"added\"]} added', GREEN)}, "
f"{c(f'-{stats[\"removed\"]} removed', RED)}, "
f"{c(f'~{stats[\"changed\"]} changed', YELLOW)}")
return 1
def diff_dirs(dir1, dir2):
"""Compare two directories and list differences."""
if not os.path.isdir(dir1):
print(f"Error: {dir1} is not a directory", file=sys.stderr)
return 1
if not os.path.isdir(dir2):
print(f"Error: {dir2} is not a directory", file=sys.stderr)
return 1
files1 = set()
files2 = set()
for root, dirs, files in os.walk(dir1):
for f in files:
rel = os.path.relpath(os.path.join(root, f), dir1)
files1.add(rel)
for root, dirs, files in os.walk(dir2):
for f in files:
rel = os.path.relpath(os.path.join(root, f), dir2)
files2.add(rel)
only1 = sorted(files1 - files2)
only2 = sorted(files2 - files1)
common = sorted(files1 & files2)
changed = []
identical = []
for f in common:
p1 = os.path.join(dir1, f)
p2 = os.path.join(dir2, f)
if is_binary(p1) or is_binary(p2):
s1 = os.path.getsize(p1)
s2 = os.path.getsize(p2)
if s1 != s2:
changed.append(f)
else:
with open(p1, "rb") as a, open(p2, "rb") as b:
if a.read() != b.read():
changed.append(f)
else:
identical.append(f)
else:
l1 = read_lines(p1)
l2 = read_lines(p2)
if l1 != l2:
changed.append(f)
else:
identical.append(f)
has_diff = False
if only1:
has_diff = True
print(c(f"\nOnly in {dir1}:", BOLD + RED))
for f in only1:
print(c(f" - {f}", RED))
if only2:
has_diff = True
print(c(f"\nOnly in {dir2}:", BOLD + GREEN))
for f in only2:
print(c(f" + {f}", GREEN))
if changed:
has_diff = True
print(c(f"\nChanged:", BOLD + YELLOW))
for f in changed:
print(c(f" ~ {f}", YELLOW))
print(f"\n{c('---', DIM)}")
print(f" {len(only1)} removed, {len(only2)} added, "
f"{len(changed)} changed, {len(identical)} identical")
return 1 if has_diff else 0
def create_patch(file1, file2, output_file):
"""Create a unified diff patch file."""
if is_binary(file1) or is_binary(file2):
print("Error: Cannot create patch for binary files", file=sys.stderr)
return 1
lines1 = read_lines(file1) or []
lines2 = read_lines(file2) or []
diff = difflib.unified_diff(
lines1, lines2,
fromfile=file1, tofile=file2
)
patch_content = "".join(diff)
if not patch_content:
print("Files are identical, no patch created")
return 0
with open(output_file, "w", encoding="utf-8") as f:
f.write(patch_content)
print(f"Patch written to {output_file}")
return 0
def apply_patch(patch_file, target=None, reverse=False):
"""Apply a unified diff patch file."""
try:
with open(patch_file, "r", encoding="utf-8") as f:
patch_lines = f.readlines()
except (IOError, OSError) as e:
print(f"Error reading patch: {e}", file=sys.stderr)
return 1
current_file = target
orig_lines = []
hunks = []
current_hunk = None
for line in patch_lines:
if line.startswith("--- "):
if reverse:
pass
else:
fname = line[4:].strip().split("\t")[0]
if target is None:
current_file = fname
elif line.startswith("+++ "):
if reverse:
fname = line[4:].strip().split("\t")[0]
if target is None:
current_file = fname
elif line.startswith("@@ "):
if current_hunk:
hunks.append(current_hunk)
current_hunk = {"removes": [], "adds": [], "context": []}
elif current_hunk is not None:
if line.startswith("-"):
current_hunk["removes"].append(line[1:])
elif line.startswith("+"):
current_hunk["adds"].append(line[1:])
else:
current_hunk["context"].append(line[1:] if line.startswith(" ") else line)
if current_hunk:
hunks.append(current_hunk)
if not current_file:
print("Error: Could not determine target file from patch", file=sys.stderr)
return 1
if not os.path.isfile(current_file):
print(f"Error: Target file not found: {current_file}", file=sys.stderr)
return 1
# Simple approach: use difflib to apply
orig = read_lines(current_file) or []
# Re-parse as proper unified diff and apply
with open(patch_file, "r", encoding="utf-8") as f:
patch_text = f.read()
# Extract the expected result from the patch
result = list(orig)
offset = 0
for line in patch_lines:
pass # simplified
# Use a more robust approach with difflib
try:
patched = []
i = 0
patch_idx = 0
removes = []
adds = []
for line in patch_lines:
if line.startswith("--- ") or line.startswith("+++ "):
continue
if line.startswith("@@ "):
import re
m = re.match(r"@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@", line)
if m:
start = int(m.group(1)) - 1
# Output lines before this hunk
while i < start:
if i < len(orig):
patched.append(orig[i])
i += 1
continue
if line.startswith("-"):
if reverse:
patched.append(line[1:])
i += 1 # skip this line in original
elif line.startswith("+"):
if not reverse:
patched.append(line[1:])
else:
i += 1
elif line.startswith(" "):
if i < len(orig):
patched.append(orig[i])
i += 1
# Append remaining lines
while i < len(orig):
patched.append(orig[i])
i += 1
with open(current_file, "w", encoding="utf-8") as f:
f.writelines(patched)
print(f"Patch applied to {current_file}")
return 0
except Exception as e:
print(f"Error applying patch: {e}", file=sys.stderr)
return 1
def main():
parser = argparse.ArgumentParser(
description="File and directory diff tool with colored output.",
epilog="Examples:\n"
" diff_tool.py file1.txt file2.txt\n"
" diff_tool.py -s dir1/ dir2/\n"
" diff_tool.py --side-by-side file1 file2\n"
" diff_tool.py --word file1.txt file2.txt\n"
" diff_tool.py --patch out.patch file1 file2\n"
" diff_tool.py --apply out.patch\n",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument("path1", nargs="?", help="First file or directory")
parser.add_argument("path2", nargs="?", help="Second file or directory")
parser.add_argument("--side-by-side", "-y", action="store_true",
help="Side-by-side view")
parser.add_argument("--word", "-w", action="store_true",
help="Word-level diff")
parser.add_argument("--ignore-whitespace", "-b", action="store_true",
help="Ignore whitespace differences")
parser.add_argument("--ignore-case", "-i", action="store_true",
help="Case-insensitive comparison")
parser.add_argument("--width", "-W", type=int, default=120,
help="Terminal width for side-by-side (default: 120)")
parser.add_argument("--patch", "-p", metavar="FILE",
help="Output diff as patch file")
parser.add_argument("--apply", "-a", metavar="PATCH",
help="Apply a patch file")
parser.add_argument("--reverse", "-R", action="store_true",
help="Reverse patch when applying")
parser.add_argument("--version", action="version",
version="diff-tool 1.0.0")
args = parser.parse_args()
if args.apply:
target = args.path1 if args.path1 else None
sys.exit(apply_patch(args.apply, target=target, reverse=args.reverse))
if not args.path1 or not args.path2:
parser.error("Two paths are required for comparison")
# Directory diff
if os.path.isdir(args.path1) and os.path.isdir(args.path2):
sys.exit(diff_dirs(args.path1, args.path2))
# Create patch
if args.patch:
sys.exit(create_patch(args.path1, args.path2, args.patch))
# File diff
mode = "unified"
if args.side_by_side:
mode = "side"
elif args.word:
mode = "word"
sys.exit(diff_files(
args.path1, args.path2,
mode=mode,
ignore_whitespace=args.ignore_whitespace,
ignore_case=args.ignore_case,
width=args.width,
))
if __name__ == "__main__":
main()