-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathfilters.py
More file actions
303 lines (219 loc) · 7.06 KB
/
Copy pathfilters.py
File metadata and controls
303 lines (219 loc) · 7.06 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
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
# --------------------------------------------------------------------------
# Default filter functions for use in templates. Additional filter functions
# can be registered using the `@register` decorator:
#
# @ibis.filters.register('name')
#
# A filter function should accept at least one argument - the value to be
# filtered - and return the filtered result. It can optionally accept any
# number of additional arguments.
# --------------------------------------------------------------------------
import random
import re
import pprint
import html
from . import errors
try:
import pygments
import pygments.lexers
import pygments.formatters
except ImportError:
pygments = None
# Dictionary of registered filter functions.
filtermap = {}
def register(nameorfunc=None):
""" Decorator function for registering filters.
Can be used as:
@register
@register()
@register('name')
If no name is supplied the function name will be used.
"""
if callable(nameorfunc):
filtermap[nameorfunc.__name__] = nameorfunc
return nameorfunc
def register_filter_function(func):
filtermap[nameorfunc or func.__name__] = func
return func
return register_filter_function
@register
def argtest(*args):
""" Test filter: returns arguments as a concatenated string. """
return '|'.join(str(arg) for arg in args)
@register
def default(obj, fallback):
""" Returns `obj` if `obj` is truthy, otherwise `fallback`. """
return obj or fallback
@register
def dtformat(dt, format='%Y-%m-%d %H:%M'):
""" Formats a datetime object using the specified format string. """
return dt.strftime(format)
@register
def endswith(s, suffix):
""" True if the string ends with the specified suffix. """
return s.endswith(suffix)
@register
@register('e')
@register('esc')
def escape(s, quotes=True):
""" Converts html syntax characters to character entities. """
return html.escape(s, quotes)
@register
def first(seq):
""" Returns the first element in the sequence `seq`. """
return seq[0]
@register
def firsth(html):
""" Returns the content of the first heading element. """
match = re.search(r'<h(\d)+[^>]*>(.*?)</h\1>', html, flags=re.DOTALL)
return match.group(2) if match else ''
@register
def firsth1(html):
""" Returns the content of the first h1 element. """
match = re.search(r'<h1[^>]*>(.*?)</h1>', html, flags=re.DOTALL)
return match.group(1) if match else ''
@register
def firstp(html):
""" Returns the content of the first p element. """
match = re.search(r'<p[^>]*>(.*?)</p>', html, flags=re.DOTALL)
return match.group(1) if match else ''
@register('reversed')
def get_reversed(seq):
""" Returns a reverse iterator over the sequence `seq`. """
return reversed(seq)
@register
def index(seq, i):
""" Returns the ith element in the sequence `seq`. """
return seq[i]
@register('divisible_by')
def is_divisible_by(n, d):
""" True if the integer `n` is a multiple of the integer `d`. """
return n % d == 0
@register('even')
def is_even(n):
""" True if the integer `n` is even. """
return n % 2 == 0
@register('odd')
def is_odd(n):
""" True if the integer `n` is odd. """
return n % 2 != 0
@register
def join(seq, sep=''):
""" Joins elements of the sequence `seq` with the string `sep`. """
return sep.join(str(item) for item in seq)
@register
def last(seq):
""" Returns the last element in the sequence `seq`. """
return seq[-1]
@register('len')
def length(seq):
""" Returns the length of the sequence `seq`. """
return len(seq)
@register
def lower(s):
""" Returns the string `s` converted to lowercase. """
return s.lower()
@register('pprint')
def prettyprint(obj):
""" Returns a pretty-printed representation of `obj`. """
return pprint.pformat(obj)
@register
def pygmentize(text, lang=None):
""" Applies syntax highlighting using Pygments.
If no language is specified, Pygments will attempt to guess the correct
lexer to use. If Pygments is not available or if an appropriate lexer
cannot be found then the filter will return the input text with any
html special characters escaped.
"""
if pygments:
if lang:
try:
lexer = pygments.lexers.get_lexer_by_name(lang)
except pygments.util.ClassNotFound:
lexer = None
else:
try:
lexer = pygments.lexers.guess_lexer(text)
except pygments.util.ClassNotFound:
lexer = None
if lexer:
formatter = pygments.formatters.HtmlFormatter(nowrap=True)
text = pygments.highlight(text, lexer, formatter)
else:
text = html.escape(text)
else:
text = html.escape(text)
return text
@register
def random(seq):
""" Returns a random element from the sequence `seq`. """
return random.choice(seq)
@register('repr')
def to_repr(obj):
""" Returns the result of calling repr() on `obj`. """
return repr(obj)
@register
def slice(seq, start, stop=None, step=None):
""" Returns the start:stop:step slice of the sequence `seq`. """
return seq[start:stop:step]
@register
def spaceless(html):
""" Strips all whitespace between html/xml tags. """
return re.sub(r'>\s+<', '><', html)
@register
def startswith(s, prefix):
""" True if the string starts with the specified prefix. """
return s.startswith(prefix)
@register('str')
def to_str(obj):
""" Returns the result of calling str() on `obj`. """
return str(obj)
@register
def striptags(html):
""" Returns the string `html` with all html tags stripped. """
return re.sub(r'<[^>]*>', '', html)
@register
def teaser(s, delimiter='<!-- more -->'):
""" Returns the portion of the string `s` before `delimiter`,
or an empty string if `delimiter` is not found. """
index = s.find(delimiter)
if index == -1:
return ''
else:
return s[:index]
@register
@register('title')
def titlecase(s):
""" Returns the string `s` converted to titlecase. """
return re.sub(
r"[A-Za-z]+('[A-Za-z]+)?",
lambda m: m.group(0)[0].upper() + m.group(0)[1:],
s
)
@register
def truncatechars(s, n, ellipsis='...'):
""" Truncates the string `s` to at most `n` characters. """
if len(s) > n:
return s[:n - 3].rstrip(' .,;:?!') + ellipsis
else:
return s
@register
def truncatewords(s, n, ellipsis=' [...]'):
""" Truncates the string `s` to at most `n` words. """
words = s.split()
if len(words) > n:
return ' '.join(words[:n]) + ellipsis
else:
return ' '.join(words)
@register
def undefined(obj, fallback):
""" Returns `obj` if `obj` is defined, otherwise `fallback`. """
return fallback if isinstance(obj, errors.Undefined) else obj
@register
def upper(s):
""" Returns the string `s` converted to uppercase. """
return s.upper()
@register
def wrap(s, tag):
""" Wraps a string in opening and closing tags. """
return '<%s>%s</%s>' % (tag, str(s), tag)