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 term
8
import xml_dom
9

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

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

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

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

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

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

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

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

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

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

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

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