-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcolor
More file actions
executable file
·60 lines (50 loc) · 1.73 KB
/
color
File metadata and controls
executable file
·60 lines (50 loc) · 1.73 KB
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
#!/usr/bin/env -S uv --quiet run --no-project --script --
# https://peps.python.org/pep-0723/
# https://github.com/astral-sh/uv
# /// script
# requires-python = ">=3.14,<4"
# dependencies = [
# ]
# ///
import re, subprocess, sys
from itertools import zip_longest as zip, islice
def shellquotes(*args):
return subprocess.Popen([repr(a) if type(a) != str else a for a in args], stdout=subprocess.PIPE).communicate()[0].decode("UTF-8")
colors = {"": ""}
color_number_mapping = [(0, "black"), (1, "red"), (2, "green"), (3, "yellow"), (4, "blue"), (5, "magenta"), (6, "cyan"), (7, "white")]
for num, name in color_number_mapping:
colors[name] = shellquotes("tput", "setaf", num)
for num, name in color_number_mapping:
colors["bg"+name] = shellquotes("tput", "setab", num)
colors["bold"] = shellquotes("tput", "bold")
colors["reset"] = shellquotes("tput", "sgr0")
class NotAColor(Exception):
pass
def color(c):
if c not in colors:
return ""
return colors[c]
if len(sys.argv) < 3:
print("Need at least two arguments: regex color[,bgcolor]", file=sys.stderr)
sys.exit(1)
if (len(sys.argv)-1) % 2 != 0:
print("Arguments should be paired: regex color[,bgcolor]", file=sys.stderr)
sys.exit(1)
for attr in islice(sys.argv, 2, None, 2):
for c in attr.split(","):
if c not in colors:
if c.startswith("bg"):
colors[c] = shellquotes("tput", "setab", c[2:])
else:
colors[c] = shellquotes("tput", "setaf", c)
rules = []
for p, c in zip(islice(sys.argv, 1, None, 2), islice(sys.argv, 2, None, 2)):
c = "".join([color(x) for x in c.split(",")])
p = re.compile(p)
rules.append((p, c))
for line in sys.stdin.readlines():
for p, c in rules:
def repl(m):
return c + m.group(0) + color("reset")
line = re.sub(p, repl, line)
sys.stdout.write(line)