Project

General

Profile

1 86 aaronmk
# XML "function" nodes that evaluate their contents to text
2
3 111 aaronmk
import datetime
4
5 818 aaronmk
import dates
6 300 aaronmk
import exc
7 86 aaronmk
import xml_dom
8
9 789 aaronmk
class SyntaxException(exc.ExceptionWithCause):
10 797 aaronmk
    def __init__(self, cause):
11
        exc.ExceptionWithCause.__init__(self, 'Invalid XML function syntax',
12
            cause)
13 278 aaronmk
14 86 aaronmk
def map_items(func, items):
15
    return [(name, func(value)) for name, value in items]
16
17 278 aaronmk
def conv_items(type_, items):
18 787 aaronmk
    def conv(val):
19
        try: return type_(val)
20
        except ValueError, e: raise SyntaxException(e)
21 793 aaronmk
    return map_items(conv, xml_dom.TextEntryOnlyIter(items))
22 278 aaronmk
23 113 aaronmk
def alt(items):
24
    items = list(items)
25
    items.sort()
26
    return items[0][1] # value of lowest-numbered item
27
28 86 aaronmk
def range_(items):
29 278 aaronmk
    items = dict(conv_items(float, items))
30 326 aaronmk
    try:
31
        to = items['to']
32
        from_ = items['from']
33
    except KeyError, e: raise SyntaxException(e)
34
    return str(to - from_)
35 86 aaronmk
36
def avg(items):
37
    count = 0
38
    sum_ = 0.
39 278 aaronmk
    for name, value in conv_items(float, items):
40 86 aaronmk
        count += 1
41
        sum_ += value
42
    return str(sum_/count)
43
44
def date(items):
45 794 aaronmk
    items = conv_items(str, items) # Get items *once* from iter and check types
46 786 aaronmk
    try: str_ = dict(items)['date']
47
    except KeyError:
48
        items = dict(filter(lambda (k, v): v != 0, conv_items(int, items)))
49
        items.setdefault('year', 1900)
50
        items.setdefault('month', 1)
51
        items.setdefault('day', 1)
52
        try: date = datetime.date(**items)
53
        except ValueError, e: raise SyntaxException(e)
54
    else:
55 324 aaronmk
        try: year = float(str_)
56
        except ValueError:
57
            try: import dateutil.parser
58
            except ImportError: return str_
59
            try: date = dateutil.parser.parse(str_)
60
            except ValueError, e: raise SyntaxException(e)
61
        else: date = (datetime.date(int(year), 1, 1) +
62
            datetime.timedelta(round((year % 1.)*365)))
63 818 aaronmk
    try: return dates.strftime('%Y-%m-%d', date)
64 721 aaronmk
    except ValueError, e: raise SyntaxException(e)
65 86 aaronmk
66 328 aaronmk
_name_parts_slices_items = [
67
    ('first', slice(None, 1)),
68
    ('middle', slice(1, -1)),
69
    ('last', slice(-1, None)),
70
]
71
name_parts_slices = dict(_name_parts_slices_items)
72
name_parts = [name for name, slice_ in _name_parts_slices_items]
73
74 89 aaronmk
def name(items):
75
    items = dict(items)
76 102 aaronmk
    parts = []
77 328 aaronmk
    for part in name_parts:
78
        if part in items: parts.append(items[part])
79 102 aaronmk
    return ' '.join(parts)
80
81 328 aaronmk
def name_part(items):
82
    out_items = []
83
    for part, value in items:
84
        try: slice_ = name_parts_slices[part]
85
        except KeyError, e: raise SyntaxException(e)
86
        else: out_items.append((part, ' '.join(value.split(' ')[slice_])))
87
    return name(out_items)
88
89 86 aaronmk
# Function names must start with _ to avoid collisions with real tags
90 144 aaronmk
# Functions take arguments (items)
91 113 aaronmk
funcs = {'_alt': alt, '_range': range_, '_avg': avg, '_date': date,
92 328 aaronmk
    '_name': name, '_namePart': name_part}
93 86 aaronmk
94 447 aaronmk
def process(node, on_error=exc.raise_):
95 457 aaronmk
    for child in xml_dom.NodeElemIter(node): process(child, on_error)
96 139 aaronmk
    name = node.tagName
97 280 aaronmk
    if name.startswith('_') and name in funcs:
98
        try: value = funcs[name](xml_dom.NodeTextEntryIter(node))
99 288 aaronmk
        except SyntaxException, e:
100 448 aaronmk
            str_ = str(node)
101
            exc.add_msg(e, 'function:\n'+str_)
102
            xml_dom.replace(node, node.ownerDocument.createComment('\n'+str_))
103 447 aaronmk
            on_error(e)
104 280 aaronmk
        else: xml_dom.replace_with_text(node, value)