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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
"""
Formatting: escaping (esc_param, esc_path_info, esc_url, esc_attr, esc_html, esc_path, sanitize),
quot_cec, quot_upr, unquote, untabify, to_utf8, chop_str, chop_and_escape_str, age_class, age_string.
Ported from gitweb/gitweb.perl.
"""
from __future__ import annotations
import html
import re
from urllib.parse import quote, quote_plus
# Fallback encoding when bytes are not valid UTF-8 (gitweb: $fallback_encoding)
FALLBACK_ENCODING = "latin1"
# Control character escape codes (CEC). Port of quot_cec.
_CEC_MAP = {
"\t": r"\t",
"\n": r"\n",
"\r": r"\r",
"\f": r"\f",
"\b": r"\b",
"\a": r"\a",
"\x1b": r"\e",
"\v": r"\v",
"\0": r"\0",
}
def to_utf8(s: str | bytes | None) -> str | None:
"""Decode to UTF-8 string; use fallback encoding if not valid UTF-8. Port of to_utf8."""
if s is None:
return None
if isinstance(s, str):
return s
try:
return s.decode("utf-8")
except UnicodeDecodeError:
return s.decode(FALLBACK_ENCODING, errors="replace")
def esc_param(s: str | None) -> str | None:
"""URL-encode for query param; keep / and space as +. Port of esc_param."""
if s is None:
return None
return quote_plus(s, safe="") # gitweb keeps -_.~()/@: and space→+
def esc_path_info(s: str | None) -> str | None:
"""Path segment encoding; ? must be escaped. Port of esc_path_info."""
if s is None:
return None
# Safe: A-Za-z0-9\-_.~();/;:@&= +
return quote(s, safe="-_.~();/:@&= ")
def esc_url(s: str | None) -> str | None:
"""URL encoding for href. Port of esc_url (same idea as esc_param)."""
if s is None:
return None
return quote(s, safe="-_.~()/:@!")
def esc_attr(s: str | None) -> str | None:
"""Escape for HTML attribute. Port of esc_attr."""
if s is None:
return None
return html.escape(s, quote=True)
def esc_html(s: str | None) -> str | None:
"""Escape for HTML body. Port of esc_html."""
if s is None:
return None
return html.escape(s, quote=False)
def quot_cec(char: str, nohtml: bool = False) -> str:
"""Printable representation of control char (CEC). Port of quot_cec."""
out = _CEC_MAP.get(char, f"\\{ord(char):02x}")
if nohtml:
return out
return f'<span class="cntrl">{out}</span>'
def quot_upr(char: str, nohtml: bool = False) -> str:
"""Unicode control pictures. Port of quot_upr."""
code = 0x2400 + ord(char)
out = f"&#{code};"
if nohtml:
return out
return f'<span class="cntrl">{out}</span>'
def esc_path(s: str | None, nbsp: bool = False) -> str | None:
"""UTF-8, HTML-escape, then control chars to quot_cec. Port of esc_path."""
if s is None:
return None
s = to_utf8(s) or s
s = html.escape(s, quote=False)
if nbsp:
s = s.replace(" ", " ")
result = []
for c in s:
if ord(c) < 32 or ord(c) == 127:
result.append(quot_cec(c))
else:
result.append(c)
return "".join(result)
def sanitize(s: str | None) -> str | None:
"""XHTML-safe: control chars to CEC except tab/lf/cr. Port of sanitize."""
if s is None:
return None
s = to_utf8(s) or s
result = []
for c in s:
if c in "\t\n\r":
result.append(c)
elif ord(c) < 32 or ord(c) == 127:
result.append(quot_cec(c, nohtml=True))
else:
result.append(c)
return "".join(result)
def unquote(s: str | None) -> str:
"""Unescape git-style quoted filenames (C and octal). Port of unquote."""
if s is None:
return ""
def unq(seq: str) -> str:
es = {
"t": "\t",
"n": "\n",
"r": "\r",
"f": "\f",
"b": "\b",
"a": "\a",
"e": "\x1b",
"v": "\v",
}
if re.match(r"^[0-7]{1,3}$", seq):
return chr(int(seq, 8))
return es.get(seq, seq)
if len(s) >= 2 and s[0] == '"' and s[-1] == '"':
s = s[1:-1]
s = re.sub(r"\\([^0-7]|[0-7]{1,3})", lambda m: unq(m.group(1)), s)
return s
def untabify(line: str, tabwidth: int = 8) -> str:
"""Expand tabs to spaces. Port of untabify."""
result = []
col = 0
for c in line:
if c == "\t":
n = tabwidth - (col % tabwidth)
result.append(" " * n)
col += n
else:
result.append(c)
col += 1
return "".join(result)
def chop_str(
s: str,
length: int,
add_len: int = 10,
where: str = "right",
) -> str:
"""Chop on word boundary between length and length+add_len. Port of chop_str."""
s = to_utf8(s) or ""
if where == "center":
if length + 5 >= len(s):
return s
half = length // 2
endre = re.compile(rf".{{{half}}}\w{{0,{add_len}}}", re.DOTALL)
begre = re.compile(rf"\w{{0,{add_len}}}.{{{half}}}$", re.DOTALL)
m1 = re.match(rf"^(.{{{half}}}\w{{0,{add_len}}})(.*)$", s, re.DOTALL)
if not m1:
return s[: length // 2] + " ... " + s[-(length // 2) :]
left, rest = m1.group(1), m1.group(2)
m2 = re.match(rf"^(.*?)(\w{{0,{add_len}}}.{{{half}}})$", rest, re.DOTALL)
if not m2:
return left + " ... " + rest[-half:]
mid, right = m2.group(1), m2.group(2)
if len(mid) > 5:
mid = " ... "
return left + mid + right
if length + 4 >= len(s):
return s
if where == "left":
begre = re.compile(rf"\w{{0,{add_len}}}.{{{length}}}$")
m = begre.search(s)
if m:
body = m.group(0)
lead = s[: m.start()]
if len(lead) > 4:
lead = " ..."
return lead + body
return s
# right
endre = re.compile(rf".{{{length}}}\w{{0,{add_len}}}")
m = endre.match(s)
if m:
body = m.group(0)
tail = s[m.end() :]
if len(tail) > 4:
tail = "... "
return body + tail
return s
def chop_and_escape_str(
s: str,
length: int,
add_len: int = 10,
where: str = "right",
) -> str:
"""Chop then HTML-escape; wrap in span with title if chopped. Port of chop_and_escape_str."""
chopped = chop_str(s, length, add_len, where)
s = to_utf8(s) or s
if chopped == s:
return esc_html(chopped) or ""
title = esc_attr(s.replace("\n", " ").replace("\r", "?"))
escaped = esc_html(chopped) or ""
return f'<span title="{title}">{escaped}</span>'
def age_class(age_seconds: float | None) -> str:
"""CSS class for age. Port of age_class."""
if age_seconds is None:
return "noage"
if age_seconds < 2 * 3600:
return "age0"
if age_seconds < 2 * 86400:
return "age1"
return "age2"
def age_string(age_seconds: float) -> str:
"""Human-readable age. Port of age_string."""
if age_seconds > 2 * 365 * 86400:
return f"{int(age_seconds / 86400 / 365)} years ago"
if age_seconds > 2 * (365 / 12) * 86400:
return f"{int(age_seconds / 86400 / (365 / 12))} months ago"
if age_seconds > 2 * 7 * 86400:
return f"{int(age_seconds / 86400 / 7)} weeks ago"
if age_seconds > 2 * 86400:
return f"{int(age_seconds / 86400)} days ago"
if age_seconds > 2 * 3600:
return f"{int(age_seconds / 3600)} hours ago"
if age_seconds > 2 * 60:
return f"{int(age_seconds / 60)} min ago"
if age_seconds > 2:
return f"{int(age_seconds)} sec ago"
return "right now"