Show More
@@ -1,190 +1,199 | |||
|
1 | 1 | # template-filters.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 |
|
6 | 6 | # of the GNU General Public License, incorporated herein by reference. |
|
7 | 7 | |
|
8 | 8 | import cgi, re, os, time, urllib, textwrap |
|
9 | 9 | import util, templater, encoding |
|
10 | 10 | |
|
11 | 11 | agescales = [("second", 1), |
|
12 | 12 | ("minute", 60), |
|
13 | 13 | ("hour", 3600), |
|
14 | 14 | ("day", 3600 * 24), |
|
15 | 15 | ("week", 3600 * 24 * 7), |
|
16 | 16 | ("month", 3600 * 24 * 30), |
|
17 | 17 | ("year", 3600 * 24 * 365)] |
|
18 | 18 | |
|
19 | 19 | agescales.reverse() |
|
20 | 20 | |
|
21 | 21 | def age(date): |
|
22 | 22 | '''turn a (timestamp, tzoff) tuple into an age string.''' |
|
23 | 23 | |
|
24 | 24 | def plural(t, c): |
|
25 | 25 | if c == 1: |
|
26 | 26 | return t |
|
27 | 27 | return t + "s" |
|
28 | 28 | def fmt(t, c): |
|
29 | 29 | return "%d %s" % (c, plural(t, c)) |
|
30 | 30 | |
|
31 | 31 | now = time.time() |
|
32 | 32 | then = date[0] |
|
33 | 33 | if then > now: |
|
34 | 34 | return 'in the future' |
|
35 | 35 | |
|
36 | 36 | delta = max(1, int(now - then)) |
|
37 | 37 | for t, s in agescales: |
|
38 | 38 | n = delta / s |
|
39 | 39 | if n >= 2 or s == 1: |
|
40 | 40 | return fmt(t, n) |
|
41 | 41 | |
|
42 | 42 | para_re = None |
|
43 | 43 | space_re = None |
|
44 | 44 | |
|
45 | 45 | def fill(text, width): |
|
46 | 46 | '''fill many paragraphs.''' |
|
47 | 47 | global para_re, space_re |
|
48 | 48 | if para_re is None: |
|
49 | 49 | para_re = re.compile('(\n\n|\n\\s*[-*]\\s*)', re.M) |
|
50 | 50 | space_re = re.compile(r' +') |
|
51 | 51 | |
|
52 | 52 | def findparas(): |
|
53 | 53 | start = 0 |
|
54 | 54 | while True: |
|
55 | 55 | m = para_re.search(text, start) |
|
56 | 56 | if not m: |
|
57 | 57 | w = len(text) |
|
58 | 58 | while w > start and text[w-1].isspace(): w -= 1 |
|
59 | 59 | yield text[start:w], text[w:] |
|
60 | 60 | break |
|
61 | 61 | yield text[start:m.start(0)], m.group(1) |
|
62 | 62 | start = m.end(1) |
|
63 | 63 | |
|
64 | 64 | return "".join([space_re.sub(' ', textwrap.fill(para, width)) + rest |
|
65 | 65 | for para, rest in findparas()]) |
|
66 | 66 | |
|
67 | 67 | def firstline(text): |
|
68 | 68 | '''return the first line of text''' |
|
69 | 69 | try: |
|
70 | 70 | return text.splitlines(1)[0].rstrip('\r\n') |
|
71 | 71 | except IndexError: |
|
72 | 72 | return '' |
|
73 | 73 | |
|
74 | 74 | def nl2br(text): |
|
75 | 75 | '''replace raw newlines with xhtml line breaks.''' |
|
76 | 76 | return text.replace('\n', '<br/>\n') |
|
77 | 77 | |
|
78 | 78 | def obfuscate(text): |
|
79 | 79 | text = unicode(text, encoding.encoding, 'replace') |
|
80 | 80 | return ''.join(['&#%d;' % ord(c) for c in text]) |
|
81 | 81 | |
|
82 | 82 | def domain(author): |
|
83 | 83 | '''get domain of author, or empty string if none.''' |
|
84 | 84 | f = author.find('@') |
|
85 | 85 | if f == -1: return '' |
|
86 | 86 | author = author[f+1:] |
|
87 | 87 | f = author.find('>') |
|
88 | 88 | if f >= 0: author = author[:f] |
|
89 | 89 | return author |
|
90 | 90 | |
|
91 | 91 | def person(author): |
|
92 | 92 | '''get name of author, or else username.''' |
|
93 | 93 | f = author.find('<') |
|
94 | 94 | if f == -1: return util.shortuser(author) |
|
95 | 95 | return author[:f].rstrip() |
|
96 | 96 | |
|
97 | 97 | def indent(text, prefix): |
|
98 | 98 | '''indent each non-empty line of text after first with prefix.''' |
|
99 | 99 | lines = text.splitlines() |
|
100 | 100 | num_lines = len(lines) |
|
101 | 101 | def indenter(): |
|
102 | 102 | for i in xrange(num_lines): |
|
103 | 103 | l = lines[i] |
|
104 | 104 | if i and l.strip(): |
|
105 | 105 | yield prefix |
|
106 | 106 | yield l |
|
107 | 107 | if i < num_lines - 1 or text.endswith('\n'): |
|
108 | 108 | yield '\n' |
|
109 | 109 | return "".join(indenter()) |
|
110 | 110 | |
|
111 | 111 | def permissions(flags): |
|
112 | 112 | if "l" in flags: |
|
113 | 113 | return "lrwxrwxrwx" |
|
114 | 114 | if "x" in flags: |
|
115 | 115 | return "-rwxr-xr-x" |
|
116 | 116 | return "-rw-r--r--" |
|
117 | 117 | |
|
118 | 118 | def xmlescape(text): |
|
119 | 119 | text = (text |
|
120 | 120 | .replace('&', '&') |
|
121 | 121 | .replace('<', '<') |
|
122 | 122 | .replace('>', '>') |
|
123 | 123 | .replace('"', '"') |
|
124 | 124 | .replace("'", ''')) # ' invalid in HTML |
|
125 | 125 | return re.sub('[\x00-\x08\x0B\x0C\x0E-\x1F]', ' ', text) |
|
126 | 126 | |
|
127 | 127 | _escapes = [ |
|
128 | 128 | ('\\', '\\\\'), ('"', '\\"'), ('\t', '\\t'), ('\n', '\\n'), |
|
129 | 129 | ('\r', '\\r'), ('\f', '\\f'), ('\b', '\\b'), |
|
130 | 130 | ] |
|
131 | 131 | |
|
132 | 132 | def jsonescape(s): |
|
133 | 133 | for k, v in _escapes: |
|
134 | 134 | s = s.replace(k, v) |
|
135 | 135 | return s |
|
136 | 136 | |
|
137 | 137 | def json(obj): |
|
138 | 138 | if obj is None or obj is False or obj is True: |
|
139 | 139 | return {None: 'null', False: 'false', True: 'true'}[obj] |
|
140 | 140 | elif isinstance(obj, int) or isinstance(obj, float): |
|
141 | 141 | return str(obj) |
|
142 | 142 | elif isinstance(obj, str): |
|
143 | 143 | return '"%s"' % jsonescape(obj) |
|
144 | 144 | elif isinstance(obj, unicode): |
|
145 | 145 | return json(obj.encode('utf-8')) |
|
146 | 146 | elif hasattr(obj, 'keys'): |
|
147 | 147 | out = [] |
|
148 | 148 | for k, v in obj.iteritems(): |
|
149 | 149 | s = '%s: %s' % (json(k), json(v)) |
|
150 | 150 | out.append(s) |
|
151 | 151 | return '{' + ', '.join(out) + '}' |
|
152 | 152 | elif hasattr(obj, '__iter__'): |
|
153 | 153 | out = [] |
|
154 | 154 | for i in obj: |
|
155 | 155 | out.append(json(i)) |
|
156 | 156 | return '[' + ', '.join(out) + ']' |
|
157 | 157 | else: |
|
158 | 158 | raise TypeError('cannot encode type %s' % obj.__class__.__name__) |
|
159 | 159 | |
|
160 | def stripdir(text): | |
|
161 | '''Treat the text as path and strip a directory level, if possible.''' | |
|
162 | dir = os.path.dirname(text) | |
|
163 | if dir == "": | |
|
164 | return os.path.basename(text) | |
|
165 | else: | |
|
166 | return dir | |
|
167 | ||
|
160 | 168 | filters = { |
|
161 | 169 | "addbreaks": nl2br, |
|
162 | 170 | "basename": os.path.basename, |
|
171 | "stripdir": stripdir, | |
|
163 | 172 | "age": age, |
|
164 | 173 | "date": lambda x: util.datestr(x), |
|
165 | 174 | "domain": domain, |
|
166 | 175 | "email": util.email, |
|
167 | 176 | "escape": lambda x: cgi.escape(x, True), |
|
168 | 177 | "fill68": lambda x: fill(x, width=68), |
|
169 | 178 | "fill76": lambda x: fill(x, width=76), |
|
170 | 179 | "firstline": firstline, |
|
171 | 180 | "tabindent": lambda x: indent(x, '\t'), |
|
172 | 181 | "hgdate": lambda x: "%d %d" % x, |
|
173 | 182 | "isodate": lambda x: util.datestr(x, '%Y-%m-%d %H:%M %1%2'), |
|
174 | 183 | "isodatesec": lambda x: util.datestr(x, '%Y-%m-%d %H:%M:%S %1%2'), |
|
175 | 184 | "json": json, |
|
176 | 185 | "jsonescape": jsonescape, |
|
177 | 186 | "obfuscate": obfuscate, |
|
178 | 187 | "permissions": permissions, |
|
179 | 188 | "person": person, |
|
180 | 189 | "rfc822date": lambda x: util.datestr(x, "%a, %d %b %Y %H:%M:%S %1%2"), |
|
181 | 190 | "rfc3339date": lambda x: util.datestr(x, "%Y-%m-%dT%H:%M:%S%1:%2"), |
|
182 | 191 | "short": lambda x: x[:12], |
|
183 | 192 | "shortdate": util.shortdate, |
|
184 | 193 | "stringify": templater.stringify, |
|
185 | 194 | "strip": lambda x: x.strip(), |
|
186 | 195 | "urlescape": lambda x: urllib.quote(x), |
|
187 | 196 | "user": lambda x: util.shortuser(x), |
|
188 | 197 | "stringescape": lambda x: x.encode('string_escape'), |
|
189 | 198 | "xmlescape": xmlescape, |
|
190 | 199 | } |
General Comments 0
You need to be logged in to leave comments.
Login now