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
class FormatException(SyntaxException): pass
16

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

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

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

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

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

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

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

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

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

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

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