-
Notifications
You must be signed in to change notification settings - Fork 9
/
ashes.py
2723 lines (2283 loc) · 82.2 KB
/
ashes.py
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# Copyright (c) Mahmoud Hashemi
# Available under the 3-clause BSD License. See LICENSE for details.
from __future__ import unicode_literals
import os
import re
import sys
import json
import time
import codecs
import pprint
import string
import fnmatch
PY3 = (sys.version_info[0] == 3)
if PY3:
unicode, string_types = str, (str, bytes)
from html import escape as html_escape
else:
string_types = (str, unicode)
from cgi import escape as html_escape
__version__ = '24.0.1dev'
__author__ = 'Mahmoud Hashemi'
__contact__ = '[email protected]'
__url__ = 'https://github.com/mahmoud/ashes'
__license__ = 'BSD'
DEFAULT_EXTENSIONS = ('.dust', '.html', '.xml')
DEFAULT_IGNORED_PATTERNS = ('.#*',)
# need to add group for literals
# switch to using word boundary for params section
node_re = re.compile(r'({'
r'(?P<closing>\/)?'
r'(?:(?P<symbol>[\~\#\?\@\:\<\>\+\^\%])\s*)?'
r'(?P<refpath>[a-zA-Z0-9_\$\.]+|"[^"]+")'
r'(?:\:(?P<contpath>[a-zA-Z0-9\$\.]+))?'
r'(?P<filters>[\|a-z]+)*?'
r'(?P<params>(?:\s+\w+\=(("[^"]*?")|([$\w\.]+)))*)?'
r'\s*'
r'(?P<selfclosing>\/)?'
r'\})',
flags=re.MULTILINE)
key_re_str = '[a-zA-Z_$][0-9a-zA-Z_$]*'
key_re = re.compile(key_re_str)
path_re = re.compile('(' + key_re_str + ')?([.]' + key_re_str + ')+')
comment_re = re.compile(r'(\{!.+?!\})|(\{`.+?`\})', flags=re.DOTALL)
def get_path_or_key(pork):
if pork == '.':
pk = ['path', True, []]
elif path_re.match(pork):
f_local = pork.startswith('.')
if f_local:
pork = pork[1:]
pk = ['path', f_local, pork.split('.')]
elif key_re.match(pork):
pk = ['key', pork]
else:
raise ValueError('expected a path or key, not %r' % pork)
return pk
def split_leading(text):
leading_stripped = text.lstrip()
leading_ws = text[:len(text) - len(leading_stripped)]
return leading_ws, leading_stripped
class Token(object):
def __init__(self, text):
self.text = text
def get_line_count(self):
# returns 0 if there's only one line, because the
# token hasn't increased the number of lines.
count = len(self.text.splitlines()) - 1
if self.text[-1] in ('\n', '\r'):
count += 1
return count
def __repr__(self):
cn = self.__class__.__name__
disp = self.text
if len(disp) > 20:
disp = disp[:17] + '...'
return '%s(%r)' % (cn, disp)
class CommentToken(Token):
def to_dust_ast(self):
return [['comment', self.text]]
class RawToken(Token):
def to_dust_ast(self):
return [['raw', self.text]]
class BufferToken(Token):
def to_dust_ast(self):
# It is hard to simulate the PEG parsing in this case,
# especially while supporting universal newlines.
if not self.text:
return []
rev = []
remaining_lines = self.text.splitlines()
if self.text[-1] in ('\n', '\r'):
# kind of a bug in splitlines if you ask me.
remaining_lines.append('')
while remaining_lines:
line = remaining_lines.pop()
leading_ws, lstripped = split_leading(line)
if remaining_lines:
if lstripped:
rev.append(['buffer', lstripped])
rev.append(['format', '\n', leading_ws])
else:
if line:
rev.append(['buffer', line])
ret = list(reversed(rev))
return ret
ALL_ATTRS = ('closing', 'symbol', 'refpath', 'contpath',
'filters', 'params', 'selfclosing')
class Tag(Token):
req_attrs = ()
ill_attrs = ()
def __init__(self, text, **kw):
super(Tag, self).__init__(text)
self._attr_dict = kw
self.set_attrs(kw)
@property
def param_list(self):
try:
return params_to_kv(self.params)
except AttributeError:
return []
@property
def name(self):
try:
return self.refpath.strip().lstrip('.')
except (AttributeError, TypeError):
return None
def set_attrs(self, attr_dict, raise_exc=True):
cn = self.__class__.__name__
all_attrs = getattr(self, 'all_attrs', ())
if all_attrs:
req_attrs = [a for a in ALL_ATTRS if a in all_attrs]
ill_attrs = [a for a in ALL_ATTRS if a not in all_attrs]
else:
req_attrs = getattr(self, 'req_attrs', ())
ill_attrs = getattr(self, 'ill_attrs', ())
opt_attrs = getattr(self, 'opt_attrs', ())
if opt_attrs:
ill_attrs = [a for a in ill_attrs if a not in opt_attrs]
for attr in req_attrs:
if attr_dict.get(attr, None) is None:
raise ValueError('%s expected %s' % (cn, attr))
for attr in ill_attrs:
if attr_dict.get(attr, None) is not None:
raise ValueError('%s does not take %s' % (cn, attr))
avail_attrs = [a for a in ALL_ATTRS if a not in ill_attrs]
for attr in avail_attrs:
setattr(self, attr, attr_dict.get(attr, ''))
return True
@classmethod
def from_match(cls, match):
kw = dict([(str(k), v.strip())
for k, v in match.groupdict().items()
if v is not None and v.strip()])
obj = cls(text=match.group(0), **kw)
obj.orig_match = match
return obj
class ReferenceTag(Tag):
all_attrs = ('refpath',)
opt_attrs = ('filters',)
def to_dust_ast(self):
pork = get_path_or_key(self.refpath)
filters = ['filters']
if self.filters:
f_list = self.filters.split('|')[1:]
for f in f_list:
filters.append(f)
return [['reference', pork, filters]]
class SectionTag(Tag):
ill_attrs = ('closing')
class ClosingTag(Tag):
all_attrs = ('closing', 'refpath')
class SpecialTag(Tag):
all_attrs = ('symbol', 'refpath')
def to_dust_ast(self):
return [['special', self.refpath]]
class BlockTag(Tag):
all_attrs = ('symbol', 'refpath')
class PartialTag(Tag):
req_attrs = ('symbol', 'refpath', 'selfclosing')
def __init__(self, **kw):
super(PartialTag, self).__init__(**kw)
self.subtokens = parse_inline(self.refpath)
def to_dust_ast(self):
"""
2014.05.09
This brings compatibility to the more popular fork of Dust.js
from LinkedIn (v1.0)
Adding in `params` so `partials` function like sections.
"""
context = ['context']
contpath = self.contpath
if contpath:
context.append(get_path_or_key(contpath))
params = ['params']
param_list = self.param_list
if param_list:
try:
params.extend(params_to_dust_ast(param_list))
except ParseError as pe:
pe.token = self
raise
# tying to make this more standardized
inline_body = inline_to_dust_ast(self.subtokens)
return [['partial',
inline_body,
context,
params,
]]
def parse_inline(source):
if not source:
raise ParseError('empty inline token')
if source.startswith('"') and source.endswith('"'):
source = source[1:-1]
if not source:
return [BufferToken("")]
tokens = tokenize(source, inline=True)
return tokens
def inline_to_dust_ast(tokens):
if tokens and all(isinstance(t, BufferToken) for t in tokens):
body = ['literal', ''.join(t.text for t in tokens)]
else:
body = ['body']
for b in tokens:
body.extend(b.to_dust_ast())
return body
def params_to_kv(params_str):
ret = []
new_k, v = None, None
p_str = params_str.strip()
k, _, tail = p_str.partition('=')
while tail:
tmp, _, tail = tail.partition('=')
tail = tail.strip()
if not tail:
v = tmp
else:
v, new_k = tmp.split()
ret.append((k.strip(), v.strip()))
k = new_k
return ret
def params_to_dust_ast(param_kv):
ret = []
for k, v in param_kv:
try:
v_body = get_path_or_key(v)
except ValueError:
v_body = inline_to_dust_ast(parse_inline(v))
ret.append(['param', ['literal', k], v_body])
return ret
def get_tag(match, inline=False):
groups = match.groupdict()
symbol = groups['symbol']
closing = groups['closing']
refpath = groups['refpath']
if closing:
tag_type = ClosingTag
elif symbol is None and refpath is not None:
tag_type = ReferenceTag
elif symbol in '#?^<+@%':
tag_type = SectionTag
elif symbol == '~':
tag_type = SpecialTag
elif symbol == ':':
tag_type = BlockTag
elif symbol == '>':
tag_type = PartialTag
else:
raise ParseError('invalid tag symbol: %r' % symbol)
if inline and tag_type not in (ReferenceTag, SpecialTag):
raise ParseError('invalid inline tag')
return tag_type.from_match(match)
def tokenize(source, inline=False):
tokens = []
com_nocom = comment_re.split(source)
line_counts = [1]
def _add_token(t):
# i wish i had nonlocal so bad
t.start_line = sum(line_counts)
line_counts.append(t.get_line_count())
t.end_line = sum(line_counts)
tokens.append(t)
for cnc in com_nocom:
if not cnc:
continue
elif cnc.startswith('{!') and cnc.endswith('!}'):
_add_token(CommentToken(cnc[2:-2]))
continue
elif cnc.startswith('{`') and cnc.endswith('`}'):
_add_token(RawToken(cnc[2:-2]))
continue
prev_end = 0
start = None
end = None
for match in node_re.finditer(cnc):
start, end = match.start(1), match.end(1)
if prev_end < start:
_add_token(BufferToken(cnc[prev_end:start]))
prev_end = end
try:
_add_token(get_tag(match, inline))
except ParseError as pe:
pe.line_no = sum(line_counts)
raise
tail = cnc[prev_end:]
if tail:
_add_token(BufferToken(tail))
return tokens
#########
# PARSING
#########
class Section(object):
def __init__(self, start_tag=None, blocks=None):
if start_tag is None:
refpath = None
name = '<root>'
else:
refpath = start_tag.refpath
name = start_tag.name
self.refpath = refpath
self.name = name
self.start_tag = start_tag
self.blocks = blocks or []
def add(self, obj):
if type(obj) == Block:
self.blocks.append(obj)
else:
if not self.blocks:
self.blocks = [Block()]
self.blocks[-1].add(obj)
def to_dict(self):
ret = {self.name: dict([(b.name, b.to_list()) for b in self.blocks])}
return ret
def to_dust_ast(self):
symbol = self.start_tag.symbol
pork = get_path_or_key(self.refpath)
context = ['context']
contpath = self.start_tag.contpath
if contpath:
context.append(get_path_or_key(contpath))
params = ['params']
param_list = self.start_tag.param_list
if param_list:
try:
params.extend(params_to_dust_ast(param_list))
except ParseError as pe:
pe.token = self
raise
bodies = ['bodies']
if self.blocks:
for b in reversed(self.blocks):
bodies.extend(b.to_dust_ast())
return [[symbol,
pork,
context,
params,
bodies]]
class Block(object):
def __init__(self, name='block'):
if not name:
raise ValueError('blocks need a name, not: %r' % name)
self.name = name
self.items = []
def add(self, item):
self.items.append(item)
def to_list(self):
ret = []
for i in self.items:
try:
ret.append(i.to_dict())
except AttributeError:
ret.append(i)
return ret
def _get_dust_body(self):
# for usage by root block in ParseTree
ret = []
for i in self.items:
ret.extend(i.to_dust_ast())
return ret
def to_dust_ast(self):
name = self.name
body = ['body']
dust_body = self._get_dust_body()
if dust_body:
body.extend(dust_body)
return [['param',
['literal', name],
body]]
class ParseTree(object):
def __init__(self, root_block):
self.root_block = root_block
def to_dust_ast(self):
ret = ['body']
ret.extend(self.root_block._get_dust_body())
return ret
@classmethod
def from_tokens(cls, tokens):
root_sect = Section()
ss = [root_sect] # section stack
for token in tokens:
if type(token) == SectionTag:
new_s = Section(token)
ss[-1].add(new_s)
if not token.selfclosing:
ss.append(new_s)
elif type(token) == ClosingTag:
if len(ss) <= 1:
msg = 'closing tag before opening tag: %r' % token.text
raise ParseError(msg, token=token)
if token.name != ss[-1].name:
msg = ('improperly nested tags: %r does not close %r' %
(token.text, ss[-1].start_tag.text))
raise ParseError(msg, token=token)
ss.pop()
elif type(token) == BlockTag:
if len(ss) <= 1:
msg = 'start block outside of a section: %r' % token.text
raise ParseError(msg, token=token)
new_b = Block(name=token.refpath)
ss[-1].add(new_b)
else:
ss[-1].add(token)
if len(ss) > 1:
raise ParseError('unclosed tag: %r' % ss[-1].start_tag.text,
token=ss[-1].start_tag)
return cls(root_sect.blocks[0])
@classmethod
def from_source(cls, src):
tokens = tokenize(src)
return cls.from_tokens(tokens)
##############
# Optimize AST
##############
DEFAULT_SPECIAL_CHARS = {'s': ' ',
'n': '\n',
'r': '\r',
'lb': '{',
'rb': '}'}
DEFAULT_OPTIMIZERS = {
'body': 'compact_buffers',
'special': 'convert_special',
'format': 'nullify',
'comment': 'nullify'}
for nsym in ('buffer', 'filters', 'key', 'path', 'literal', 'raw'):
DEFAULT_OPTIMIZERS[nsym] = 'noop'
for nsym in ('#', '?', '^', '<', '+', '@', '%', 'reference',
'partial', 'context', 'params', 'bodies', 'param'):
DEFAULT_OPTIMIZERS[nsym] = 'visit'
UNOPT_OPTIMIZERS = dict(DEFAULT_OPTIMIZERS)
UNOPT_OPTIMIZERS.update({'format': 'noop', 'body': 'visit'})
def escape(text, esc_func=json.dumps):
return esc_func(text)
class Optimizer(object):
def __init__(self, optimizers=None, special_chars=None):
if special_chars is None:
special_chars = DEFAULT_SPECIAL_CHARS
self.special_chars = special_chars
if optimizers is None:
optimizers = DEFAULT_OPTIMIZERS
self.optimizers = dict(optimizers)
def optimize(self, node):
# aka filter_node()
nsym = node[0]
optimizer_name = self.optimizers[nsym]
return getattr(self, optimizer_name)(node)
def noop(self, node):
return node
def nullify(self, node):
return None
def convert_special(self, node):
return ['buffer', self.special_chars[node[1]]]
def visit(self, node):
ret = [node[0]]
for n in node[1:]:
filtered = self.optimize(n)
if filtered:
ret.append(filtered)
return ret
def compact_buffers(self, node):
ret = [node[0]]
memo = None
for n in node[1:]:
filtered = self.optimize(n)
if not filtered:
continue
if filtered[0] == 'buffer':
if memo is not None:
memo[1] += filtered[1]
else:
memo = filtered
ret.append(filtered)
else:
memo = None
ret.append(filtered)
return ret
def __call__(self, node):
return self.optimize(node)
#########
# Compile
#########
ROOT_RENDER_TMPL = \
'''def render(chk, ctx):
{body}
return {root_func_name}(chk, ctx)
'''
def _python_compile(source):
"""
Generates a Python `code` object (via `compile`).
args:
source: (required) string of python code to be compiled
this actually compiles the template to code
"""
try:
code = compile(source, '<string>', 'single')
return code
except:
raise
def _python_exec(code, name, global_env=None):
"""
this loads a code object (generated via `_python_compile`
args:
code: (required) code object (generate via `_python_compile`)
name: (required) the name of the function
kwargs:
global_env: (default None): the environment
"""
if global_env is None:
global_env = {}
else:
global_env = dict(global_env)
if PY3:
exec(code, global_env)
else:
exec("exec code in global_env")
return global_env[name]
def python_string_to_code(python_string):
"""
utility function
used to compile python string functions to code object
args:
``python_string``
"""
code = _python_compile(python_string)
return code
def python_string_to_function(python_string):
"""
utility function
used to compile python string functions for template loading/caching
args:
``python_string``
"""
code = _python_compile(python_string)
function = _python_exec(code, name='render', global_env=None)
return function
class Compiler(object):
"""
Note: Compiler objects aren't really meant to be reused,
the class is just for namespacing and convenience.
"""
sections = {'#': 'section',
'?': 'exists',
'^': 'notexists'}
nodes = {'<': 'inline_partial',
'+': 'region',
'@': 'helper',
'%': 'pragma'}
def __init__(self, env=None):
if env is None:
env = default_env
self.env = env
self.bodies = {}
self.blocks = {}
self.block_str = ''
self.index = 0
self.auto = self.env.autoescape_filter
def compile(self, ast, name='render'):
python_source = self._gen_python(ast)
python_code = _python_compile(python_source)
python_func = _python_exec(python_code, name=name)
return (python_code, python_func)
def _gen_python(self, ast): # ast to init?
lines = []
c_node = self._node(ast)
block_str = self._root_blocks()
bodies = self._root_bodies()
lines.extend(bodies.splitlines())
if block_str:
lines.extend(['', block_str, ''])
body = '\n '.join(lines)
ret = ROOT_RENDER_TMPL.format(body=body,
root_func_name=c_node)
self.python_source = ret
return ret
def _root_blocks(self):
if not self.blocks:
self.block_str = ''
return ''
self.block_str = 'ctx = ctx.shift_blocks(blocks)\n '
pairs = ['"' + name + '": ' + fn for name, fn in self.blocks.items()]
return 'blocks = {' + ', '.join(pairs) + '}'
def _root_bodies(self):
max_body = max(self.bodies.keys())
ret = [''] * (max_body + 1)
for i, body in self.bodies.items():
ret[i] = ('\ndef body_%s(chk, ctx):\n %sreturn chk%s\n'
% (i, self.block_str, body))
return ''.join(ret)
def _convert_special(self, node):
return ['buffer', self.special_chars[node[1]]]
def _node(self, node):
ntype = node[0]
if ntype in self.sections:
stype = self.sections[ntype]
return self._section(node, stype)
elif ntype in self.nodes:
ntype = self.nodes[ntype]
cfunc = getattr(self, '_' + ntype, None)
if not callable(cfunc):
raise TypeError('unsupported node type: "%r"', node[0])
return cfunc(node)
def _body(self, node):
index = self.index
self.index += 1 # make into property, equal to len of bodies?
name = 'body_%s' % index
self.bodies[index] = self._parts(node)
return name
def _parts(self, body):
parts = []
for part in body[1:]:
parts.append(self._node(part))
return ''.join(parts)
def _raw(self, node):
return '.write(%r)' % node[1]
def _buffer(self, node):
return '.write(%s)' % escape(node[1])
def _format(self, node):
return '.write(%s)' % escape(node[1] + node[2])
def _reference(self, node):
return '.reference(%s,ctx,%s)' % (self._node(node[1]),
self._node(node[2]))
def _section(self, node, cmd):
return '.%s(%s,%s,%s,%s)' % (cmd,
self._node(node[1]),
self._node(node[2]),
self._node(node[4]),
self._node(node[3]))
def _inline_partial(self, node):
bodies = node[4]
for param in bodies[1:]:
btype = param[1][1]
if btype == 'block':
self.blocks[node[1][1]] = self._node(param[2])
return ''
return ''
def _region(self, node):
"""aka the plus sign ('+') block"""
tmpl = '.block(ctx.get_block(%s),%s,%s,%s)'
return tmpl % (escape(node[1][1]),
self._node(node[2]),
self._node(node[4]),
self._node(node[3]))
def _helper(self, node):
return '.helper(%s,%s,%s,%s)' % (escape(node[1][1]),
self._node(node[2]),
self._node(node[4]),
self._node(node[3]))
def _pragma(self, node):
pr_name = node[1][1]
pragma = self.env.pragmas.get(pr_name)
if not pragma or not callable(pragma):
self.env.log('error', 'pragma', 'missing pragma: %s' % pr_name)
return ''
raw_bodies = node[4]
bodies = {}
for rb in raw_bodies[1:]:
bodies[rb[1][1]] = rb[2]
raw_params = node[3]
params = {}
for rp in raw_params[1:]:
params[rp[1][1]] = rp[2][1]
try:
ctx = node[2][1][1]
except (IndexError, AttributeError):
ctx = None
return pragma(self, ctx, bodies, params)
def _partial(self, node):
"""
2014.05.09
This brings compatibility to the more popular fork of Dust.js
from LinkedIn (v1.0)
Adding in `params` so `partials` function like sections.
updating call to .partial() to include the kwargs
dust.js reference :
compile.nodes = {
partial: function(context, node) {
return '.partial(' +
compiler.compileNode(context, node[1]) +
',' + compiler.compileNode(context, node[2]) +
',' + compiler.compileNode(context, node[3]) + ')';
},
"""
if node[0] == 'body':
body_name = self._node(node[1])
return '.partial(' + body_name + ', %s)' % self._node(node[2])
return '.partial(%s, %s, %s)' % (self._node(node[1]),
self._node(node[2]),
self._node(node[3]))
def _context(self, node):
contpath = node[1:]
if contpath:
return 'ctx.rebase(%s)' % (self._node(contpath[0]))
return 'ctx'
def _params(self, node):
parts = [self._node(p) for p in node[1:]]
if parts:
return '{' + ','.join(parts) + '}'
return 'None'
def _bodies(self, node):
parts = [self._node(p) for p in node[1:]]
return '{' + ','.join(parts) + '}'
def _param(self, node):
return ':'.join([self._node(node[1]), self._node(node[2])])
def _filters(self, node):
ret = '"%s"' % self.auto
f_list = ['"%s"' % f for f in node[1:]] # repr?
if f_list:
ret += ',[%s]' % ','.join(f_list)
return ret
def _key(self, node):
return 'ctx.get(%r)' % node[1]
def _path(self, node):
cur = node[1]
keys = node[2] or []
return 'ctx.get_path(%s, %s)' % (cur, keys)
def _literal(self, node):
return escape(node[1])
#########
# Runtime
#########
class UndefinedValueType(object):
def __repr__(self):
return self.__class__.__name__ + '()'
def __str__(self):
return ''
UndefinedValue = UndefinedValueType()
# Prerequisites for escape_url_path
def _make_quote_map(allowed_chars):
ret = {}
for i in range(256):
c = chr(i)
esc_c = c if c in allowed_chars else '%{0:02X}'.format(i)
ret[i] = ret[c] = esc_c
return ret
# The unreserved URI characters (per RFC 3986)
_UNRESERVED_CHARS = (frozenset(string.ascii_letters)
| frozenset(string.digits)
| frozenset('-._~'))
_RESERVED_CHARS = frozenset(":/?#[]@!$&'()*+,;=") # not used
_PATH_RESERVED_CHARS = frozenset("?#") # not used
_PATH_QUOTE_MAP = _make_quote_map(_UNRESERVED_CHARS | set('/?=&:#'))
# Escapes/filters
def escape_uri_path(text, to_bytes=True):
# actually meant to run on path + query args + fragment
text = to_unicode(text)
if not to_bytes:
return unicode().join([_PATH_QUOTE_MAP.get(c, c) for c in text])
try:
bytestr = text.encode('utf-8')
except UnicodeDecodeError:
bytestr = text
except Exception:
raise ValueError('expected text or UTF-8 encoded bytes, not %r' % text)
return ''.join([_PATH_QUOTE_MAP[b] for b in bytestr])
def escape_uri_component(text):
return (escape_uri_path(text) # calls to_unicode for us
.replace('/', '%2F')
.replace('?', '%3F')
.replace('=', '%3D')
.replace('&', '%26'))
def escape_html(text):
text = to_unicode(text)
ret = html_escape(text, True)
if not PY3:
ret = ret.replace("'", ''')
return ret
def escape_js(text):
text = to_unicode(text)
return (text
.replace('\\', '\\\\')
.replace('"', '\\"')
.replace("'", "\\'")
.replace('\r', '\\r')
.replace('\u2028', '\\u2028')
.replace('\u2029', '\\u2029')
.replace('\n', '\\n')
.replace('\f', '\\f')
.replace('\t', '\\t'))
def comma_num(val):
try:
return '{0:,}'.format(val)
except ValueError:
return to_unicode(val)
def pp_filter(val):
try:
return pprint.pformat(val)
except Exception:
try:
return repr(val)
except Exception:
return 'unreprable object %s' % object.__repr__(val)