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