1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 """Functions that aid with generating text from templates and maps."""
17
18 import re
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 _substIdPattern = re.compile("%{(?P<id>\w+)}")
44
45
46
47
48
49
50 _substConditionalPattern = re.compile("%{\?(?P<expr>.+?)\?\?(?P<true>.*?)(\?:(?P<false>.*?))?\?}", re.MULTILINE + re.DOTALL)
51
52
53
54
55
56
57
58
59
60
61 _substIfDefinedPattern = re.compile("%{\?(?P<id>\w+)(\?\+(?P<repl>.*?))?(\?\-(?P<ndrepl>.*?))?\?}", re.MULTILINE + re.DOTALL)
62
63
64
65 _substDefinedBodyPattern = re.compile("\?@")
66
67 -def _bodyIfDefinedPattern (match_object, dictionary):
68 global _substDefinedBodyPattern
69 id = match_object.group('id')
70 repl = match_object.group('repl')
71 ndrepl = match_object.group('ndrepl')
72 value = dictionary.get(id, None)
73 if value is not None:
74 if repl:
75 return _substDefinedBodyPattern.sub(id, repl)
76 if ndrepl:
77 return ''
78 return _substDefinedBodyPattern.sub(id, '%{?@}')
79 else:
80 if ndrepl:
81 return _substDefinedBodyPattern.sub(id, ndrepl)
82 return ''
83
84 -def _bodyConditionalPattern (match_object, dictionary):
85 global _substDefinedBodyPattern
86 expr = match_object.group('expr')
87 true = match_object.group('true')
88 false = match_object.group('false')
89 value = None
90 try:
91 value = eval(expr, dictionary)
92 except Exception, e:
93 return '%%{EXCEPTION: %s}' % (e,)
94 if value:
95 return _substDefinedBodyPattern.sub(expr, true)
96 if false is not None:
97 return _substDefinedBodyPattern.sub(expr, false)
98 return ''
99
100 -def replaceInText (text, **dictionary):
101 global _substIfDefinedPattern
102 global _substConditionalPattern
103 global _substIdPattern
104 global _substDefinedBodyPattern
105 rv = text
106 rv = _substIfDefinedPattern.sub(lambda _x: _bodyIfDefinedPattern(_x, dictionary), rv)
107 rv = _substConditionalPattern.sub(lambda _x: _bodyConditionalPattern(_x, dictionary), rv)
108 rv = _substIdPattern.sub(
109 lambda _x,_map=dictionary:
110 _map.get(_x.group('id'), '%%{MISSING:%s}' % (_x.group('id'),))
111 , rv)
112 return rv
113