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

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

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

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

    
76
def process(node):
77
    name = node.tagName
78
    if name.startswith('_') and name in funcs:
79
        try: value = funcs[name](xml_dom.NodeTextEntryIter(node))
80
        except SyntaxException, e: ex.repl_msg(e, func=name); raise
81
        else: xml_dom.replace_with_text(node, value)
82
    else:
83
        for child in xml_dom.NodeElemIter(node): process(child)
(10-10/11)