-
Notifications
You must be signed in to change notification settings - Fork 2
/
visitor.py
1631 lines (1347 loc) · 68.2 KB
/
visitor.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Hive Colony Framework
# Copyright (c) 2008-2015 Hive Solutions Lda.
#
# This file is part of Hive Colony Framework.
#
# Hive Colony Framework is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Hive Colony Framework is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Hive Colony Framework. If not, see <http://www.gnu.org/licenses/>.
__author__ = "João Magalhães <joamag@hive.pt>"
""" The author(s) of the module """
__version__ = "1.0.0"
""" The version of the module """
__revision__ = "$LastChangedRevision$"
""" The revision number of the module """
__date__ = "$LastChangedDate$"
""" The last change date of the module """
__copyright__ = "Copyright (c) 2008-2015 Hive Solutions Lda."
""" The copyright for the module """
__license__ = "GNU General Public License (GPL), Version 3"
""" The license for the module """
import re
import os
import uuid
import types
import calendar
import datetime
import xml.sax.saxutils
import colony
from . import ast
from . import util
from . import exceptions
FUNCTION_TYPES = (
types.MethodType,
types.FunctionType,
types.BuiltinMethodType,
types.BuiltinFunctionType
)
""" The complete set of types that are going to be
considered function types during runtime """
SERIALIZERS = (
"json",
"pickle"
)
""" The list to hold the various serializers
in order of preference for serialization """
SERIALIZERS_MAP = None
""" The map associating the encoding type for
the serialization with the appropriate serializer
object to handle it """
LITERAL_ESCAPE_REGEX_VALUE = "\$\\\\(?=\\\\*\{)"
""" The literal escape regular expression value """
FUCNTION_ARGUMENTS_REGEX_VALUE = "\([\sa-zA-Z0-9_\-,\.\:\=\%'\/\"]+\)"
""" The function arguments regular expression value
that will match any possible (variable or constant) value """
NAMES_REGEX_VALUE = "([^\.]+\([^\)]+\))|([^\.]+)"
""" The regular expression that is going to be used for the
splitting of the various names for a variable based value that
is going to be evaluated at runtime, this value may contain
method calls with literal an non literal values """
LITERAL_ESCAPE_REGEX = re.compile(LITERAL_ESCAPE_REGEX_VALUE)
""" The literal escape regular expression """
FUCNTION_ARGUMENTS_REGEX = re.compile(FUCNTION_ARGUMENTS_REGEX_VALUE)
""" The function arguments regular expression """
NAMES_REGEX = re.compile(NAMES_REGEX_VALUE)
""" The compiled version of names regular expression used for the
matching of the various components of a variable template value """
DEFAULT_DATE_FORMAT = "%d/%m/%y"
""" The default date format """
DEFAULT_TIME_FORMAT = "%H:%M:%S"
""" The default time format """
DEFAULT_DATE_TIME_FORMAT = "%d/%m/%y %H:%M:%S"
""" The default date time format """
SEQUENCE_TYPES = (list, tuple)
""" The tuple containing the types considered to be sequences """
SERIALIZABLE_TYPES = (list, tuple)
""" The tuple containing the set of types that can be
"serializable" in a custom manner """
RESOLVABLE_TYPES = (str, colony.legacy.UNICODE, colony.FormatTuple)
""" The tuple containing the set of types that can be
"resolved" in the localization context """
BUILTINS = {
"True" : True,
"False" : False,
"len" : len
}
""" The base builtins structure that is going to be re-used
for every parsing operation to be done by the visitor, this
should contain the minimum amount of symbols required for the
parsing of the template file (to avoid security issues) """
CONVERSION_MAP = {
"2_of_5" : colony.encode_2_of_5
}
""" The map associating the name of the conversion
function with the conversion function symbol reference """
COMPARISION_FUNCTIONS = {
"not" : lambda item, value: not item,
"eq" : lambda item, value: item == value,
"neq" : lambda item, value: not item == value,
"gte" : lambda item, value: item >= value,
"gt" : lambda item, value: item > value,
"lte" : lambda item, value: item <= value,
"lt" : lambda item, value: item < value,
"len" : lambda item, value: len(item) == value,
"lengt" : lambda item, value: len(item) > value,
"lenlt" : lambda item, value: len(item) < value,
"in" : lambda item, value: item and value in item or False,
"nin" : lambda item, value: item and not value in item or False
}
""" The map containing the comparison functions (lambda) these
are going to be used "inside" the visitor execution logic """
FILTERS = dict(
e = lambda v, t: v if v == None else xml.sax.saxutils.escape(t._serialize_value(v)),
default = lambda v, t, default = "", boolean = False:\
default if boolean and not v or v == None else v,
double = lambda v, t: v if v == None else v * 2,
format = lambda v, t, format: v if v == None else format % v
)
""" The dictionary containing the complete set
of base filters to be exposed to the visitor,
this dictionary may be extended at runtime """
class Visitor(object):
"""
The visitor class for the template engine. This is the abstract
implementation and more concrete implementations may exists if
the default behavior should be replaced.
"""
owner = None
""" The owner object for the visitor, this object may be used
for external state changes that are processed upon visit
(eg: inheritance processing) """
node_method_map = {}
""" The node method map structure that is going to be used
by the visitor decorators for proper polymorphic visit """
encoding = None
""" The encoding used the file, this is a meta-information
value that is not going to be used for any practical usage """
base_path = None
""" The base path to be used for the resolution of template
files that are going to be either included or extended, this
value is not mandatory and in case it's not defined only
the relative path resolution strategy is going to be used """
file_path = None
""" The path to the file that generated the abstract syntax
tree that is going to be visited by this visitor """
template_engine = None
""" The reference template engine system object that handles
and manages this visitor (owner object) """
variable_encoding = None
""" The variable encoding value this is the name of the encoding
that is going to be used for the output of their string value
to the currently set string buffer """
strict_mode = False
""" The strict mode, that controls if the processing should
be done in a strict way meaning that exceptions should be
raised whenever an unexpected value is received/processed """
visit_childs = True
""" The visit childs flag, that controls if the children
of a note should also be visited when a node is visited """
global_map = {}
""" The global map, containing the global (interpreter wide)
names that are going to be used at the time of template
evaluation note that this map may be shared among the
sub templates in both the extension and inclusion operations """
string_buffer = None
""" Buffer to where the complete set of output data will be
written as part of the processing of the template, this object
should comply with the typical file orations interface so that
no runtime problems occur during the template processing """
process_methods_list = []
""" The list of process methods (tuples) that contains the
complete set of extra methods that are going to be used in
the processing of "complex" nodes """
locale_bundles = []
""" The list that contains the various bundles to be searched for
localization, the order set is going to be the priority for template
value resolution (from first to last list element) """
def __init__(self, owner = None, string_buffer = None):
"""
Constructor of the class.
@type owner: Template
@param owner: The owner object of the visitor, this object is
expected to comply with the template interface as some of the
visitor operations will change the object with that assumption.
@type string_buffer: File
@param string_buffer: The file like object that is going to be
used for the underlying buffering of the template process. In
case no value is provided the default string buffer object is used.
"""
self.owner = owner
self.node_method_map = {}
self.visit_childs = True
self.global_map = dict(__builtins__ = BUILTINS)
self.string_buffer = string_buffer or colony.StringBuffer()
self.process_methods_list = []
self.locale_bundles = []
self.filters = dict(FILTERS)
self.update_node_method_map()
def update_node_method_map(self):
# retrieves the current instance class and list the
# complete set of element for the current class so that
# the proper node method map may be created
cls = self.__class__
cls_elements = dir(cls)
# iterates over the complete set of elements (attributes)
# defined for the current instance's class trying to find
# the ones that are annotated with the ast node class value
for name in cls_elements:
# retrieves the current element in iteration and verifies
# if the current element is annotated with the asr node class
# value, if that's not the case continues the loop
element = getattr(cls, name)
if not hasattr(element, "ast_node_class"): continue
# retrieves the elements node class and associated the
# current element with the node class in the node class
# method map (to be used latter in runtime verification)
ast_node_class = element.ast_node_class
self.node_method_map[ast_node_class] = element
def attach_process_method(self, method_name, method):
# creates the process method instance, that is attached to
# the general visitor class and sets it the current instance
method_instance = types.MethodType(method, self)
setattr(self, method_name, method_instance)
# creates the process method tuple that contains both the
# name of the method and the method reference and adds the
# tuple to the list of process method, this is going to be
# used in the initial stage of the template creation
process_method_tuple = (method_name, method)
self.process_methods_list.append(process_method_tuple)
def get_global_map(self):
return self.global_map
def write(self, data, *args, **kwargs):
if not self.string_buffer: return
is_unicode = type(data) == colony.legacy.UNICODE
if is_unicode and self.encoding: data = data.encode(self.encoding)
self.string_buffer.write(data, *args, **kwargs)
def set_global_map(self, global_map):
self.global_map = global_map
def get_global(self, name):
return self.global_map[name]
def set_global(self, name, value):
self.global_map[name] = value
def del_global(self, name):
del self.global_map[name]
def get_global_many(self, name):
parts = name.split(".")
last = parts[-1]
current = self.global_map
for part in parts[:-1]:
current = current.get(part, {})
return current.get(last, None)
def set_global_many(self, name, value):
parts = name.split(".")
last = parts[-1]
current = self.global_map
for part in parts[:-1]:
next = current.get(part, {})
current[part] = next
current = next
current[last] = value
def add_bundle(self, bundle):
self.locale_bundles.append(bundle)
def add_filter(self, name, filter):
self.filters[name] = filter
def get_encoding(self):
return self.encoding
def set_encoding(self, encoding):
self.encoding = encoding
def get_base_path(self):
return self.base_path
def set_base_path(self, base_path):
self.base_path = base_path
def get_file_path(self):
return self.file_path
def set_file_path(self, file_path):
self.file_path = file_path
def get_template_engine(self):
return self.template_engine
def set_template_engine(self, template_engine):
self.template_engine = template_engine
def get_variable_encoding(self):
return self.variable_encoding
def set_variable_encoding(self, variable_encoding):
self.variable_encoding = variable_encoding
def get_strict_mode(self):
return self.strict_mode
def set_strict_mode(self, strict_mode):
self.strict_mode = strict_mode
@colony.dispatch_visit()
def visit(self, node):
print("unrecognized element node of type " + node.__class__.__name__)
def before_visit(self, node):
self.visit_childs = True
def after_visit(self, node):
pass
@colony.visit(ast.AstNode)
def visit_ast_node(self, node):
pass
@colony.visit(ast.RootNode)
def visit_root_node(self, node):
pass
@colony.visit(ast.LiteralNode)
def visit_literal_node(self, node):
# retrieves the match value from the current node's
# value escaping it to avoid any problem and then
# writes the value into the current string buffer
match_value = node.value.value
match_value = self._escape_literal(match_value)
self.write(match_value)
@colony.visit(ast.MatchNode)
def visit_match_node(self, node):
pass
@colony.visit(ast.SingleNode)
def visit_single_node(self, node):
pass
@colony.visit(ast.CompositeNode)
def visit_composite_node(self, node):
pass
def process_accept(self, node, name):
# retrieves the process method for the name and runs the
# same method with the current node as the argument
process_method = getattr(self, "process_" + name)
process_method(node)
def process_out(self, node):
"""
Processes the out none node, that outputs a processed
data to the current processing context/buffer.
In case the resolved value is invalid/none the resulting
data is printed as an empty string.
@type node: SingleNode
@param node: The single node to be processed as out none.
"""
# retrieves the attributes map for the current node that
# is going to be used to process the data that is going
# to be printed to the current context
attributes = node.get_attributes()
# retrieves the localization value, this is going to be used
# for a lot of sub-operation in retrieval and must be gathered
# before the rest of the attributes for such purpose
localize = attributes.get("localize", None)
localize = self.get_boolean_value(localize, True)
# retrieves the complete set of attributes from the attributes
# defined for the current node, it's an extensive list and
# the range of usage and data types are vast
value = attributes["value"]
value = self.get_value(value, localize = localize)
prefix = attributes.get("prefix", None)
prefix = self.get_value(prefix, localize = localize, default = "")
format = attributes.get("format", None)
format = self.get_value(format)
quote = attributes.get("quote", None)
quote = self.get_boolean_value(quote)
xml_escape = attributes.get("xml_escape", None)
xml_escape = self.get_boolean_value(xml_escape)
xml_quote = attributes.get("xml_escape", None)
xml_quote = self.get_boolean_value(xml_quote)
newline_convert = attributes.get("newline_convert", None)
newline_convert = self.get_boolean_value(newline_convert)
convert = attributes.get("convert", None)
convert = self.get_value(convert)
allow_empty = attributes.get("allow_empty", None)
allow_empty = self.get_value(allow_empty, default = True)
default = attributes.get("default", None)
default = self.get_value(default, localize = localize)
serializer = attributes.get("serializer", None)
serializer = self.get_literal_value(serializer)
# in case the format value is defined the provided value
# must be formated according to the value specified in
# that field using the default (python) formatter
if format:
is_valid = format and not value == None
value = format % value if is_valid else value
# creates the invalid values tuple according to the allow
# empty flag and the verifies if the value is defined under
# such value falling back to the default value for such case
invalid_values = (None,) if allow_empty else (None, "")
if value in invalid_values: value = default
# in case the attribute value value is invalid and the default
# value is not set (no need to show the value) must return
# immediately nothing will be printed
if value in invalid_values and default == None: return
# in case the serializer value is set must try to gather
# the serializer and serialize the attribute value using it
if serializer:
serializer, _name = self._get_serializer(serializer)
value = serializer.dumps(value)
# serializes the value into the correct visual representation
# (in case the attribute type is "serializable", eg: lists, tuples, etc.)
value = self._serialize_value(value)
# checks if the attribute value contains a unicode string
# in such case there's no need to re-decode it
is_unicode = type(value) == colony.legacy.UNICODE
value = is_unicode and value or colony.legacy.UNICODE(value)
# in case the attribute convert value is set
if convert:
# retrieves the conversion method for the string
# value representing it and uses it to convert
# the attribute value to the target encoding
conversion_method = CONVERSION_MAP.get(convert, None)
value = conversion_method(value) if conversion_method else value
# in case the variable encoding is defined must re-encode
# the variable according to the current variable encoding
if self.variable_encoding: value = value.encode(self.variable_encoding)
# in case the attribute quote value is set must quote the
# value using the provided colony utility
if quote:
value = value.encode("utf-8")
value = colony.quote(value, safe = "/")
# runs the final transformation on the value according to
# the provided flags (custom operations)
if xml_escape: value = xml.sax.saxutils.escape(value)
if xml_quote: value = value.replace("\"", """)
if newline_convert: value = value.replace("\n", "<br/>")
# runs the final appending of the prefix value to the value
# and then writes the final string/unicode value to the buffer
value = prefix + value
self.write(value)
def process_set(self, node):
return self.process_var(node)
def process_var(self, node):
"""
Processes the var node, this is the operation that
allow the attribute of a value in the current context
the required attributes are the item (literal) and the
value.
@type node: Node
@param node: The single node to be processed as var.
"""
# retrieves the map that contains the attributes for the
# current node and then unpacks each of this values
attributes = node.get_attributes()
item = attributes["item"]
item = self.get_literal_value(item)
value = attributes["value"]
value = self.get_value(value)
# sets the attribute value value in the global map, this
# is considered to represent the assign operation, from
# this moment the variable with the same name is available
self.set_global(item, value)
def process_for(self, node):
return self.process_foreach(node)
def process_foreach(self, node):
attributes = node.get_attributes()
iterable = attributes["from"]
iterable = self.get_value(iterable)
item = attributes.get("item", None)
item = self.get_literal_value(item)
index_ref = attributes.get("index", None)
index_ref = self.get_literal_value(index_ref)
key_ref = attributes.get("key", None)
key_ref = self.get_literal_value(key_ref)
start_index = attributes.get("start_index", None)
start_index = self.get_literal_value(start_index)
# in case the start index literal value is defined
# retrieves the index as the integer cast of the
# partial name otherwise the index start at one
if start_index: index = int(start_index[1:-1])
else: index = 1
# in case the attribute does not have the iterator method
# it's not iterable and a fallback strategy must performed
if not hasattr(iterable, "__iter__"):
# in case the strict mode is active, an exception must be
# raised because it's not possible to perform the iteration
if self.strict_mode:
# retrieves the attribute from name (value) and uses
# it to raise the proper exception with the description
# for the variable that is not iterable
from_value = attributes["from"]["value"]
raise exceptions.VariableNotIterable("value not iterable: " + from_value)
# otherwise avoids exception in case the object
# is not an invalid one (possible problems) by
# "casting" the attribute from value to a list it
# will create an iterable object that may be used
elif not iterable == None: iterable = [iterable]
# otherwise in case the object is considered invalid
# the best match for the cast is an empty list
else: iterable = []
# sets the various global wide values relates with the
# current loop operation that is going to be performed
# this values are not related with each iteration
self.set_global_many("loop.length", len(iterable))
self.set_global_many("loop.cycle", self._loop_cycle)
# verifies if the iterable currently in use is of type
# map (dictionary) this will condition the way the loop
# part of the operation will be performed
is_map = colony.is_dictionary(iterable)
# in case the current structure is not map based and the
# item value naming is not defined, sets the key reference
# as the item value and unsets both the key and index
# reference (non map iteration requires value assign)
if not is_map and not item:
item = key_ref; key_ref = None; index_ref = None
# iterates over the complete set of elements in the iterable,
# note that the value contained in the item will not be the
# same if the iterable is a map or if it is a sequence
for element in iterable:
is_first = index == 1
is_last = index == len(iterable)
self.set_global_many("loop.index", index)
self.set_global_many("loop.index0", index - 1)
self.set_global_many("loop.first", is_first)
self.set_global_many("loop.last", is_last)
self.set_global("is_first", is_first)
self.set_global("is_last", is_last)
key = element if is_map else index
value = iterable[element] if is_map else element
if item: self.set_global(item, value)
if index_ref: self.set_global(index_ref, index)
if key_ref: self.set_global(key_ref, key)
if self.visit_childs:
for child in node.children:
child.accept(self)
index += 1
def process_if(self, node):
# evaluates the current node comparison, this is the default
# acceptance behavior for all the nodes that do not require
# an extra evaluation process (evaluation nodes)
accept_node = self._evaluate_comparison_node(node)
# in case the visit child flag is not set the method must
# return immediately as there's nothing remaining to be done
if not self.visit_childs: return
# iterates over all the child nodes for the current if node
# to evaluate or process them according to their type
for child in node.children:
# validates the accept node, so that if the node is "eval"
# the evaluation is done otherwise the default evaluation
# result for the if node is applied
accept_node = self._validate_accept_node(child, accept_node)
# in case the accept node is set to invalid
# the evaluation is over (nothing to be done)
if accept_node == None: return
# in case the accept node flag is set accepts the node
# child node as it is considered to be valid
accept_node and child.accept(self)
def process_else(self, node):
pass
def process_elif(self, node):
pass
def process_cycle(self, node):
attributes = node.get_attributes()
values = attributes["values"]
values = self.get_value(values)
values = values.split(",")
if hasattr(node, "current_index"):
values_length = len(values)
current_index = node.current_index
if current_index == values_length - 1: current_index = 0
else: current_index += 1
else:
current_index = 0
node.current_index = current_index
current_value = values[current_index]
self.write(current_value)
def process_count(self, node):
# retrieves the current nodes's attributes and gathers the value
# field from the dictionary retrieving then it's value
attributes = node.get_attributes()
value = attributes["value"]
value = self.get_value(value)
# in case the retrieved value is invalid the length of it is considered
# to be zero otherwise measures its size and sets accordingly
if value == None: value_length = 0
else: value_length = len(value)
# checks if the attribute value length contains a unicode string
# in such case there's no need to re-decode it
is_unicode = type(value_length) == colony.legacy.UNICODE
value_length = is_unicode and value_length or colony.legacy.UNICODE(value_length)
# in case the variable encoding value is defined encodes the string
# value using the currently defined encoding (as expected) and then
# writes the resulting string value to the current buffer
if self.variable_encoding:
value_length = value_length.encode(self.variable_encoding)
self.write(value_length)
def process_include(self, node):
# in case the current include node already contains children nodes it
# is considered to be processed and so there's no need to re-process
# again the same structure (time to visit the children nodes instead)
if node.children:
children = node.children if self.visit_childs else ()
for child in children: child.accept(self)
return
# retrieves the current node's attributes and uses them to unpack
# the attributes that are relevant for the include processing
attributes = node.get_attributes()
file = attributes.get("file", None)
file = self.get_literal_value(file)
file_value = attributes.get("file_value", None)
file_value = self.get_value(file_value)
# retrieves the initial file path value from either the file
# or the file value attributes (whatever is defined)
file_path = file or file_value
# parses the file retrieving the template file structure, note
# that any path existence validation will be done at this stage,
# after this loading operation the visitor is loaded into the
# template engine and the visitor is accepted, this is going to
# create a partial abstract syntax tree that is going to be
# appended to the current node as subtree
template_file = self._get_template(node, file_path)
template_file.set_global_map(self.global_map)
template_file.load_visitor()
template_file.root_node.accept(template_file.visitor)
# updates the current node's children sequence with the complete
# set of root children of the processed file (propagation) and
# then sets the parent node of the complete set of children with
# the current include node (parent reference update)
node.children = template_file.root_node.children
for child in node.children: child.parent = node
# runs the visit operation in the complete set of child nodes
# so that they get update with the proper include files if they
# have ones (normal recursive step operation)
children = node.children if self.visit_childs else ()
for child in children: child.accept(self)
def process_extends(self, node):
# retrieves the current node's attributes and uses them to unpack
# the information for the template to be extended
attributes = node.get_attributes()
file = attributes.get("file", None)
file = self.get_literal_value(file)
file_value = attributes.get("file_value", None)
file_value = self.get_value(file_value)
# retrieves the initial file path value from either the file
# or the file value attributes (whatever is defined)
file_path = file or file_value
# parses the file retrieving the template file structure, note
# that any path existence validation will be done at this stage,
# after this loading operation the visitor is loaded into the
# template engine and the visitor is accepted, this should create
# a partial abstract syntax tree that must then be processed and
# used as the base for the current processing (inheritance)
template_file = self._get_template(node, file_path)
template_file.set_global_map(self.global_map)
template_file.load_visitor()
template_file.root_node.accept(template_file.visitor)
template_file.index_nodes()
# "transfers" the children nodes of the super template file to
# the current visitor owner root node (base inheritance)
self.owner.root_node.children = template_file.root_node.children
for child in self.owner.root_node.children: child.parent = self.owner.root_node
# retrieves both the current template owner nodes map and the nodes
# map of the "super" template file as there structures are going
# to be used for the replacing of the various blocks
nodes = self.owner.nodes
super_nodes = template_file.nodes
# iterates over the complete set of globally index nodes to try to find
# the ones that are defined and switch them so that the most specific
# (concrete templates) are defined and reference the most abstract ones
for name, node in colony.legacy.items(nodes):
# tries to retrieve a super node for the current block name in
# iteration and in case there's one switches the current node
# with the previous one, otherwise adds the current node as a
# child to the root node (fallback operation) then updates the
# global nodes map with the current node
super_node = super_nodes.get(name, None)
if super_node: super_node.switch(node)
else: self.owner.root_node.add_child(node)
super_nodes[name] = node
# sets the global nodes map of the super node (already updated) as
# the nodes map of the visitor's owner
self.owner.nodes = super_nodes
def process_block(self, node):
def super():
if not node.super: return
node.super.accept(self)
self.set_global("super", super)
if self.visit_childs:
for child in node.children:
child.accept(self)
def process_uuid(self, node):
# creates a new uuid value and converts it into a string
# value to be used in the string buffer
uuid_value = uuid.uuid4()
uuid_string_value = str(uuid_value)
self.write(uuid_string_value)
def process_year(self, node):
# retrieves the current date time formats it according to
# the default year format and writes the value to buffer
current_date_time = datetime.datetime.now()
year_value = current_date_time.strftime("%Y")
self.write(year_value)
def process_date(self, node):
attributes = node.get_attributes()
format = attributes.get("format", None)
format = self.get_literal_value(format, default = DEFAULT_DATE_FORMAT)
format = str(format)
current_date_time = datetime.datetime.now()
date_value = current_date_time.strftime(format)
self.write(date_value)
def process_time(self, node):
attributes = node.get_attributes()
format = attributes.get("format", None)
format = self.get_literal_value(format, default = DEFAULT_TIME_FORMAT)
format = str(format)
current_date_time = datetime.datetime.now()
time_value = current_date_time.strftime(format)
self.write(time_value)
def process_datetime(self, node):
attributes = node.get_attributes()
format = attributes.get("format", None)
format = self.get_literal_value(format, default = DEFAULT_DATE_TIME_FORMAT)
format = str(format)
current_date_time = datetime.datetime.now()
date_time_value = current_date_time.strftime(format)
self.write(date_time_value)
def process_format_datetime(self, node):
attributes = node.get_attributes()
value = attributes["value"]
value = self.get_value(value)
format = attributes["format"]
format = self.get_literal_value(format)
default = attributes.get("default", None)
default = self.get_value(default)
if value == None:
value = default if default else value
if value: self.write(value)
return
format = str(format)
value_format = value.strftime(format)
self.write(value_format)
def process_format_timestamp(self, node):
attributes = node.get_attributes()
value = attributes["value"]
value = self.get_value(value)
format = attributes["format"]
format = self.get_literal_value(format)
default = attributes.get("default", None)
default = self.get_value(default)
if value == None:
value = default if default else value
if value: self.write(value)
return
format = str(format)
date_time = datetime.datetime.utcfromtimestamp(value)
value_format = date_time.strftime(format)
self.write(value_format)
def process_timestamp(self, node):
attributes = node.get_attributes()
localize = attributes.get("localize", None)
localize = self.get_boolean_value(localize, True)
value = attributes.get("value", None)
value = self.get_value(value, default = datetime.datetime.now())
default = attributes.get("default", None)
default = self.get_value(default, localize = localize)
if value == None:
value = default if default else value
if value: self.write(value)
return
time_tuple = value.utctimetuple()
timestamp = calendar.timegm(time_tuple)
timestamp_s = str(timestamp)
self.write(timestamp_s)
def get_value(self, attribute, localize = False, default = None):
"""
Retrieves the value (variable or literal) of the given
value. The process of retrieving the variable value is
iterative and may consume some time in resolution.
An optional localize flag may be set of the value should
be localized using the current local bundles.
@type attribute: Dictionary
@param attribute: A map describing the attribute structure.
@type localize: bool
@param localize: If the value must be localized using the currently
available locale bundles.
@type default: Object
@param default: The default (fallback) value to be returned if
no valid attribute is provided or in case it is invalid.
@rtype: Object
@return: The resolved attribute value.
"""
# in case the passed attribute is not valid the default must
# be returned immediately as no resolution is possible, this
# is the default and expected behavior (fallback procedure)
if not attribute: return default
# retrieves the (processed) value of the attribute and the
# original (unprocessed) value, so that they may be used
# for the value processing (as expected)
value = attribute["value"]
original = attribute["original"]
# splits the raw (attribute) value into the various parts
# of it, separating the proper variable name from the
# various filters as defined in the specification
parts = original.split("|")
filters = [filter.strip() for filter in parts[1:]]
# in case the attribute value is of type variable, must be
# properly handled (stripping the value from extra lines)
if attribute["type"] == "variable":
# retrieves the variable name by stripping the first part
# of the filters splitting (as expected)
variable_name = parts[0].strip()
# in case the variable name is none sets the final value
# with the invalid value as that's requested by the template
if variable_name == "None": value = None
# otherwise the value must be processed according to the currently
# defined template rules (may required method invocation)
else:
# resolves the variable name using the multiple parts
# approach so that the final value is retrieved according
# to the current state of the template engine
value = self.resolve_many(variable_name)
# in case the attribute value is of type literal the value must
# be "read" using a literal based approach so that the proper and
# concrete value is going to be returned as the value
elif attribute["type"] == "literal":
pass
# resolves the current "variable" value, trying to
# localize it using the current locale bundles only
# do this in case the localize flag is set
value = self._resolve_locale(value) if localize else value
# iterates over the complete set of filter definition to