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