2011-09-20 17:20:53 +02:00
|
|
|
#!/usr/bin/python
|
|
|
|
|
|
|
|
import sys, re, difflib, os
|
|
|
|
|
|
|
|
red_color = green_color = end_color = ""
|
2012-01-19 19:54:52 +01:00
|
|
|
if "--color" in sys.argv or os.isatty (sys.stdout.fileno ()):
|
|
|
|
if "--color" in sys.argv:
|
|
|
|
sys.argv.remove ("--color")
|
2011-09-20 17:20:53 +02:00
|
|
|
red_color = '\033[41;37;1m'
|
|
|
|
green_color = '\033[42;37;1m'
|
|
|
|
end_color = '\033[m'
|
|
|
|
|
2012-01-20 20:24:21 +01:00
|
|
|
def fancy_diff_lines (l1, l2):
|
2011-09-20 17:20:53 +02:00
|
|
|
|
2012-01-19 19:54:52 +01:00
|
|
|
ss = [re.sub ('([A-Za-z0-9_]*)([^A-Za-z0-9_]?)', r'\1\n\2\n', l).splitlines (True) for l in (l1, l2)]
|
2011-09-20 17:20:53 +02:00
|
|
|
oo = ["",""]
|
2012-01-19 19:54:52 +01:00
|
|
|
st = [False, False]
|
2011-09-20 17:20:53 +02:00
|
|
|
for l in difflib.Differ().compare (*ss):
|
|
|
|
if l[0] == '?':
|
|
|
|
continue
|
|
|
|
if l[0] == ' ':
|
|
|
|
for i in range(2):
|
|
|
|
if st[i]:
|
|
|
|
oo[i] += end_color
|
2012-01-19 19:54:52 +01:00
|
|
|
st[i] = False
|
2011-09-20 17:20:53 +02:00
|
|
|
oo = [o + l[2:] for o in oo]
|
|
|
|
continue
|
|
|
|
if l[0] == '-':
|
|
|
|
if not st[0]:
|
|
|
|
oo[0] += red_color
|
2012-01-19 19:54:52 +01:00
|
|
|
st[0] = True
|
2011-09-20 17:20:53 +02:00
|
|
|
oo[0] += l[2:]
|
|
|
|
continue
|
|
|
|
if l[0] == '+':
|
|
|
|
if not st[1]:
|
|
|
|
oo[1] += green_color
|
2012-01-19 19:54:52 +01:00
|
|
|
st[1] = True
|
2011-09-20 17:20:53 +02:00
|
|
|
oo[1] += l[2:]
|
|
|
|
for i in range(2):
|
|
|
|
if st[i]:
|
|
|
|
oo[i] += end_color
|
|
|
|
st[i] = 0
|
|
|
|
oo = [o.replace ('\n', '') for o in oo]
|
|
|
|
if oo[0] == oo[1]:
|
2012-01-19 19:54:52 +01:00
|
|
|
return [' ', oo[0], '\n']
|
|
|
|
return ['-', oo[0], '\n', '+', oo[1], '\n']
|
2011-09-20 17:20:53 +02:00
|
|
|
|
2012-01-20 20:24:21 +01:00
|
|
|
def fancy_diff_files (f1, f2):
|
|
|
|
for (l1,l2) in zip (f1, f2):
|
|
|
|
if l1 == l2:
|
|
|
|
sys.stdout.writelines ([" ", l1])
|
|
|
|
continue
|
|
|
|
|
|
|
|
sys.stdout.writelines (fancy_diff_lines (l1, l2))
|
|
|
|
# Print out residues
|
|
|
|
for l in f1:
|
|
|
|
sys.stdout.writelines (["-", red_color, l1, end_color])
|
|
|
|
for l in f1:
|
|
|
|
sys.stdout.writelines (["-", green_color, l1, end_color])
|
|
|
|
|
2011-09-20 17:20:53 +02:00
|
|
|
|
2012-01-19 19:54:52 +01:00
|
|
|
def open_file (f):
|
|
|
|
if f == '-':
|
|
|
|
return sys.stdin
|
|
|
|
return file (f)
|
|
|
|
|
2012-01-20 20:24:21 +01:00
|
|
|
if __name__ == '__main__':
|
2012-01-19 19:54:52 +01:00
|
|
|
|
2012-01-20 20:24:21 +01:00
|
|
|
if len (sys.argv) != 3:
|
|
|
|
print "Usage: %s [--color] FILE1 FILE2" % sys.argv[0]
|
|
|
|
sys.exit (1)
|
2011-09-20 17:20:53 +02:00
|
|
|
|
2012-01-20 20:24:21 +01:00
|
|
|
f1, f2 = (open_file (f) for f in sys.argv[1:3])
|
2011-09-20 17:20:53 +02:00
|
|
|
|
2012-01-20 20:24:21 +01:00
|
|
|
fancy_diff_files (f1, f2)
|