Show More
@@ -1,439 +1,440 b'' | |||
|
1 | 1 | # templatefilters.py - common template expansion filters |
|
2 | 2 | # |
|
3 | 3 | # Copyright 2005-2008 Matt Mackall <mpm@selenic.com> |
|
4 | 4 | # |
|
5 | 5 | # This software may be used and distributed according to the terms of the |
|
6 | 6 | # GNU General Public License version 2 or any later version. |
|
7 | 7 | |
|
8 | 8 | from __future__ import absolute_import |
|
9 | 9 | |
|
10 | 10 | import os |
|
11 | 11 | import re |
|
12 | 12 | import time |
|
13 | 13 | |
|
14 | 14 | from .i18n import _ |
|
15 | 15 | from . import ( |
|
16 | 16 | encoding, |
|
17 | 17 | error, |
|
18 | 18 | node, |
|
19 | 19 | pycompat, |
|
20 | 20 | registrar, |
|
21 | 21 | templateutil, |
|
22 | 22 | url, |
|
23 | 23 | util, |
|
24 | 24 | ) |
|
25 | 25 | from .utils import ( |
|
26 | 26 | dateutil, |
|
27 | 27 | stringutil, |
|
28 | 28 | ) |
|
29 | 29 | |
|
30 | 30 | urlerr = util.urlerr |
|
31 | 31 | urlreq = util.urlreq |
|
32 | 32 | |
|
33 | 33 | if pycompat.ispy3: |
|
34 | 34 | long = int |
|
35 | 35 | |
|
36 | 36 | # filters are callables like: |
|
37 | 37 | # fn(obj) |
|
38 | 38 | # with: |
|
39 | 39 | # obj - object to be filtered (text, date, list and so on) |
|
40 | 40 | filters = {} |
|
41 | 41 | |
|
42 | 42 | templatefilter = registrar.templatefilter(filters) |
|
43 | 43 | |
|
44 | 44 | @templatefilter('addbreaks', intype=bytes) |
|
45 | 45 | def addbreaks(text): |
|
46 | 46 | """Any text. Add an XHTML "<br />" tag before the end of |
|
47 | 47 | every line except the last. |
|
48 | 48 | """ |
|
49 | 49 | return text.replace('\n', '<br/>\n') |
|
50 | 50 | |
|
51 | 51 | agescales = [("year", 3600 * 24 * 365, 'Y'), |
|
52 | 52 | ("month", 3600 * 24 * 30, 'M'), |
|
53 | 53 | ("week", 3600 * 24 * 7, 'W'), |
|
54 | 54 | ("day", 3600 * 24, 'd'), |
|
55 | 55 | ("hour", 3600, 'h'), |
|
56 | 56 | ("minute", 60, 'm'), |
|
57 | 57 | ("second", 1, 's')] |
|
58 | 58 | |
|
59 | 59 | @templatefilter('age', intype=templateutil.date) |
|
60 | 60 | def age(date, abbrev=False): |
|
61 | 61 | """Date. Returns a human-readable date/time difference between the |
|
62 | 62 | given date/time and the current date/time. |
|
63 | 63 | """ |
|
64 | 64 | |
|
65 | 65 | def plural(t, c): |
|
66 | 66 | if c == 1: |
|
67 | 67 | return t |
|
68 | 68 | return t + "s" |
|
69 | 69 | def fmt(t, c, a): |
|
70 | 70 | if abbrev: |
|
71 | 71 | return "%d%s" % (c, a) |
|
72 | 72 | return "%d %s" % (c, plural(t, c)) |
|
73 | 73 | |
|
74 | 74 | now = time.time() |
|
75 | 75 | then = date[0] |
|
76 | 76 | future = False |
|
77 | 77 | if then > now: |
|
78 | 78 | future = True |
|
79 | 79 | delta = max(1, int(then - now)) |
|
80 | 80 | if delta > agescales[0][1] * 30: |
|
81 | 81 | return 'in the distant future' |
|
82 | 82 | else: |
|
83 | 83 | delta = max(1, int(now - then)) |
|
84 | 84 | if delta > agescales[0][1] * 2: |
|
85 | 85 | return dateutil.shortdate(date) |
|
86 | 86 | |
|
87 | 87 | for t, s, a in agescales: |
|
88 | 88 | n = delta // s |
|
89 | 89 | if n >= 2 or s == 1: |
|
90 | 90 | if future: |
|
91 | 91 | return '%s from now' % fmt(t, n, a) |
|
92 | 92 | return '%s ago' % fmt(t, n, a) |
|
93 | 93 | |
|
94 | 94 | @templatefilter('basename', intype=bytes) |
|
95 | 95 | def basename(path): |
|
96 | 96 | """Any text. Treats the text as a path, and returns the last |
|
97 | 97 | component of the path after splitting by the path separator. |
|
98 | 98 | For example, "foo/bar/baz" becomes "baz" and "foo/bar//" becomes "". |
|
99 | 99 | """ |
|
100 | 100 | return os.path.basename(path) |
|
101 | 101 | |
|
102 | 102 | @templatefilter('count') |
|
103 | 103 | def count(i): |
|
104 | 104 | """List or text. Returns the length as an integer.""" |
|
105 | 105 | try: |
|
106 | 106 | return len(i) |
|
107 | 107 | except TypeError: |
|
108 | 108 | raise error.ParseError(_('not countable')) |
|
109 | 109 | |
|
110 | 110 | @templatefilter('dirname', intype=bytes) |
|
111 | 111 | def dirname(path): |
|
112 | 112 | """Any text. Treats the text as a path, and strips the last |
|
113 | 113 | component of the path after splitting by the path separator. |
|
114 | 114 | """ |
|
115 | 115 | return os.path.dirname(path) |
|
116 | 116 | |
|
117 | 117 | @templatefilter('domain', intype=bytes) |
|
118 | 118 | def domain(author): |
|
119 | 119 | """Any text. Finds the first string that looks like an email |
|
120 | 120 | address, and extracts just the domain component. Example: ``User |
|
121 | 121 | <user@example.com>`` becomes ``example.com``. |
|
122 | 122 | """ |
|
123 | 123 | f = author.find('@') |
|
124 | 124 | if f == -1: |
|
125 | 125 | return '' |
|
126 | 126 | author = author[f + 1:] |
|
127 | 127 | f = author.find('>') |
|
128 | 128 | if f >= 0: |
|
129 | 129 | author = author[:f] |
|
130 | 130 | return author |
|
131 | 131 | |
|
132 | 132 | @templatefilter('email', intype=bytes) |
|
133 | 133 | def email(text): |
|
134 | 134 | """Any text. Extracts the first string that looks like an email |
|
135 | 135 | address. Example: ``User <user@example.com>`` becomes |
|
136 | 136 | ``user@example.com``. |
|
137 | 137 | """ |
|
138 | 138 | return stringutil.email(text) |
|
139 | 139 | |
|
140 | 140 | @templatefilter('escape', intype=bytes) |
|
141 | 141 | def escape(text): |
|
142 | 142 | """Any text. Replaces the special XML/XHTML characters "&", "<" |
|
143 | 143 | and ">" with XML entities, and filters out NUL characters. |
|
144 | 144 | """ |
|
145 | 145 | return url.escape(text.replace('\0', ''), True) |
|
146 | 146 | |
|
147 | 147 | para_re = None |
|
148 | 148 | space_re = None |
|
149 | 149 | |
|
150 | 150 | def fill(text, width, initindent='', hangindent=''): |
|
151 | 151 | '''fill many paragraphs with optional indentation.''' |
|
152 | 152 | global para_re, space_re |
|
153 | 153 | if para_re is None: |
|
154 | 154 | para_re = re.compile('(\n\n|\n\\s*[-*]\\s*)', re.M) |
|
155 | 155 | space_re = re.compile(br' +') |
|
156 | 156 | |
|
157 | 157 | def findparas(): |
|
158 | 158 | start = 0 |
|
159 | 159 | while True: |
|
160 | 160 | m = para_re.search(text, start) |
|
161 | 161 | if not m: |
|
162 | 162 | uctext = encoding.unifromlocal(text[start:]) |
|
163 | 163 | w = len(uctext) |
|
164 | 164 | while 0 < w and uctext[w - 1].isspace(): |
|
165 | 165 | w -= 1 |
|
166 | 166 | yield (encoding.unitolocal(uctext[:w]), |
|
167 | 167 | encoding.unitolocal(uctext[w:])) |
|
168 | 168 | break |
|
169 | 169 | yield text[start:m.start(0)], m.group(1) |
|
170 | 170 | start = m.end(1) |
|
171 | 171 | |
|
172 | 172 | return "".join([stringutil.wrap(space_re.sub(' ', |
|
173 | 173 | stringutil.wrap(para, width)), |
|
174 | 174 | width, initindent, hangindent) + rest |
|
175 | 175 | for para, rest in findparas()]) |
|
176 | 176 | |
|
177 | 177 | @templatefilter('fill68', intype=bytes) |
|
178 | 178 | def fill68(text): |
|
179 | 179 | """Any text. Wraps the text to fit in 68 columns.""" |
|
180 | 180 | return fill(text, 68) |
|
181 | 181 | |
|
182 | 182 | @templatefilter('fill76', intype=bytes) |
|
183 | 183 | def fill76(text): |
|
184 | 184 | """Any text. Wraps the text to fit in 76 columns.""" |
|
185 | 185 | return fill(text, 76) |
|
186 | 186 | |
|
187 | 187 | @templatefilter('firstline', intype=bytes) |
|
188 | 188 | def firstline(text): |
|
189 | 189 | """Any text. Returns the first line of text.""" |
|
190 | 190 | try: |
|
191 | 191 | return text.splitlines(True)[0].rstrip('\r\n') |
|
192 | 192 | except IndexError: |
|
193 | 193 | return '' |
|
194 | 194 | |
|
195 | 195 | @templatefilter('hex', intype=bytes) |
|
196 | 196 | def hexfilter(text): |
|
197 | 197 | """Any text. Convert a binary Mercurial node identifier into |
|
198 | 198 | its long hexadecimal representation. |
|
199 | 199 | """ |
|
200 | 200 | return node.hex(text) |
|
201 | 201 | |
|
202 | 202 | @templatefilter('hgdate', intype=templateutil.date) |
|
203 | 203 | def hgdate(text): |
|
204 | 204 | """Date. Returns the date as a pair of numbers: "1157407993 |
|
205 | 205 | 25200" (Unix timestamp, timezone offset). |
|
206 | 206 | """ |
|
207 | 207 | return "%d %d" % text |
|
208 | 208 | |
|
209 | 209 | @templatefilter('isodate', intype=templateutil.date) |
|
210 | 210 | def isodate(text): |
|
211 | 211 | """Date. Returns the date in ISO 8601 format: "2009-08-18 13:00 |
|
212 | 212 | +0200". |
|
213 | 213 | """ |
|
214 | 214 | return dateutil.datestr(text, '%Y-%m-%d %H:%M %1%2') |
|
215 | 215 | |
|
216 | 216 | @templatefilter('isodatesec', intype=templateutil.date) |
|
217 | 217 | def isodatesec(text): |
|
218 | 218 | """Date. Returns the date in ISO 8601 format, including |
|
219 | 219 | seconds: "2009-08-18 13:00:13 +0200". See also the rfc3339date |
|
220 | 220 | filter. |
|
221 | 221 | """ |
|
222 | 222 | return dateutil.datestr(text, '%Y-%m-%d %H:%M:%S %1%2') |
|
223 | 223 | |
|
224 | 224 | def indent(text, prefix): |
|
225 | 225 | '''indent each non-empty line of text after first with prefix.''' |
|
226 | 226 | lines = text.splitlines() |
|
227 | 227 | num_lines = len(lines) |
|
228 | 228 | endswithnewline = text[-1:] == '\n' |
|
229 | 229 | def indenter(): |
|
230 | 230 | for i in xrange(num_lines): |
|
231 | 231 | l = lines[i] |
|
232 | 232 | if i and l.strip(): |
|
233 | 233 | yield prefix |
|
234 | 234 | yield l |
|
235 | 235 | if i < num_lines - 1 or endswithnewline: |
|
236 | 236 | yield '\n' |
|
237 | 237 | return "".join(indenter()) |
|
238 | 238 | |
|
239 | 239 | @templatefilter('json') |
|
240 | 240 | def json(obj, paranoid=True): |
|
241 | """Any object. Serializes the object to a JSON formatted text.""" | |
|
241 | 242 | if obj is None: |
|
242 | 243 | return 'null' |
|
243 | 244 | elif obj is False: |
|
244 | 245 | return 'false' |
|
245 | 246 | elif obj is True: |
|
246 | 247 | return 'true' |
|
247 | 248 | elif isinstance(obj, (int, long, float)): |
|
248 | 249 | return pycompat.bytestr(obj) |
|
249 | 250 | elif isinstance(obj, bytes): |
|
250 | 251 | return '"%s"' % encoding.jsonescape(obj, paranoid=paranoid) |
|
251 | 252 | elif isinstance(obj, str): |
|
252 | 253 | # This branch is unreachable on Python 2, because bytes == str |
|
253 | 254 | # and we'll return in the next-earlier block in the elif |
|
254 | 255 | # ladder. On Python 3, this helps us catch bugs before they |
|
255 | 256 | # hurt someone. |
|
256 | 257 | raise error.ProgrammingError( |
|
257 | 258 | 'Mercurial only does output with bytes on Python 3: %r' % obj) |
|
258 | 259 | elif util.safehasattr(obj, 'keys'): |
|
259 | 260 | out = ['"%s": %s' % (encoding.jsonescape(k, paranoid=paranoid), |
|
260 | 261 | json(v, paranoid)) |
|
261 | 262 | for k, v in sorted(obj.iteritems())] |
|
262 | 263 | return '{' + ', '.join(out) + '}' |
|
263 | 264 | elif util.safehasattr(obj, '__iter__'): |
|
264 | 265 | out = [json(i, paranoid) for i in obj] |
|
265 | 266 | return '[' + ', '.join(out) + ']' |
|
266 | 267 | raise error.ProgrammingError('cannot encode %r' % obj) |
|
267 | 268 | |
|
268 | 269 | @templatefilter('lower', intype=bytes) |
|
269 | 270 | def lower(text): |
|
270 | 271 | """Any text. Converts the text to lowercase.""" |
|
271 | 272 | return encoding.lower(text) |
|
272 | 273 | |
|
273 | 274 | @templatefilter('nonempty', intype=bytes) |
|
274 | 275 | def nonempty(text): |
|
275 | 276 | """Any text. Returns '(none)' if the string is empty.""" |
|
276 | 277 | return text or "(none)" |
|
277 | 278 | |
|
278 | 279 | @templatefilter('obfuscate', intype=bytes) |
|
279 | 280 | def obfuscate(text): |
|
280 | 281 | """Any text. Returns the input text rendered as a sequence of |
|
281 | 282 | XML entities. |
|
282 | 283 | """ |
|
283 | 284 | text = unicode(text, pycompat.sysstr(encoding.encoding), r'replace') |
|
284 | 285 | return ''.join(['&#%d;' % ord(c) for c in text]) |
|
285 | 286 | |
|
286 | 287 | @templatefilter('permissions', intype=bytes) |
|
287 | 288 | def permissions(flags): |
|
288 | 289 | if "l" in flags: |
|
289 | 290 | return "lrwxrwxrwx" |
|
290 | 291 | if "x" in flags: |
|
291 | 292 | return "-rwxr-xr-x" |
|
292 | 293 | return "-rw-r--r--" |
|
293 | 294 | |
|
294 | 295 | @templatefilter('person', intype=bytes) |
|
295 | 296 | def person(author): |
|
296 | 297 | """Any text. Returns the name before an email address, |
|
297 | 298 | interpreting it as per RFC 5322. |
|
298 | 299 | """ |
|
299 | 300 | return stringutil.person(author) |
|
300 | 301 | |
|
301 | 302 | @templatefilter('revescape', intype=bytes) |
|
302 | 303 | def revescape(text): |
|
303 | 304 | """Any text. Escapes all "special" characters, except @. |
|
304 | 305 | Forward slashes are escaped twice to prevent web servers from prematurely |
|
305 | 306 | unescaping them. For example, "@foo bar/baz" becomes "@foo%20bar%252Fbaz". |
|
306 | 307 | """ |
|
307 | 308 | return urlreq.quote(text, safe='/@').replace('/', '%252F') |
|
308 | 309 | |
|
309 | 310 | @templatefilter('rfc3339date', intype=templateutil.date) |
|
310 | 311 | def rfc3339date(text): |
|
311 | 312 | """Date. Returns a date using the Internet date format |
|
312 | 313 | specified in RFC 3339: "2009-08-18T13:00:13+02:00". |
|
313 | 314 | """ |
|
314 | 315 | return dateutil.datestr(text, "%Y-%m-%dT%H:%M:%S%1:%2") |
|
315 | 316 | |
|
316 | 317 | @templatefilter('rfc822date', intype=templateutil.date) |
|
317 | 318 | def rfc822date(text): |
|
318 | 319 | """Date. Returns a date using the same format used in email |
|
319 | 320 | headers: "Tue, 18 Aug 2009 13:00:13 +0200". |
|
320 | 321 | """ |
|
321 | 322 | return dateutil.datestr(text, "%a, %d %b %Y %H:%M:%S %1%2") |
|
322 | 323 | |
|
323 | 324 | @templatefilter('short', intype=bytes) |
|
324 | 325 | def short(text): |
|
325 | 326 | """Changeset hash. Returns the short form of a changeset hash, |
|
326 | 327 | i.e. a 12 hexadecimal digit string. |
|
327 | 328 | """ |
|
328 | 329 | return text[:12] |
|
329 | 330 | |
|
330 | 331 | @templatefilter('shortbisect', intype=bytes) |
|
331 | 332 | def shortbisect(label): |
|
332 | 333 | """Any text. Treats `label` as a bisection status, and |
|
333 | 334 | returns a single-character representing the status (G: good, B: bad, |
|
334 | 335 | S: skipped, U: untested, I: ignored). Returns single space if `text` |
|
335 | 336 | is not a valid bisection status. |
|
336 | 337 | """ |
|
337 | 338 | if label: |
|
338 | 339 | return label[0:1].upper() |
|
339 | 340 | return ' ' |
|
340 | 341 | |
|
341 | 342 | @templatefilter('shortdate', intype=templateutil.date) |
|
342 | 343 | def shortdate(text): |
|
343 | 344 | """Date. Returns a date like "2006-09-18".""" |
|
344 | 345 | return dateutil.shortdate(text) |
|
345 | 346 | |
|
346 | 347 | @templatefilter('slashpath', intype=bytes) |
|
347 | 348 | def slashpath(path): |
|
348 | 349 | """Any text. Replaces the native path separator with slash.""" |
|
349 | 350 | return util.pconvert(path) |
|
350 | 351 | |
|
351 | 352 | @templatefilter('splitlines', intype=bytes) |
|
352 | 353 | def splitlines(text): |
|
353 | 354 | """Any text. Split text into a list of lines.""" |
|
354 | 355 | return templateutil.hybridlist(text.splitlines(), name='line') |
|
355 | 356 | |
|
356 | 357 | @templatefilter('stringescape', intype=bytes) |
|
357 | 358 | def stringescape(text): |
|
358 | 359 | return stringutil.escapestr(text) |
|
359 | 360 | |
|
360 | 361 | @templatefilter('stringify', intype=bytes) |
|
361 | 362 | def stringify(thing): |
|
362 | 363 | """Any type. Turns the value into text by converting values into |
|
363 | 364 | text and concatenating them. |
|
364 | 365 | """ |
|
365 | 366 | return thing # coerced by the intype |
|
366 | 367 | |
|
367 | 368 | @templatefilter('stripdir', intype=bytes) |
|
368 | 369 | def stripdir(text): |
|
369 | 370 | """Treat the text as path and strip a directory level, if |
|
370 | 371 | possible. For example, "foo" and "foo/bar" becomes "foo". |
|
371 | 372 | """ |
|
372 | 373 | dir = os.path.dirname(text) |
|
373 | 374 | if dir == "": |
|
374 | 375 | return os.path.basename(text) |
|
375 | 376 | else: |
|
376 | 377 | return dir |
|
377 | 378 | |
|
378 | 379 | @templatefilter('tabindent', intype=bytes) |
|
379 | 380 | def tabindent(text): |
|
380 | 381 | """Any text. Returns the text, with every non-empty line |
|
381 | 382 | except the first starting with a tab character. |
|
382 | 383 | """ |
|
383 | 384 | return indent(text, '\t') |
|
384 | 385 | |
|
385 | 386 | @templatefilter('upper', intype=bytes) |
|
386 | 387 | def upper(text): |
|
387 | 388 | """Any text. Converts the text to uppercase.""" |
|
388 | 389 | return encoding.upper(text) |
|
389 | 390 | |
|
390 | 391 | @templatefilter('urlescape', intype=bytes) |
|
391 | 392 | def urlescape(text): |
|
392 | 393 | """Any text. Escapes all "special" characters. For example, |
|
393 | 394 | "foo bar" becomes "foo%20bar". |
|
394 | 395 | """ |
|
395 | 396 | return urlreq.quote(text) |
|
396 | 397 | |
|
397 | 398 | @templatefilter('user', intype=bytes) |
|
398 | 399 | def userfilter(text): |
|
399 | 400 | """Any text. Returns a short representation of a user name or email |
|
400 | 401 | address.""" |
|
401 | 402 | return stringutil.shortuser(text) |
|
402 | 403 | |
|
403 | 404 | @templatefilter('emailuser', intype=bytes) |
|
404 | 405 | def emailuser(text): |
|
405 | 406 | """Any text. Returns the user portion of an email address.""" |
|
406 | 407 | return stringutil.emailuser(text) |
|
407 | 408 | |
|
408 | 409 | @templatefilter('utf8', intype=bytes) |
|
409 | 410 | def utf8(text): |
|
410 | 411 | """Any text. Converts from the local character encoding to UTF-8.""" |
|
411 | 412 | return encoding.fromlocal(text) |
|
412 | 413 | |
|
413 | 414 | @templatefilter('xmlescape', intype=bytes) |
|
414 | 415 | def xmlescape(text): |
|
415 | 416 | text = (text |
|
416 | 417 | .replace('&', '&') |
|
417 | 418 | .replace('<', '<') |
|
418 | 419 | .replace('>', '>') |
|
419 | 420 | .replace('"', '"') |
|
420 | 421 | .replace("'", ''')) # ' invalid in HTML |
|
421 | 422 | return re.sub('[\x00-\x08\x0B\x0C\x0E-\x1F]', ' ', text) |
|
422 | 423 | |
|
423 | 424 | def websub(text, websubtable): |
|
424 | 425 | """:websub: Any text. Only applies to hgweb. Applies the regular |
|
425 | 426 | expression replacements defined in the websub section. |
|
426 | 427 | """ |
|
427 | 428 | if websubtable: |
|
428 | 429 | for regexp, format in websubtable: |
|
429 | 430 | text = regexp.sub(format, text) |
|
430 | 431 | return text |
|
431 | 432 | |
|
432 | 433 | def loadfilter(ui, extname, registrarobj): |
|
433 | 434 | """Load template filter from specified registrarobj |
|
434 | 435 | """ |
|
435 | 436 | for name, func in registrarobj._table.iteritems(): |
|
436 | 437 | filters[name] = func |
|
437 | 438 | |
|
438 | 439 | # tell hggettext to extract docstrings from these functions: |
|
439 | 440 | i18nfunctions = filters.values() |
General Comments 0
You need to be logged in to leave comments.
Login now