Project

General

Profile

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

    
3
import datetime
4

    
5
import exc
6
import xml_dom
7

    
8
class SyntaxException(Exception):
9
    def __init__(self, cause=None):
10
        Exception.__init__(self, 'Invalid syntax in XML function: '+str(cause))
11

    
12
def map_items(func, items):
13
    return [(name, func(value)) for name, value in items]
14

    
15
def conv_items(type_, items):
16
    def conv(val):
17
        try: return type_(val)
18
        except ValueError, e: raise SyntaxException(e)
19
    return map_items(conv, items)
20

    
21
def alt(items):
22
    items = list(items)
23
    items.sort()
24
    return items[0][1] # value of lowest-numbered item
25

    
26
def range_(items):
27
    items = dict(conv_items(float, items))
28
    try:
29
        to = items['to']
30
        from_ = items['from']
31
    except KeyError, e: raise SyntaxException(e)
32
    return str(to - from_)
33

    
34
def avg(items):
35
    count = 0
36
    sum_ = 0.
37
    for name, value in conv_items(float, items):
38
        count += 1
39
        sum_ += value
40
    return str(sum_/count)
41

    
42
def date(items):
43
    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
        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
    try: return date.strftime('%Y-%m-%d')
62
    except ValueError, e: raise SyntaxException(e)
63

    
64
_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
def name(items):
73
    items = dict(items)
74
    parts = []
75
    for part in name_parts:
76
        if part in items: parts.append(items[part])
77
    return ' '.join(parts)
78

    
79
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
# Function names must start with _ to avoid collisions with real tags
88
# Functions take arguments (items)
89
funcs = {'_alt': alt, '_range': range_, '_avg': avg, '_date': date,
90
    '_name': name, '_namePart': name_part}
91

    
92
def process(node, on_error=exc.raise_):
93
    for child in xml_dom.NodeElemIter(node): process(child, on_error)
94
    name = node.tagName
95
    if name.startswith('_') and name in funcs:
96
        try: value = funcs[name](xml_dom.NodeTextEntryIter(node))
97
        except SyntaxException, e:
98
            str_ = str(node)
99
            exc.add_msg(e, 'function:\n'+str_)
100
            xml_dom.replace(node, node.ownerDocument.createComment('\n'+str_))
101
            on_error(e)
102
        else: xml_dom.replace_with_text(node, value)
(12-12/13)