Project

General

Profile

1
# XML "function" nodes that evaluate their contents to text
2

    
3
import datetime
4

    
5
import dates
6
import exc
7
import maps
8
import term
9
import xml_dom
10

    
11
class SyntaxException(exc.ExceptionWithCause):
12
    def __init__(self, cause):
13
        exc.ExceptionWithCause.__init__(self, 'Invalid XML function syntax',
14
            cause)
15

    
16
class FormatException(SyntaxException): pass
17

    
18
def map_items(func, items):
19
    return [(name, func(value)) for name, value in items]
20

    
21
def conv_items(type_, items):
22
    def conv(val):
23
        try: return type_(val)
24
        except ValueError, e: raise SyntaxException(e)
25
    return map_items(conv, xml_dom.TextEntryOnlyIter(items))
26

    
27
def alt(items):
28
    items = list(items)
29
    items.sort()
30
    return items[0][1] # value of lowest-numbered item
31

    
32
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
def range_(items):
46
    items = dict(conv_items(float, items))
47
    try:
48
        to = items['to']
49
        from_ = items['from']
50
    except KeyError, e: raise SyntaxException(e)
51
    return str(to - from_)
52

    
53
def avg(items):
54
    count = 0
55
    sum_ = 0.
56
    for name, value in conv_items(float, items):
57
        count += 1
58
        sum_ += value
59
    return str(sum_/count)
60

    
61
def date(items):
62
    items = conv_items(str, items) # get *once* from iter and check types
63
    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
        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
    try: return dates.strftime('%Y-%m-%d', date)
81
    except ValueError, e: raise FormatException(e)
82

    
83
_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
def name(items):
92
    items = dict(items)
93
    parts = []
94
    for part in name_parts:
95
        if part in items: parts.append(items[part])
96
    return ' '.join(parts)
97

    
98
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
# Function names must start with _ to avoid collisions with real tags
107
# Functions take arguments (items)
108
funcs = {'_alt': alt, '_merge': merge, '_label': label, '_range': range_,
109
    '_avg': avg, '_date': date, '_name': name, '_namePart': name_part}
110

    
111
def process(node, on_error=exc.raise_):
112
    for child in xml_dom.NodeElemIter(node): process(child, on_error)
113
    name = node.tagName
114
    if name.startswith('_') and name in funcs:
115
        try: value = funcs[name](xml_dom.NodeTextEntryIter(node))
116
        except SyntaxException, e:
117
            str_ = str(node)
118
            exc.add_msg(e, 'function:\n'+str_)
119
            xml_dom.replace(node, node.ownerDocument.createComment(
120
                '\n'+term.emph_multiline(str_)))
121
            on_error(e)
122
        else: xml_dom.replace_with_text(node, value)
(13-13/14)