-
Notifications
You must be signed in to change notification settings - Fork 6
/
colorize
executable file
·63 lines (48 loc) · 1.3 KB
/
colorize
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
#!/usr/bin/env python
import sys
import re
from optparse import OptionParser
COLORS = {
'bold': '\033[1m',
'italic': '\033[3m',
'underline': '\033[4m',
'inverse': '\033[7m',
'red': '\033[31m',
'green': '\033[32m',
'yellow': '\033[33m',
'blue': "\033[34m",
'purple': "\033[35m",
'lightblue': "\033[36m",
'white': "\033[37m",
'redbg': '\033[41m',
'greenbg': '\033[42m',
'yellowbg': '\033[43m',
'bluebg': "\033[44m",
'purplebg': "\033[45m",
'lightbluebg': "\033[46m",
'whitebg': "\033[47m",
'end': "\033[0m"
}
parser = OptionParser()
parser.add_option("-o", "--only-colored-lines", dest="only_colored", action="store_true")
parser.usage = """%s <color hash>
For example: colorize '{ "error": "red" }'
"""
options, args = parser.parse_args()
if len(args) != 1:
parser.print_help(sys.stderr)
sys.exit(1)
colors = eval(args[0])
def make_repl(color):
parts = color.split(",")
return ("".join(COLORS[part.strip()] for part in parts) +
r'\g<0>' + COLORS['end'])
pairs = [(re.compile(regex), make_repl(colorspec))
for regex,colorspec in colors.iteritems()]
for line in sys.stdin.xreadlines():
made_sub = 0
for r, repl in pairs:
line,count = re.subn(r, repl, line)
made_sub += count
if not options.only_colored or made_sub > 0:
print line,