-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcolumns.py
More file actions
executable file
·152 lines (121 loc) · 3.7 KB
/
columns.py
File metadata and controls
executable file
·152 lines (121 loc) · 3.7 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
#!/usr/bin/env uv --quiet run --no-project --script --isolated --refresh --
# /// script
# # Docopt issues SyntaxWarning in Python 3.12
# requires-python = ">=3.11,<3.12"
# dependencies = [
# "docopt >=0.6.2",
# ]
# ///
"""
Usage:
{prog} (-s REGEX)... [--] [FILE]...
{prog} (-r REGEX) [--] [FILE]...
Options:
--separator, -s REGEX The regular expression for the column separator.
--row, -r REGEX The regular expression for the entire row where columns are capture groups. Lines that do not match will be ignored.
"""
import sys, locale, os, re, functools, itertools
import docopt
def main(*, args, prog):
locale.setlocale(locale.LC_ALL, "")
params = docopt.docopt(
__doc__.replace("\t", " " * 4).format(prog=os.path.basename(prog)),
argv=args,
help=True,
version=True,
options_first=False
)
params.pop("--")
files = params.pop("FILE")
separator_patterns = params.pop("--separator")
row_pattern = params.pop("--row")
assert (len(separator_patterns) == 0) != (row_pattern is None), (separator_patterns, row_pattern)
assert not params, params
if row_pattern:
column_splitter = functools.partial(split_columns_by_row_pattern, pattern=row_pattern)
else:
column_splitter = functools.partial(split_columns_by_separator, patterns=separator_patterns)
if files:
text = ""
for f in files:
with open(f, "r") as fo:
text += fo.read()
else:
text = sys.stdin.read()
sys.stdout.write(
align_columns(
text=text,
column_splitter=column_splitter
)
)
def align_columns(*, text, column_splitter):
lines = text.splitlines(keepends=True)
rows = column_splitter(lines=lines)
widths = calculate_columns_widths(rows)
def aligned_columns(rows):
for row in rows:
for width, column in itertools.zip_longest(widths[:len(row)], row, fillvalue=None):
yield (column if ends_with_line_sep(column) else align_text(column, width) + "")
return "".join(aligned_columns(rows))
def calculate_columns_widths(rows):
if not rows:
return []
widths = [[len(strip_ansi_escapes(c)) for c in r] for r in rows]
return list(functools.reduce(
lambda c1, c2: [max(x) for x in itertools.zip_longest(c1, c2, fillvalue=0)],
widths
))
def align_text(text, width):
text_len = len(strip_ansi_escapes(text))
return text + " " * (max(width, text_len) - text_len)
def strip_ansi_escapes(s):
return ANSI_ESCAPE_PATTERN.sub("", s)
# 7-bit C1 ANSI sequences
ANSI_ESCAPE_PATTERN = re.compile(r"""
\x1B # ESC
(?: # 7-bit C1 Fe (except CSI)
[@-Z\\-_]
| # or [ for CSI, followed by a control sequence
\[
[0-?]* # Parameter bytes
[ -/]* # Intermediate bytes
[@-~] # Final byte
)
""", re.VERBOSE)
def split_columns_by_separator(*, lines, patterns):
sep_p = re.compile("|".join(f"(?:{p})" for p in patterns))
rows = []
for line in lines:
columns = []
line_cursor = 0
for sep_m in sep_p.finditer(line):
column_start, column_end = sep_m.span()
columns.append(line[line_cursor:column_start])
columns.append(line[column_start:column_end])
line_cursor = column_end
columns.append(line[line_cursor:])
rows.append(columns)
return rows
def split_columns_by_row_pattern(*, lines, pattern):
p = re.compile(pattern, flags=re.DOTALL)
rows = []
for line in lines:
m = p.fullmatch(line)
if m is None:
raise ValueError("not all lines match the row regular expression")
rows.append(m.groups(default=""))
return rows
def ends_with_line_sep(s):
return s and s != s.splitlines(keepends=False)[-1]
def smain(argv=None):
if argv is None:
argv = sys.argv
try:
return main(
args=argv[1:],
prog=argv[0]
)
except KeyboardInterrupt:
print(file=sys.stderr)
if __name__ == "__main__":
sys.exit(smain())