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