Project

General

Profile

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

    
3
import datetime
4

    
5
import ex
6
import xml_dom
7

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

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

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

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

    
25
def range_(items):
26
    items = dict(conv_items(float, items))
27
    return str(items['to'] - items['from'])
28

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

    
37
def date(items):
38
    items = dict(items)
39
    year = items['year']
40
    month = items.get('month', '1')
41
    day = items.get('day', '1')
42
    try:
43
        year = float(year)
44
        month = int(month)
45
        day = int(day)
46
    except ValueError, e: raise SyntaxException(e)
47
    date = (datetime.date(int(year), month, day) +
48
        datetime.timedelta(round((year % 1.)*365)))
49
    return date.strftime('%Y-%m-%d')
50

    
51
def name(items):
52
    items = dict(items)
53
    return ' '.join([items['first'], items['last']])
54

    
55
def namePart(items):
56
    items = dict(items)
57
    def to_parts(name): return items[name].split(' ')
58
    parts = []
59
    if 'first' in items: parts += to_parts('first')[:1]
60
    if 'last' in items: parts += to_parts('last')[-1:]
61
    if 'middle' in items: parts += to_parts('middle')[1:-1]
62
    return ' '.join(parts)
63

    
64
# Function names must start with _ to avoid collisions with real tags
65
# Functions take arguments (items)
66
funcs = {'_alt': alt, '_range': range_, '_avg': avg, '_date': date,
67
    '_name': name, '_namePart': namePart}
68

    
69
def process(node):
70
    name = node.tagName
71
    if name.startswith('_') and name in funcs:
72
        try: value = funcs[name](xml_dom.NodeTextEntryIter(node))
73
        except SyntaxException, e: ex.repl_msg(e, {'func': name}); raise
74
        else: xml_dom.replace_with_text(node, value)
75
    else:
76
        for child in xml_dom.NodeElemIter(node): process(child)
(10-10/11)