hb-diff 1.7 KB
Newer Older
B
Behdad Esfahbod 已提交
1 2 3 4 5
#!/usr/bin/python

import sys, re, difflib, os

red_color = green_color = end_color = ""
B
Behdad Esfahbod 已提交
6 7 8
if "--color" in sys.argv or os.isatty (sys.stdout.fileno ()):
	if "--color" in sys.argv:
		sys.argv.remove ("--color")
B
Behdad Esfahbod 已提交
9 10 11 12
	red_color = '\033[41;37;1m'
	green_color = '\033[42;37;1m'
	end_color = '\033[m'

B
Minor  
Behdad Esfahbod 已提交
13
def fancy_diff_lines (l1, l2):
B
Behdad Esfahbod 已提交
14

B
Behdad Esfahbod 已提交
15
	ss = [re.sub ('([A-Za-z0-9_]*)([^A-Za-z0-9_]?)', r'\1\n\2\n', l).splitlines (True) for l in (l1, l2)]
B
Behdad Esfahbod 已提交
16
	oo = ["",""]
B
Behdad Esfahbod 已提交
17
	st = [False, False]
B
Behdad Esfahbod 已提交
18 19 20 21 22 23 24
	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
B
Behdad Esfahbod 已提交
25
					st[i] = False
B
Behdad Esfahbod 已提交
26 27 28 29 30
			oo = [o + l[2:] for o in oo]
			continue
		if l[0] == '-':
			if not st[0]:
				oo[0] += red_color
B
Behdad Esfahbod 已提交
31
				st[0] = True
B
Behdad Esfahbod 已提交
32 33 34 35 36
			oo[0] += l[2:]
			continue
		if l[0] == '+':
			if not st[1]:
				oo[1] += green_color
B
Behdad Esfahbod 已提交
37
				st[1] = True
B
Behdad Esfahbod 已提交
38 39 40 41 42 43 44
			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]:
B
Behdad Esfahbod 已提交
45 46
		return [' ', oo[0], '\n']
	return ['-', oo[0], '\n', '+', oo[1], '\n']
B
Behdad Esfahbod 已提交
47

B
Minor  
Behdad Esfahbod 已提交
48 49 50 51 52 53 54 55 56 57 58 59 60
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])

B
Behdad Esfahbod 已提交
61

B
Behdad Esfahbod 已提交
62 63 64 65 66
def open_file (f):
	if f == '-':
		return sys.stdin
	return file (f)

B
Minor  
Behdad Esfahbod 已提交
67
if __name__ == '__main__':
B
Behdad Esfahbod 已提交
68

B
Minor  
Behdad Esfahbod 已提交
69 70 71
	if len (sys.argv) != 3:
		print "Usage: %s [--color] FILE1 FILE2" % sys.argv[0]
		sys.exit (1)
B
Behdad Esfahbod 已提交
72

B
Minor  
Behdad Esfahbod 已提交
73
	f1, f2 = (open_file (f) for f in sys.argv[1:3])
B
Behdad Esfahbod 已提交
74

B
Minor  
Behdad Esfahbod 已提交
75
	fancy_diff_files (f1, f2)