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