Skip to content

Commit 4407650

Browse files
committed
Support for unified-like diffs via diff-match-patch
1 parent 38aedb9 commit 4407650

File tree

1 file changed

+43
-19
lines changed

1 file changed

+43
-19
lines changed

tokdiff.py

Lines changed: 43 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@
1616
parser.add_argument('file2', type=argparse.FileType('r'))
1717
parser.add_argument('-o', '--out', type=argparse.FileType('w'),
1818
default=sys.stdout)
19+
group = parser.add_mutually_exclusive_group()
20+
group.add_argument('-v', '--verbose', action='store_true')
21+
group.add_argument('-u', '--unidiff', action='store_true')
1922
data = parser.parse_args()
2023

2124
lexer = pygments.lexers.get_lexer_by_name(data.lexername)
@@ -25,24 +28,45 @@
2528

2629
sm = SequenceMatcher(None, a, b)
2730

28-
for op, a1, a2, b1, b2 in sm.get_opcodes():
29-
if op == 'equal':
30-
for item in a[a1:a2]:
31-
data.out.write(" %s: %s\n" % item)
32-
elif op == 'replace':
33-
data.out.write("~~~\n")
34-
for item in a[a1:a2]:
35-
data.out.write("- %s: %s\n" % item)
36-
for item in b[b1:b2]:
37-
data.out.write("+ %s: %s\n" % item)
38-
data.out.write("~~~\n")
39-
elif op == 'insert':
40-
for item in b[b1:b2]:
41-
data.out.write("+ %s: %s\n" % item)
42-
elif op == 'delete':
43-
for item in a[a1:a2]:
44-
data.out.write("- %s: %s\n" % item)
45-
else:
46-
data.out.write("<<%s>>\n" % op)
31+
if data.verbose or not data.unidiff:
32+
for op, a1, a2, b1, b2 in sm.get_opcodes():
33+
if op == 'equal':
34+
for item in a[a1:a2]:
35+
data.out.write(" %s: %s\n" % item)
36+
elif op == 'replace':
37+
data.out.write("~~~\n")
38+
for item in a[a1:a2]:
39+
data.out.write("- %s: %s\n" % item)
40+
for item in b[b1:b2]:
41+
data.out.write("+ %s: %s\n" % item)
42+
data.out.write("~~~\n")
43+
elif op == 'insert':
44+
for item in b[b1:b2]:
45+
data.out.write("+ %s: %s\n" % item)
46+
elif op == 'delete':
47+
for item in a[a1:a2]:
48+
data.out.write("- %s: %s\n" % item)
49+
else:
50+
data.out.write("<<%s>>\n" % op)
51+
elif data.unidiff:
52+
dmp = diff_match_patch()
53+
diffs = []
54+
for op, a1, a2, b1, b2 in sm.get_opcodes():
55+
if op == 'equal':
56+
diffs.append((dmp.DIFF_EQUAL,
57+
''.join(val for type, val in a[a1:a2])))
58+
elif op == 'replace':
59+
for line in ''.join(val for type, val in b[a1:a2]).splitlines(True):
60+
diffs.append((dmp.DIFF_DELETE, line))
61+
for line in ''.join(val for type, val in b[b1:b2]).splitlines(True):
62+
diffs.append((dmp.DIFF_INSERT, line))
63+
elif op == 'insert':
64+
for line in ''.join(val for type, val in b[b1:b2]).splitlines(True):
65+
diffs.append((dmp.DIFF_INSERT, line))
66+
elif op == 'delete':
67+
for line in ''.join(val for type, val in b[a1:a2]).splitlines(True):
68+
diffs.append((dmp.DIFF_DELETE, line))
69+
patches = dmp.patch_make(diffs)
70+
data.out.write(dmp.patch_toText(patches))
4771

4872
# vim: ai et ts=4 sts=4 sw=4

0 commit comments

Comments
 (0)