##// END OF EJS Templates
templatefilters: split out jsonescape() function
Dirkjan Ochtman -
r8014:6a77ba18 default
parent child Browse files
Show More
@@ -1,186 +1,190 b''
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('&', '&amp;')
121 121 .replace('<', '&lt;')
122 122 .replace('>', '&gt;')
123 123 .replace('"', '&quot;')
124 124 .replace("'", '&#39;')) # &apos; 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 def jsonescape(s):
133 for k, v in _escapes:
134 s = s.replace(k, v)
135 return s
136
132 137 def json(obj):
133 138 if obj is None or obj is False or obj is True:
134 139 return {None: 'null', False: 'false', True: 'true'}[obj]
135 140 elif isinstance(obj, int) or isinstance(obj, float):
136 141 return str(obj)
137 142 elif isinstance(obj, str):
138 for k, v in _escapes:
139 obj = obj.replace(k, v)
140 return '"%s"' % obj
143 return '"%s"' % jsonescape(obj)
141 144 elif isinstance(obj, unicode):
142 145 return json(obj.encode('utf-8'))
143 146 elif hasattr(obj, 'keys'):
144 147 out = []
145 148 for k, v in obj.iteritems():
146 149 s = '%s: %s' % (json(k), json(v))
147 150 out.append(s)
148 151 return '{' + ', '.join(out) + '}'
149 152 elif hasattr(obj, '__iter__'):
150 153 out = []
151 154 for i in obj:
152 155 out.append(json(i))
153 156 return '[' + ', '.join(out) + ']'
154 157 else:
155 158 raise TypeError('cannot encode type %s' % obj.__class__.__name__)
156 159
157 160 filters = {
158 161 "addbreaks": nl2br,
159 162 "basename": os.path.basename,
160 163 "age": age,
161 164 "date": lambda x: util.datestr(x),
162 165 "domain": domain,
163 166 "email": util.email,
164 167 "escape": lambda x: cgi.escape(x, True),
165 168 "fill68": lambda x: fill(x, width=68),
166 169 "fill76": lambda x: fill(x, width=76),
167 170 "firstline": firstline,
168 171 "tabindent": lambda x: indent(x, '\t'),
169 172 "hgdate": lambda x: "%d %d" % x,
170 173 "isodate": lambda x: util.datestr(x, '%Y-%m-%d %H:%M %1%2'),
171 174 "isodatesec": lambda x: util.datestr(x, '%Y-%m-%d %H:%M:%S %1%2'),
175 "json": json,
176 "jsonescape": jsonescape,
172 177 "obfuscate": obfuscate,
173 178 "permissions": permissions,
174 179 "person": person,
175 180 "rfc822date": lambda x: util.datestr(x, "%a, %d %b %Y %H:%M:%S %1%2"),
176 181 "rfc3339date": lambda x: util.datestr(x, "%Y-%m-%dT%H:%M:%S%1:%2"),
177 182 "short": lambda x: x[:12],
178 183 "shortdate": util.shortdate,
179 184 "stringify": templater.stringify,
180 185 "strip": lambda x: x.strip(),
181 186 "urlescape": lambda x: urllib.quote(x),
182 187 "user": lambda x: util.shortuser(x),
183 188 "stringescape": lambda x: x.encode('string_escape'),
184 189 "xmlescape": xmlescape,
185 "json": json,
186 190 }
General Comments 0
You need to be logged in to leave comments. Login now