1 |
996
|
aaronmk
|
# XML "function" nodes that transform their contents
|
2 |
86
|
aaronmk
|
|
3 |
111
|
aaronmk
|
import datetime
|
4 |
968
|
aaronmk
|
import re
|
5 |
1219
|
aaronmk
|
import sre_constants
|
6 |
1369
|
aaronmk
|
import sys
|
7 |
111
|
aaronmk
|
|
8 |
818
|
aaronmk
|
import dates
|
9 |
300
|
aaronmk
|
import exc
|
10 |
917
|
aaronmk
|
import maps
|
11 |
1234
|
aaronmk
|
import strings
|
12 |
827
|
aaronmk
|
import term
|
13 |
1047
|
aaronmk
|
import util
|
14 |
86
|
aaronmk
|
import xml_dom
|
15 |
1321
|
aaronmk
|
import xpath
|
16 |
86
|
aaronmk
|
|
17 |
995
|
aaronmk
|
##### Exceptions
|
18 |
|
|
|
19 |
962
|
aaronmk
|
class SyntaxException(Exception):
|
20 |
797
|
aaronmk
|
def __init__(self, cause):
|
21 |
962
|
aaronmk
|
Exception.__init__(self, 'Invalid XML function syntax: '
|
22 |
|
|
+exc.str_(cause))
|
23 |
278
|
aaronmk
|
|
24 |
843
|
aaronmk
|
class FormatException(SyntaxException): pass
|
25 |
|
|
|
26 |
995
|
aaronmk
|
##### Functions
|
27 |
|
|
|
28 |
|
|
funcs = {}
|
29 |
|
|
|
30 |
|
|
def process(node, on_error=exc.raise_):
|
31 |
|
|
for child in xml_dom.NodeElemIter(node): process(child, on_error)
|
32 |
|
|
name = node.tagName
|
33 |
|
|
if name.startswith('_') and name in funcs:
|
34 |
1369
|
aaronmk
|
try:
|
35 |
|
|
value = funcs[name](xml_dom.NodeTextEntryIter(node))
|
36 |
|
|
xml_dom.replace_with_text(node, value)
|
37 |
|
|
except Exception, e: # also catch XML func internal errors
|
38 |
1371
|
aaronmk
|
# Save in case another exception raised, overwriting sys.exc_info()
|
39 |
|
|
exc.add_traceback(e)
|
40 |
995
|
aaronmk
|
str_ = str(node)
|
41 |
|
|
exc.add_msg(e, 'function:\n'+str_)
|
42 |
|
|
xml_dom.replace(node, node.ownerDocument.createComment(
|
43 |
1234
|
aaronmk
|
'\n'+term.emph_multiline(str_).replace('--','-')))
|
44 |
|
|
# comments can't contain '--'
|
45 |
995
|
aaronmk
|
on_error(e)
|
46 |
|
|
|
47 |
86
|
aaronmk
|
def map_items(func, items):
|
48 |
|
|
return [(name, func(value)) for name, value in items]
|
49 |
|
|
|
50 |
1234
|
aaronmk
|
def cast(type_, val):
|
51 |
|
|
'''Throws SyntaxException if can't cast'''
|
52 |
|
|
try: return type_(val)
|
53 |
|
|
except ValueError, e: raise SyntaxException(e)
|
54 |
|
|
|
55 |
278
|
aaronmk
|
def conv_items(type_, items):
|
56 |
1234
|
aaronmk
|
return map_items(lambda val: cast(type_, val),
|
57 |
|
|
xml_dom.TextEntryOnlyIter(items))
|
58 |
278
|
aaronmk
|
|
59 |
995
|
aaronmk
|
#### XML functions
|
60 |
|
|
|
61 |
|
|
# Function names must start with _ to avoid collisions with real tags
|
62 |
|
|
# Functions take arguments (items)
|
63 |
|
|
|
64 |
|
|
def _ignore(items):
|
65 |
994
|
aaronmk
|
'''Used to "comment out" an XML subtree'''
|
66 |
|
|
return None
|
67 |
995
|
aaronmk
|
funcs['_ignore'] = _ignore
|
68 |
994
|
aaronmk
|
|
69 |
1234
|
aaronmk
|
def _eq(items):
|
70 |
|
|
items = dict(items)
|
71 |
|
|
try:
|
72 |
|
|
left = items['left']
|
73 |
|
|
right = items['right']
|
74 |
|
|
except KeyError: return '' # a value was None
|
75 |
|
|
return util.bool2str(left == right)
|
76 |
|
|
funcs['_eq'] = _eq
|
77 |
|
|
|
78 |
|
|
def _if(items):
|
79 |
|
|
items = dict(items)
|
80 |
|
|
try:
|
81 |
|
|
cond = items['cond']
|
82 |
|
|
then = items['then']
|
83 |
|
|
except KeyError, e: raise SyntaxException(e)
|
84 |
|
|
else_ = items.get('else', None)
|
85 |
|
|
cond = bool(cast(str, cond))
|
86 |
|
|
if cond: return then
|
87 |
|
|
else: return else_
|
88 |
|
|
funcs['_if'] = _if
|
89 |
|
|
|
90 |
995
|
aaronmk
|
def _alt(items):
|
91 |
113
|
aaronmk
|
items = list(items)
|
92 |
|
|
items.sort()
|
93 |
1186
|
aaronmk
|
try: return items[0][1] # value of lowest-numbered item
|
94 |
1187
|
aaronmk
|
except IndexError: return None # input got removed by e.g. SyntaxException
|
95 |
995
|
aaronmk
|
funcs['_alt'] = _alt
|
96 |
113
|
aaronmk
|
|
97 |
995
|
aaronmk
|
def _merge(items):
|
98 |
1234
|
aaronmk
|
items = list(conv_items(strings.ustr, items))
|
99 |
|
|
# get *once* from iter and check types
|
100 |
917
|
aaronmk
|
items.sort()
|
101 |
|
|
return maps.merge_values(*[v for k, v in items])
|
102 |
995
|
aaronmk
|
funcs['_merge'] = _merge
|
103 |
917
|
aaronmk
|
|
104 |
995
|
aaronmk
|
def _label(items):
|
105 |
917
|
aaronmk
|
items = dict(conv_items(str, items)) # get *once* from iter and check types
|
106 |
|
|
try:
|
107 |
|
|
label = items['label']
|
108 |
|
|
value = items['value']
|
109 |
|
|
except KeyError, e: raise SyntaxException(e)
|
110 |
|
|
return label+': '+value
|
111 |
995
|
aaronmk
|
funcs['_label'] = _label
|
112 |
917
|
aaronmk
|
|
113 |
1047
|
aaronmk
|
def _nullIf(items):
|
114 |
|
|
items = dict(conv_items(str, items))
|
115 |
|
|
try:
|
116 |
|
|
null = items['null']
|
117 |
|
|
value = items['value']
|
118 |
|
|
except KeyError, e: raise SyntaxException(e)
|
119 |
1219
|
aaronmk
|
type_str = items.get('type', None)
|
120 |
|
|
type_ = str
|
121 |
|
|
if type_str == 'float': type_ = float
|
122 |
|
|
return util.none_if(value, type_(null))
|
123 |
1047
|
aaronmk
|
funcs['_nullIf'] = _nullIf
|
124 |
|
|
|
125 |
1219
|
aaronmk
|
def _map(items):
|
126 |
|
|
items = conv_items(str, items) # get *once* from iter and check types
|
127 |
|
|
try: value = items.pop()[1] # value is last entry's value
|
128 |
|
|
except IndexError, e: raise SyntaxException(e)
|
129 |
|
|
map_ = dict(items)
|
130 |
1304
|
aaronmk
|
closed = bool(map_.pop('_closed', False))
|
131 |
1219
|
aaronmk
|
try: return map_[value]
|
132 |
1304
|
aaronmk
|
except KeyError, e:
|
133 |
|
|
if closed: raise SyntaxException(e)
|
134 |
|
|
else: return value
|
135 |
1219
|
aaronmk
|
funcs['_map'] = _map
|
136 |
|
|
|
137 |
|
|
def _replace(items):
|
138 |
|
|
items = conv_items(str, items) # get *once* from iter and check types
|
139 |
|
|
try: value = items.pop() # value is last entry
|
140 |
|
|
except IndexError, e: raise SyntaxException(e)
|
141 |
|
|
try:
|
142 |
|
|
for repl, with_ in items:
|
143 |
|
|
if re.match(r'^\w+$', repl):
|
144 |
|
|
repl = r'(?<![^\W_])'+repl+r'(?![^\W_])' # match whole word
|
145 |
|
|
value = re.sub(repl, with_, value)
|
146 |
|
|
except sre_constants.error, e: raise SyntaxException(e)
|
147 |
|
|
return value
|
148 |
|
|
funcs['_replace'] = _replace
|
149 |
|
|
|
150 |
1225
|
aaronmk
|
def _units(items):
|
151 |
|
|
items = dict(conv_items(str, items))
|
152 |
|
|
try:
|
153 |
|
|
units = items['units']
|
154 |
|
|
value = items['value']
|
155 |
|
|
except KeyError, e: raise SyntaxException(e)
|
156 |
|
|
return value#+' '+units # don't add yet because unit conversion isn't ready
|
157 |
|
|
funcs['_units'] = _units
|
158 |
|
|
|
159 |
995
|
aaronmk
|
def _range(items):
|
160 |
278
|
aaronmk
|
items = dict(conv_items(float, items))
|
161 |
965
|
aaronmk
|
from_ = items.get('from', None)
|
162 |
|
|
to = items.get('to', None)
|
163 |
|
|
if from_ == None or to == None: return None
|
164 |
326
|
aaronmk
|
return str(to - from_)
|
165 |
995
|
aaronmk
|
funcs['_range'] = _range
|
166 |
86
|
aaronmk
|
|
167 |
995
|
aaronmk
|
def _avg(items):
|
168 |
86
|
aaronmk
|
count = 0
|
169 |
|
|
sum_ = 0.
|
170 |
278
|
aaronmk
|
for name, value in conv_items(float, items):
|
171 |
86
|
aaronmk
|
count += 1
|
172 |
|
|
sum_ += value
|
173 |
|
|
return str(sum_/count)
|
174 |
995
|
aaronmk
|
funcs['_avg'] = _avg
|
175 |
86
|
aaronmk
|
|
176 |
968
|
aaronmk
|
class CvException(Exception):
|
177 |
|
|
def __init__(self):
|
178 |
|
|
Exception.__init__(self, 'CV (coefficient of variation) values are only'
|
179 |
|
|
' allowed for ratio scale data '
|
180 |
|
|
'(see <http://en.wikipedia.org/wiki/Coefficient_of_variation>)')
|
181 |
|
|
|
182 |
995
|
aaronmk
|
def _noCV(items):
|
183 |
968
|
aaronmk
|
try: name, value = items.next()
|
184 |
|
|
except StopIteration: return None
|
185 |
|
|
if re.match('^(?i)CV *\d+$', value): raise SyntaxException(CvException())
|
186 |
|
|
return value
|
187 |
995
|
aaronmk
|
funcs['_noCV'] = _noCV
|
188 |
968
|
aaronmk
|
|
189 |
995
|
aaronmk
|
def _date(items):
|
190 |
917
|
aaronmk
|
items = conv_items(str, items) # get *once* from iter and check types
|
191 |
786
|
aaronmk
|
try: str_ = dict(items)['date']
|
192 |
|
|
except KeyError:
|
193 |
1308
|
aaronmk
|
items = dict(conv_items(int, items))
|
194 |
1292
|
aaronmk
|
try: items['year'] # year is required
|
195 |
1309
|
aaronmk
|
except KeyError, e:
|
196 |
|
|
if items == {}: return None # entire date is empty
|
197 |
|
|
else: raise SyntaxException(e)
|
198 |
786
|
aaronmk
|
items.setdefault('month', 1)
|
199 |
|
|
items.setdefault('day', 1)
|
200 |
|
|
try: date = datetime.date(**items)
|
201 |
|
|
except ValueError, e: raise SyntaxException(e)
|
202 |
|
|
else:
|
203 |
324
|
aaronmk
|
try: year = float(str_)
|
204 |
|
|
except ValueError:
|
205 |
1264
|
aaronmk
|
try: date = dates.strtotime(str_)
|
206 |
324
|
aaronmk
|
except ImportError: return str_
|
207 |
|
|
except ValueError, e: raise SyntaxException(e)
|
208 |
|
|
else: date = (datetime.date(int(year), 1, 1) +
|
209 |
|
|
datetime.timedelta(round((year % 1.)*365)))
|
210 |
818
|
aaronmk
|
try: return dates.strftime('%Y-%m-%d', date)
|
211 |
843
|
aaronmk
|
except ValueError, e: raise FormatException(e)
|
212 |
995
|
aaronmk
|
funcs['_date'] = _date
|
213 |
86
|
aaronmk
|
|
214 |
1366
|
aaronmk
|
def _dateRangeStart(items):
|
215 |
|
|
items = dict(conv_items(str, items))
|
216 |
|
|
try: value = items['value']
|
217 |
|
|
except KeyError, e: raise SyntaxException(e)
|
218 |
|
|
return dates.parse_date_range(value)[0]
|
219 |
|
|
funcs['_dateRangeStart'] = _dateRangeStart
|
220 |
1311
|
aaronmk
|
|
221 |
1366
|
aaronmk
|
def _dateRangeEnd(items):
|
222 |
1311
|
aaronmk
|
items = dict(conv_items(str, items))
|
223 |
1366
|
aaronmk
|
try: value = items['value']
|
224 |
1311
|
aaronmk
|
except KeyError, e: raise SyntaxException(e)
|
225 |
1366
|
aaronmk
|
return dates.parse_date_range(value)[1]
|
226 |
|
|
funcs['_dateRangeEnd'] = _dateRangeEnd
|
227 |
1311
|
aaronmk
|
|
228 |
328
|
aaronmk
|
_name_parts_slices_items = [
|
229 |
|
|
('first', slice(None, 1)),
|
230 |
|
|
('middle', slice(1, -1)),
|
231 |
|
|
('last', slice(-1, None)),
|
232 |
|
|
]
|
233 |
|
|
name_parts_slices = dict(_name_parts_slices_items)
|
234 |
|
|
name_parts = [name for name, slice_ in _name_parts_slices_items]
|
235 |
|
|
|
236 |
995
|
aaronmk
|
def _name(items):
|
237 |
89
|
aaronmk
|
items = dict(items)
|
238 |
102
|
aaronmk
|
parts = []
|
239 |
328
|
aaronmk
|
for part in name_parts:
|
240 |
|
|
if part in items: parts.append(items[part])
|
241 |
102
|
aaronmk
|
return ' '.join(parts)
|
242 |
995
|
aaronmk
|
funcs['_name'] = _name
|
243 |
102
|
aaronmk
|
|
244 |
995
|
aaronmk
|
def _namePart(items):
|
245 |
328
|
aaronmk
|
out_items = []
|
246 |
|
|
for part, value in items:
|
247 |
|
|
try: slice_ = name_parts_slices[part]
|
248 |
|
|
except KeyError, e: raise SyntaxException(e)
|
249 |
1219
|
aaronmk
|
out_items.append((part, ' '.join(value.split(' ')[slice_])))
|
250 |
995
|
aaronmk
|
return _name(out_items)
|
251 |
|
|
funcs['_namePart'] = _namePart
|
252 |
1321
|
aaronmk
|
|
253 |
|
|
def _simplifyPath(items):
|
254 |
|
|
items = dict(items)
|
255 |
|
|
try:
|
256 |
|
|
next = cast(str, items['next'])
|
257 |
|
|
require = cast(str, items['require'])
|
258 |
|
|
root = items['path']
|
259 |
|
|
except KeyError, e: raise SyntaxException(e)
|
260 |
|
|
|
261 |
|
|
node = root
|
262 |
|
|
while node != None:
|
263 |
|
|
new_node = xpath.get_1(node, next, allow_rooted=False)
|
264 |
|
|
if xpath.get_1(node, require, allow_rooted=False) == None: # empty elem
|
265 |
|
|
xml_dom.replace(node, new_node) # remove current elem
|
266 |
|
|
if node is root: root = new_node # also update root
|
267 |
|
|
node = new_node
|
268 |
|
|
return root
|
269 |
|
|
funcs['_simplifyPath'] = _simplifyPath
|