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 xml_dom
8

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

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

    
17
def conv_items(type_, items):
18
    def conv(val):
19
        try: return type_(val)
20
        except ValueError, e: raise SyntaxException(e)
21
    return map_items(conv, xml_dom.TextEntryOnlyIter(items))
22

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

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

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

    
44
def date(items):
45
    items = conv_items(str, items) # Get items *once* from iter and check types
46
    try: str_ = dict(items)['date']
47
    except KeyError:
48
        items = dict(filter(lambda (k, v): v != 0, conv_items(int, items)))
49
        items.setdefault('year', 1900)
50
        items.setdefault('month', 1)
51
        items.setdefault('day', 1)
52
        try: date = datetime.date(**items)
53
        except ValueError, e: raise SyntaxException(e)
54
    else:
55
        try: year = float(str_)
56
        except ValueError:
57
            try: import dateutil.parser
58
            except ImportError: return str_
59
            try: date = dateutil.parser.parse(str_)
60
            except ValueError, e: raise SyntaxException(e)
61
        else: date = (datetime.date(int(year), 1, 1) +
62
            datetime.timedelta(round((year % 1.)*365)))
63
    try: return dates.strftime('%Y-%m-%d', date)
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)
(13-13/14)