comparison diff-colorize.py @ 1:44f86539d245

Refactored to allow me to more easily add new prefixes.
author Peter Hosey
date Sun, 10 Aug 2008 23:25:24 -0700
parents 2df4ed64a388
children 9eda9139d627
comparison
equal deleted inserted replaced
0:2df4ed64a388 1:44f86539d245
7 7
8 INDEX_COLOR = 32 8 INDEX_COLOR = 32
9 REMOVED_COLOR = 203 9 REMOVED_COLOR = 203
10 ADDED_COLOR = 2 10 ADDED_COLOR = 2
11 11
12 prefixes_to_invert = ['---', '+++', '-', '+'] 12 class OrderedDict(dict):
13 def __init__(self, input=None):
14 if input is None:
15 self.keys = []
16 super(OrderedDict, self).__init__()
17 elif isinstance(input, dict):
18 self.keys = list(input)
19 super(OrderedDict, self).__init__(input)
20 else:
21 self.keys = [k for k, v in input]
22 super(OrderedDict, self).__init__(input)
23 def __iter__(self):
24 return iter(self.keys)
25 def __setitem__(self, k, v):
26 if k not in self:
27 self.keys.append(k)
28 super(OrderedDict, self).__setitem__(k, v)
29 def __delitem__(self, k):
30 super(OrderedDict, self).__delitem__(k)
31 self.keys.remove(k)
32
33 prefixes = OrderedDict()
34 prefixes['---'] = (
35 COLOR_FORMAT % (REMOVED_COLOR,)
36 + BEGIN_REVERSE_FORMAT
37 + '---'
38 + END_REVERSE_FORMAT
39 )
40 prefixes['+++'] = (
41 COLOR_FORMAT % (ADDED_COLOR,)
42 + BEGIN_REVERSE_FORMAT
43 + '+++'
44 + END_REVERSE_FORMAT
45 )
46 prefixes['-'] = (
47 COLOR_FORMAT % (REMOVED_COLOR,)
48 + BEGIN_REVERSE_FORMAT
49 + '-'
50 + END_REVERSE_FORMAT
51 )
52 prefixes['+'] = (
53 COLOR_FORMAT % (ADDED_COLOR,)
54 + BEGIN_REVERSE_FORMAT
55 + '+'
56 + END_REVERSE_FORMAT
57 )
58 prefixes['Index: '] = COLOR_FORMAT % (INDEX_COLOR,) + 'Index: '
59 prefixes['diff --git '] = COLOR_FORMAT % (INDEX_COLOR,) + 'diff --git '
13 60
14 import sys 61 import sys
15 import fileinput 62 import fileinput
16 63
17 for line in fileinput.input(): 64 for line in fileinput.input():
18 if line.startswith('Index: ') or line.startswith('diff --git '): 65 for prefix_to_test in prefixes:
19 color = INDEX_COLOR 66 if line.startswith(prefix_to_test):
20 elif line.startswith('-'): 67 sys.stdout.write(prefixes[prefix_to_test])
21 color = REMOVED_COLOR 68 line = line[len(prefix_to_test):]
22 elif line.startswith('+'):
23 color = ADDED_COLOR
24 else:
25 color = None
26
27 if color is not None:
28 sys.stdout.write(COLOR_FORMAT % (color,))
29 for prefix in prefixes_to_invert:
30 if line.startswith(prefix):
31 sys.stdout.write(BEGIN_REVERSE_FORMAT)
32 sys.stdout.write(prefix)
33 sys.stdout.write(END_REVERSE_FORMAT)
34 line = line[len(prefix):]
35 break
36 else:
37 sys.stdout.write(RESET_FORMAT)
38 69
39 sys.stdout.write(line) 70 sys.stdout.write(line)
40 71
72 sys.stdout.write(RESET_FORMAT)
73
41 print RESET_FORMAT 74 print RESET_FORMAT