Project

General

Profile

1 86 aaronmk
# XML "function" nodes that evaluate their contents to text
2
3 111 aaronmk
import datetime
4
5 300 aaronmk
import exc
6 86 aaronmk
import xml_dom
7
8 280 aaronmk
class SyntaxException(Exception):
9
    def __init__(self, cause=None):
10 288 aaronmk
        Exception.__init__(self, 'Invalid syntax in XML function: '+str(cause))
11 278 aaronmk
12 86 aaronmk
def map_items(func, items):
13
    return [(name, func(value)) for name, value in items]
14
15 278 aaronmk
def conv_items(type_, items):
16
    try: return map_items(type_, items)
17
    except ValueError, e: raise SyntaxException(e)
18
19 113 aaronmk
def alt(items):
20
    items = list(items)
21
    items.sort()
22
    return items[0][1] # value of lowest-numbered item
23
24 86 aaronmk
def range_(items):
25 278 aaronmk
    items = dict(conv_items(float, items))
26 326 aaronmk
    try:
27
        to = items['to']
28
        from_ = items['from']
29
    except KeyError, e: raise SyntaxException(e)
30
    return str(to - from_)
31 86 aaronmk
32
def avg(items):
33
    count = 0
34
    sum_ = 0.
35 278 aaronmk
    for name, value in conv_items(float, items):
36 86 aaronmk
        count += 1
37
        sum_ += value
38
    return str(sum_/count)
39
40
def date(items):
41
    items = dict(items)
42 287 aaronmk
    if 'date' in items:
43
        str_ = items['date']
44 324 aaronmk
        try: year = float(str_)
45
        except ValueError:
46
            try: import dateutil.parser
47
            except ImportError: return str_
48
            try: date = dateutil.parser.parse(str_)
49
            except ValueError, e: raise SyntaxException(e)
50
        else: date = (datetime.date(int(year), 1, 1) +
51
            datetime.timedelta(round((year % 1.)*365)))
52 287 aaronmk
    else:
53 326 aaronmk
        try: year = items['year']
54
        except KeyError, e: raise SyntaxException(e)
55 287 aaronmk
        month = items.get('month', '1')
56
        day = items.get('day', '1')
57
        try:
58 324 aaronmk
            year = int(year)
59 287 aaronmk
            month = int(month)
60
            day = int(day)
61
        except ValueError, e: raise SyntaxException(e)
62 324 aaronmk
        date = datetime.date(year, month, day)
63 111 aaronmk
    return date.strftime('%Y-%m-%d')
64 86 aaronmk
65 89 aaronmk
def name(items):
66
    items = dict(items)
67
    return ' '.join([items['first'], items['last']])
68
69 102 aaronmk
def namePart(items):
70
    items = dict(items)
71
    def to_parts(name): return items[name].split(' ')
72
    parts = []
73
    if 'first' in items: parts += to_parts('first')[:1]
74
    if 'last' in items: parts += to_parts('last')[-1:]
75
    if 'middle' in items: parts += to_parts('middle')[1:-1]
76
    return ' '.join(parts)
77
78 86 aaronmk
# Function names must start with _ to avoid collisions with real tags
79 144 aaronmk
# Functions take arguments (items)
80 113 aaronmk
funcs = {'_alt': alt, '_range': range_, '_avg': avg, '_date': date,
81 138 aaronmk
    '_name': name, '_namePart': namePart}
82 86 aaronmk
83 142 aaronmk
def process(node):
84 139 aaronmk
    name = node.tagName
85 280 aaronmk
    if name.startswith('_') and name in funcs:
86
        try: value = funcs[name](xml_dom.NodeTextEntryIter(node))
87 288 aaronmk
        except SyntaxException, e:
88 300 aaronmk
            exc.add_msg(e, 'function: '+str(node))
89 288 aaronmk
            raise
90 280 aaronmk
        else: xml_dom.replace_with_text(node, value)
91 86 aaronmk
    else:
92 142 aaronmk
        for child in xml_dom.NodeElemIter(node): process(child)