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