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
    return str(items['to'] - items['from'])
27

    
28
def avg(items):
29
    count = 0
30
    sum_ = 0.
31
    for name, value in conv_items(float, items):
32
        count += 1
33
        sum_ += value
34
    return str(sum_/count)
35

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

    
60
def name(items):
61
    items = dict(items)
62
    return ' '.join([items['first'], items['last']])
63

    
64
def namePart(items):
65
    items = dict(items)
66
    def to_parts(name): return items[name].split(' ')
67
    parts = []
68
    if 'first' in items: parts += to_parts('first')[:1]
69
    if 'last' in items: parts += to_parts('last')[-1:]
70
    if 'middle' in items: parts += to_parts('middle')[1:-1]
71
    return ' '.join(parts)
72

    
73
# Function names must start with _ to avoid collisions with real tags
74
# Functions take arguments (items)
75
funcs = {'_alt': alt, '_range': range_, '_avg': avg, '_date': date,
76
    '_name': name, '_namePart': namePart}
77

    
78
def process(node):
79
    name = node.tagName
80
    if name.startswith('_') and name in funcs:
81
        try: value = funcs[name](xml_dom.NodeTextEntryIter(node))
82
        except SyntaxException, e:
83
            exc.add_msg(e, 'function: '+str(node))
84
            raise
85
        else: xml_dom.replace_with_text(node, value)
86
    else:
87
        for child in xml_dom.NodeElemIter(node): process(child)
(10-10/11)