1
|
# XML "function" nodes that transform their contents
|
2
|
|
3
|
import datetime
|
4
|
import re
|
5
|
import sre_constants
|
6
|
import warnings
|
7
|
|
8
|
import angles
|
9
|
import dates
|
10
|
import exc
|
11
|
import format
|
12
|
import maps
|
13
|
import sql
|
14
|
import strings
|
15
|
import term
|
16
|
import units
|
17
|
import util
|
18
|
import xml_dom
|
19
|
import xpath
|
20
|
|
21
|
##### Exceptions
|
22
|
|
23
|
class SyntaxError(exc.ExceptionWithCause):
|
24
|
def __init__(self, cause):
|
25
|
exc.ExceptionWithCause.__init__(self, 'Invalid XML function syntax',
|
26
|
cause)
|
27
|
|
28
|
class FormatException(exc.ExceptionWithCause):
|
29
|
def __init__(self, cause):
|
30
|
exc.ExceptionWithCause.__init__(self, 'Invalid input value', cause)
|
31
|
|
32
|
##### Helper functions
|
33
|
|
34
|
def map_items(func, items):
|
35
|
return [(name, func(value)) for name, value in items]
|
36
|
|
37
|
def cast(type_, val):
|
38
|
'''Throws FormatException if can't cast'''
|
39
|
try: return type_(val)
|
40
|
except ValueError, e: raise FormatException(e)
|
41
|
|
42
|
def conv_items(type_, items):
|
43
|
return map_items(lambda val: cast(type_, val),
|
44
|
xml_dom.TextEntryOnlyIter(items))
|
45
|
|
46
|
def pop_value(items, name='value'):
|
47
|
'''@param name Name of value param, or None to accept any name'''
|
48
|
try: last = items.pop() # last entry contains value
|
49
|
except IndexError: return None # input is empty and no actions
|
50
|
if name != None and last[0] != name: return None # input is empty
|
51
|
return last[1]
|
52
|
|
53
|
funcs = {}
|
54
|
|
55
|
structural_funcs = set()
|
56
|
|
57
|
##### Public functions
|
58
|
|
59
|
def is_func_name(name):
|
60
|
return name.startswith('_') and name != '_' # '_' is default root node name
|
61
|
|
62
|
def is_func(node): return is_func_name(node.tagName)
|
63
|
|
64
|
def is_xml_func_name(name): return is_func_name(name) and name in funcs
|
65
|
|
66
|
def is_xml_func(node): return is_xml_func_name(node.tagName)
|
67
|
|
68
|
def process(node, on_error=exc.raise_, db=None):
|
69
|
for child in xml_dom.NodeElemIter(node): process(child, on_error)
|
70
|
name = node.tagName
|
71
|
if is_func_name(name):
|
72
|
try:
|
73
|
items = xml_dom.NodeTextEntryIter(node)
|
74
|
try: func = funcs[name]
|
75
|
except KeyError:
|
76
|
if db != None: # DB with relational functions available
|
77
|
value = sql.put(db, name, dict(items))
|
78
|
else: value = pop_value(list(items)) # pass value through
|
79
|
else: value = func(items, node) # local XML function
|
80
|
|
81
|
xml_dom.replace_with_text(node, value)
|
82
|
except Exception, e: # also catch non-wrapped exceptions (XML func bugs)
|
83
|
# Save in case another exception raised, overwriting sys.exc_info()
|
84
|
exc.add_traceback(e)
|
85
|
str_ = strings.ustr(node)
|
86
|
exc.add_msg(e, 'function:\n'+str_)
|
87
|
xml_dom.replace(node, xml_dom.mk_comment(node.ownerDocument,
|
88
|
'\n'+term.emph_multiline(str_)))
|
89
|
|
90
|
on_error(e)
|
91
|
|
92
|
def strip(node, preserve=set()):
|
93
|
'''Replaces every XML function with its last parameter (which is usually its
|
94
|
value), except for structural functions, which are evaluated by process().
|
95
|
@param preserve set(str...) XML functions not to remove.
|
96
|
* container can be any iterable type
|
97
|
'''
|
98
|
preserve = set(preserve)
|
99
|
|
100
|
name = node.tagName
|
101
|
is_func = is_xml_func_name(name) and name not in preserve
|
102
|
if is_func and name in structural_funcs: process(node)
|
103
|
else:
|
104
|
for child in xml_dom.NodeElemIter(node): strip(child, preserve)
|
105
|
if is_func:
|
106
|
value = pop_value(list(xml_dom.NodeTextEntryIter(node)), None)
|
107
|
xml_dom.replace_with_text(node, value)
|
108
|
|
109
|
##### XML functions
|
110
|
|
111
|
# Function names must start with _ to avoid collisions with real tags
|
112
|
# Functions take arguments (items)
|
113
|
|
114
|
#### Structural
|
115
|
|
116
|
def _ignore(items, node):
|
117
|
'''Used to "comment out" an XML subtree'''
|
118
|
return None
|
119
|
funcs['_ignore'] = _ignore
|
120
|
structural_funcs.add('_ignore')
|
121
|
|
122
|
def _ref(items, node):
|
123
|
'''Used to retrieve a value from another XML node
|
124
|
@param items
|
125
|
addr=<path> XPath to value, relative to the XML func's parent node
|
126
|
'''
|
127
|
items = dict(items)
|
128
|
try: addr = items['addr']
|
129
|
except KeyError, e: raise SyntaxError(e)
|
130
|
|
131
|
value = xpath.get_value(node.parentNode, addr)
|
132
|
if value == None:
|
133
|
warnings.warn(UserWarning('_ref: XPath reference target missing: '
|
134
|
+str(addr)))
|
135
|
return value
|
136
|
funcs['_ref'] = _ref
|
137
|
structural_funcs.add('_ref')
|
138
|
|
139
|
#### Conditionals
|
140
|
|
141
|
def _eq(items, node):
|
142
|
items = dict(items)
|
143
|
try:
|
144
|
left = items['left']
|
145
|
right = items['right']
|
146
|
except KeyError: return '' # a value was None
|
147
|
return util.bool2str(left == right)
|
148
|
funcs['_eq'] = _eq
|
149
|
|
150
|
def _if(items, node):
|
151
|
items = dict(items)
|
152
|
try:
|
153
|
cond = items['cond']
|
154
|
then = items['then']
|
155
|
except KeyError, e: raise SyntaxError(e)
|
156
|
else_ = items.get('else', None)
|
157
|
cond = bool(cast(strings.ustr, cond))
|
158
|
if cond: return then
|
159
|
else: return else_
|
160
|
funcs['_if'] = _if
|
161
|
|
162
|
#### Combining values
|
163
|
|
164
|
def _alt(items, node):
|
165
|
items = list(items)
|
166
|
items.sort()
|
167
|
try: return items[0][1] # value of lowest-numbered item
|
168
|
except IndexError: return None # input got removed by e.g. FormatException
|
169
|
funcs['_alt'] = _alt
|
170
|
|
171
|
def _merge(items, node):
|
172
|
items = list(conv_items(strings.ustr, items))
|
173
|
# get *once* from iter, check types
|
174
|
items.sort()
|
175
|
return maps.merge_values(*[v for k, v in items])
|
176
|
funcs['_merge'] = _merge
|
177
|
|
178
|
def _label(items, node):
|
179
|
items = dict(conv_items(strings.ustr, items))
|
180
|
# get *once* from iter, check types
|
181
|
value = items.get('value', None)
|
182
|
if value == None: return None # input is empty
|
183
|
try: label = items['label']
|
184
|
except KeyError, e: raise SyntaxError(e)
|
185
|
return label+': '+value
|
186
|
funcs['_label'] = _label
|
187
|
|
188
|
#### Transforming values
|
189
|
|
190
|
def _collapse(items, node):
|
191
|
'''Collapses a subtree if the "value" element in it is NULL'''
|
192
|
items = dict(items)
|
193
|
try: require = cast(strings.ustr, items['require'])
|
194
|
except KeyError, e: raise SyntaxError(e)
|
195
|
value = items.get('value', None)
|
196
|
|
197
|
if xpath.get_value(value, require, allow_rooted=False) == None: return None
|
198
|
else: return value
|
199
|
funcs['_collapse'] = _collapse
|
200
|
|
201
|
types_by_name = {None: strings.ustr, 'str': strings.ustr, 'float': float}
|
202
|
|
203
|
def _nullIf(items, node):
|
204
|
items = dict(conv_items(strings.ustr, items))
|
205
|
try: null = items['null']
|
206
|
except KeyError, e: raise SyntaxError(e)
|
207
|
value = items.get('value', None)
|
208
|
type_str = items.get('type', None)
|
209
|
|
210
|
try: type_ = types_by_name[type_str]
|
211
|
except KeyError, e: raise SyntaxError(e)
|
212
|
null = type_(null)
|
213
|
|
214
|
try: return util.none_if(value, null)
|
215
|
except ValueError: return value # value not convertible, so can't equal null
|
216
|
funcs['_nullIf'] = _nullIf
|
217
|
|
218
|
def repl(repls, value):
|
219
|
'''Raises error if value not in map and no special '*' entry
|
220
|
@param repls dict repl:with
|
221
|
repl "*" means all other input values
|
222
|
with "*" means keep input value the same
|
223
|
with "" means ignore input value
|
224
|
'''
|
225
|
try: new_value = repls[value]
|
226
|
except KeyError, e:
|
227
|
# Save traceback right away in case another exception raised
|
228
|
fe = FormatException(e)
|
229
|
try: new_value = repls['*']
|
230
|
except KeyError: raise fe
|
231
|
if new_value == '*': new_value = value # '*' means keep input value the same
|
232
|
return new_value
|
233
|
|
234
|
def _map(items, node):
|
235
|
'''See repl()
|
236
|
@param items
|
237
|
<last_entry> Value
|
238
|
<other_entries> name=value Mappings. Special values: See repl() repls.
|
239
|
'''
|
240
|
items = conv_items(strings.ustr, items) # get *once* from iter, check types
|
241
|
value = pop_value(items)
|
242
|
if value == None: return None # input is empty
|
243
|
return util.none_if(repl(dict(items), value), u'') # empty value means None
|
244
|
funcs['_map'] = _map
|
245
|
|
246
|
def _replace(items, node):
|
247
|
items = conv_items(strings.ustr, items) # get *once* from iter, check types
|
248
|
value = pop_value(items)
|
249
|
if value == None: return None # input is empty
|
250
|
try:
|
251
|
for repl, with_ in items:
|
252
|
if re.match(r'^\w+$', repl):
|
253
|
repl = r'(?<![^\W_])'+repl+r'(?![^\W_])' # match whole word
|
254
|
value = re.sub(repl, with_, value)
|
255
|
except sre_constants.error, e: raise SyntaxError(e)
|
256
|
return util.none_if(value.strip(), u'') # empty strings always mean None
|
257
|
funcs['_replace'] = _replace
|
258
|
|
259
|
#### Quantities
|
260
|
|
261
|
def _units(items, node):
|
262
|
items = conv_items(strings.ustr, items) # get *once* from iter, check types
|
263
|
value = pop_value(items)
|
264
|
if value == None: return None # input is empty
|
265
|
|
266
|
quantity = units.str2quantity(value)
|
267
|
try:
|
268
|
for action, units_ in items:
|
269
|
units_ = util.none_if(units_, u'')
|
270
|
if action == 'default': units.set_default_units(quantity, units_)
|
271
|
elif action == 'to':
|
272
|
try: quantity = units.convert(quantity, units_)
|
273
|
except ValueError, e: raise FormatException(e)
|
274
|
else: raise SyntaxError(ValueError('Invalid action: '+action))
|
275
|
except units.MissingUnitsException, e: raise FormatException(e)
|
276
|
return units.quantity2str(quantity)
|
277
|
funcs['_units'] = _units
|
278
|
|
279
|
def parse_range(str_, range_sep='-'):
|
280
|
default = (str_, None)
|
281
|
start, sep, end = str_.partition(range_sep)
|
282
|
if sep == '': return default # not a range
|
283
|
if start == '' and range_sep == '-': return default # negative number
|
284
|
return tuple(d.strip() for d in (start, end))
|
285
|
|
286
|
def _rangeStart(items, node):
|
287
|
items = dict(conv_items(strings.ustr, items))
|
288
|
try: value = items['value']
|
289
|
except KeyError: return None # input is empty
|
290
|
return parse_range(value)[0]
|
291
|
funcs['_rangeStart'] = _rangeStart
|
292
|
|
293
|
def _rangeEnd(items, node):
|
294
|
items = dict(conv_items(strings.ustr, items))
|
295
|
try: value = items['value']
|
296
|
except KeyError: return None # input is empty
|
297
|
return parse_range(value)[1]
|
298
|
funcs['_rangeEnd'] = _rangeEnd
|
299
|
|
300
|
def _range(items, node):
|
301
|
items = dict(conv_items(float, items))
|
302
|
from_ = items.get('from', None)
|
303
|
to = items.get('to', None)
|
304
|
if from_ == None or to == None: return None
|
305
|
return str(to - from_)
|
306
|
funcs['_range'] = _range
|
307
|
|
308
|
def _avg(items, node):
|
309
|
count = 0
|
310
|
sum_ = 0.
|
311
|
for name, value in conv_items(float, items):
|
312
|
count += 1
|
313
|
sum_ += value
|
314
|
if count == 0: return None # input is empty
|
315
|
else: return str(sum_/count)
|
316
|
funcs['_avg'] = _avg
|
317
|
|
318
|
class CvException(Exception):
|
319
|
def __init__(self):
|
320
|
Exception.__init__(self, 'CV (coefficient of variation) values are only'
|
321
|
' allowed for ratio scale data '
|
322
|
'(see <http://en.wikipedia.org/wiki/Coefficient_of_variation>)')
|
323
|
|
324
|
def _noCV(items, node):
|
325
|
try: name, value = items.next()
|
326
|
except StopIteration: return None
|
327
|
if re.match('^(?i)CV *\d+$', value): raise FormatException(CvException())
|
328
|
return value
|
329
|
funcs['_noCV'] = _noCV
|
330
|
|
331
|
#### Dates
|
332
|
|
333
|
def _date(items, node):
|
334
|
items = dict(conv_items(strings.ustr, items))
|
335
|
# get *once* from iter, check types
|
336
|
try: str_ = items['date']
|
337
|
except KeyError:
|
338
|
# Year is required
|
339
|
try: items['year']
|
340
|
except KeyError, e:
|
341
|
if items == {}: return None # entire date is empty
|
342
|
else: raise FormatException(e)
|
343
|
|
344
|
# Convert month name to number
|
345
|
try: month = items['month']
|
346
|
except KeyError: pass
|
347
|
else:
|
348
|
if not month.isdigit(): # month is name
|
349
|
try: items['month'] = str(dates.strtotime(month).month)
|
350
|
except ValueError, e: raise FormatException(e)
|
351
|
|
352
|
items = dict(conv_items(format.str2int, items.iteritems()))
|
353
|
items.setdefault('month', 1)
|
354
|
items.setdefault('day', 1)
|
355
|
|
356
|
for try_num in xrange(2):
|
357
|
try:
|
358
|
date = datetime.date(**items)
|
359
|
break
|
360
|
except ValueError, e:
|
361
|
if try_num > 0: raise FormatException(e)
|
362
|
# exception still raised after retry
|
363
|
msg = strings.ustr(e)
|
364
|
if msg == 'month must be in 1..12': # try swapping month and day
|
365
|
items['month'], items['day'] = items['day'], items['month']
|
366
|
else: raise FormatException(e)
|
367
|
else:
|
368
|
try: year = float(str_)
|
369
|
except ValueError:
|
370
|
try: date = dates.strtotime(str_)
|
371
|
except ImportError: return str_
|
372
|
except ValueError, e: raise FormatException(e)
|
373
|
else: date = (datetime.date(int(year), 1, 1) +
|
374
|
datetime.timedelta(round((year % 1.)*365)))
|
375
|
try: return dates.strftime('%Y-%m-%d', date)
|
376
|
except ValueError, e: raise FormatException(e)
|
377
|
funcs['_date'] = _date
|
378
|
|
379
|
def _dateRangeStart(items, node):
|
380
|
items = dict(conv_items(strings.ustr, items))
|
381
|
try: value = items['value']
|
382
|
except KeyError: return None # input is empty
|
383
|
return dates.parse_date_range(value)[0]
|
384
|
funcs['_dateRangeStart'] = _dateRangeStart
|
385
|
|
386
|
def _dateRangeEnd(items, node):
|
387
|
items = dict(conv_items(strings.ustr, items))
|
388
|
try: value = items['value']
|
389
|
except KeyError: return None # input is empty
|
390
|
return dates.parse_date_range(value)[1]
|
391
|
funcs['_dateRangeEnd'] = _dateRangeEnd
|
392
|
|
393
|
#### Names
|
394
|
|
395
|
_name_parts_slices_items = [
|
396
|
('first', slice(None, 1)),
|
397
|
('middle', slice(1, -1)),
|
398
|
('last', slice(-1, None)),
|
399
|
]
|
400
|
name_parts_slices = dict(_name_parts_slices_items)
|
401
|
name_parts = [name for name, slice_ in _name_parts_slices_items]
|
402
|
|
403
|
def _name(items, node):
|
404
|
items = dict(items)
|
405
|
parts = []
|
406
|
for part in name_parts:
|
407
|
if part in items: parts.append(items[part])
|
408
|
return ' '.join(parts)
|
409
|
funcs['_name'] = _name
|
410
|
|
411
|
def _namePart(items, node):
|
412
|
out_items = []
|
413
|
for part, value in items:
|
414
|
try: slice_ = name_parts_slices[part]
|
415
|
except KeyError, e: raise SyntaxError(e)
|
416
|
out_items.append((part, ' '.join(value.split(' ')[slice_])))
|
417
|
return _name(out_items, node)
|
418
|
funcs['_namePart'] = _namePart
|
419
|
|
420
|
#### Angles
|
421
|
|
422
|
def _compass(items, node):
|
423
|
'''Converts a compass direction (N, NE, NNE, etc.) into a degree heading'''
|
424
|
items = dict(conv_items(strings.ustr, items))
|
425
|
try: value = items['value']
|
426
|
except KeyError: return None # input is empty
|
427
|
|
428
|
if not value.isupper(): return value # pass through other coordinate formats
|
429
|
try: return util.cast(str, angles.compass2heading(value)) # ignore None
|
430
|
except KeyError, e: raise FormatException(e)
|
431
|
funcs['_compass'] = _compass
|
432
|
|
433
|
#### Paths
|
434
|
|
435
|
def _simplifyPath(items, node):
|
436
|
items = dict(items)
|
437
|
try:
|
438
|
next = cast(strings.ustr, items['next'])
|
439
|
require = cast(strings.ustr, items['require'])
|
440
|
root = items['path']
|
441
|
except KeyError, e: raise SyntaxError(e)
|
442
|
|
443
|
node = root
|
444
|
while node != None:
|
445
|
new_node = xpath.get_1(node, next, allow_rooted=False)
|
446
|
if xpath.get_value(node, require, allow_rooted=False) == None: # empty
|
447
|
xml_dom.replace(node, new_node) # remove current elem
|
448
|
if node is root: root = new_node # also update root
|
449
|
node = new_node
|
450
|
return root
|
451
|
funcs['_simplifyPath'] = _simplifyPath
|