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
    try: return map_items(type_, items)
17
    except ValueError, e: raise SyntaxException(e)
18

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

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

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

    
40
def date(items):
41
    items = dict(items)
42
    if 'date' in items:
43
        str_ = items['date']
44
        try: year = float(str_)
45
        except ValueError:
46
            try: import dateutil.parser
47
            except ImportError: return str_
48
            try: date = dateutil.parser.parse(str_)
49
            except ValueError, e: raise SyntaxException(e)
50
        else: date = (datetime.date(int(year), 1, 1) +
51
            datetime.timedelta(round((year % 1.)*365)))
52
    else:
53
        try: year = items['year']
54
        except KeyError, e: raise SyntaxException(e)
55
        month = items.get('month', '1')
56
        day = items.get('day', '1')
57
        try:
58
            year = int(year)
59
            month = int(month)
60
            day = int(day)
61
            date = datetime.date(year, month, day)
62
        except ValueError, e: raise SyntaxException(e)
63
    try: return date.strftime('%Y-%m-%d')
64
    except ValueError, e: raise SyntaxException(e)
65

    
66
_name_parts_slices_items = [
67
    ('first', slice(None, 1)),
68
    ('middle', slice(1, -1)),
69
    ('last', slice(-1, None)),
70
]
71
name_parts_slices = dict(_name_parts_slices_items)
72
name_parts = [name for name, slice_ in _name_parts_slices_items]
73

    
74
def name(items):
75
    items = dict(items)
76
    parts = []
77
    for part in name_parts:
78
        if part in items: parts.append(items[part])
79
    return ' '.join(parts)
80

    
81
def name_part(items):
82
    out_items = []
83
    for part, value in items:
84
        try: slice_ = name_parts_slices[part]
85
        except KeyError, e: raise SyntaxException(e)
86
        else: out_items.append((part, ' '.join(value.split(' ')[slice_])))
87
    return name(out_items)
88

    
89
# Function names must start with _ to avoid collisions with real tags
90
# Functions take arguments (items)
91
funcs = {'_alt': alt, '_range': range_, '_avg': avg, '_date': date,
92
    '_name': name, '_namePart': name_part}
93

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