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

    
11
class SyntaxException(Exception):
12
    def __init__(self, cause):
13
        Exception.__init__(self, 'Invalid XML function syntax: '
14
            +exc.str_(cause))
15

    
16
class FormatException(SyntaxException): pass
17

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

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

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

    
32
def merge(items):
33
    items = list(items)
34
    items.sort()
35
    return maps.merge_values(*[v for k, v in items])
36

    
37
def label(items):
38
    items = dict(conv_items(str, items)) # get *once* from iter and check types
39
    try:
40
        label = items['label']
41
        value = items['value']
42
    except KeyError, e: raise SyntaxException(e)
43
    return label+': '+value
44

    
45
def range_(items):
46
    items = dict(conv_items(float, items))
47
    from_ = items.get('from', None)
48
    to = items.get('to', None)
49
    if from_ == None or to == None: return None
50
    return str(to - from_)
51

    
52
def avg(items):
53
    count = 0
54
    sum_ = 0.
55
    for name, value in conv_items(float, items):
56
        count += 1
57
        sum_ += value
58
    return str(sum_/count)
59

    
60
def date(items):
61
    items = conv_items(str, items) # get *once* from iter and check types
62
    try: str_ = dict(items)['date']
63
    except KeyError:
64
        items = dict(filter(lambda (k, v): v != 0, conv_items(int, items)))
65
        items.setdefault('year', 1900)
66
        items.setdefault('month', 1)
67
        items.setdefault('day', 1)
68
        try: date = datetime.date(**items)
69
        except ValueError, e: raise SyntaxException(e)
70
    else:
71
        try: year = float(str_)
72
        except ValueError:
73
            try: import dateutil.parser
74
            except ImportError: return str_
75
            try: date = dateutil.parser.parse(str_)
76
            except ValueError, e: raise SyntaxException(e)
77
        else: date = (datetime.date(int(year), 1, 1) +
78
            datetime.timedelta(round((year % 1.)*365)))
79
    try: return dates.strftime('%Y-%m-%d', date)
80
    except ValueError, e: raise FormatException(e)
81

    
82
_name_parts_slices_items = [
83
    ('first', slice(None, 1)),
84
    ('middle', slice(1, -1)),
85
    ('last', slice(-1, None)),
86
]
87
name_parts_slices = dict(_name_parts_slices_items)
88
name_parts = [name for name, slice_ in _name_parts_slices_items]
89

    
90
def name(items):
91
    items = dict(items)
92
    parts = []
93
    for part in name_parts:
94
        if part in items: parts.append(items[part])
95
    return ' '.join(parts)
96

    
97
def name_part(items):
98
    out_items = []
99
    for part, value in items:
100
        try: slice_ = name_parts_slices[part]
101
        except KeyError, e: raise SyntaxException(e)
102
        else: out_items.append((part, ' '.join(value.split(' ')[slice_])))
103
    return name(out_items)
104

    
105
# Function names must start with _ to avoid collisions with real tags
106
# Functions take arguments (items)
107
funcs = {'_alt': alt, '_merge': merge, '_label': label, '_range': range_,
108
    '_avg': avg, '_date': date, '_name': name, '_namePart': name_part}
109

    
110
def process(node, on_error=exc.raise_):
111
    for child in xml_dom.NodeElemIter(node): process(child, on_error)
112
    name = node.tagName
113
    if name.startswith('_') and name in funcs:
114
        try: value = funcs[name](xml_dom.NodeTextEntryIter(node))
115
        except SyntaxException, e:
116
            str_ = str(node)
117
            exc.add_msg(e, 'function:\n'+str_)
118
            xml_dom.replace(node, node.ownerDocument.createComment(
119
                '\n'+term.emph_multiline(str_)))
120
            on_error(e)
121
        else: xml_dom.replace_with_text(node, value)
(13-13/14)