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