Project

General

Profile

1
# XML "function" nodes that transform their contents
2

    
3
import datetime
4
import re
5
import sre_constants
6

    
7
import dates
8
import exc
9
import maps
10
import strings
11
import term
12
import units
13
import util
14
import xml_dom
15
import xpath
16

    
17
##### Exceptions
18

    
19
class SyntaxException(Exception):
20
    def __init__(self, cause):
21
        Exception.__init__(self, 'Invalid XML function syntax: '
22
            +exc.str_(cause))
23

    
24
class FormatException(SyntaxException): pass
25

    
26
##### Functions
27

    
28
funcs = {}
29

    
30
def process(node, on_error=exc.raise_):
31
    for child in xml_dom.NodeElemIter(node): process(child, on_error)
32
    name = node.tagName
33
    if name.startswith('_') and name in funcs:
34
        try:
35
            value = funcs[name](xml_dom.NodeTextEntryIter(node))
36
            xml_dom.replace_with_text(node, value)
37
        except Exception, e: # also catch XML func internal errors
38
            # Save in case another exception raised, overwriting sys.exc_info()
39
            exc.add_traceback(e)
40
            str_ = str(node)
41
            exc.add_msg(e, 'function:\n'+str_)
42
            xml_dom.replace(node, node.ownerDocument.createComment(
43
                '\n'+term.emph_multiline(str_).replace('--','-')))
44
                # comments can't contain '--'
45
            on_error(e)
46

    
47
def map_items(func, items):
48
    return [(name, func(value)) for name, value in items]
49

    
50
def cast(type_, val):
51
    '''Throws SyntaxException if can't cast'''
52
    try: return type_(val)
53
    except ValueError, e: raise SyntaxException(e)
54

    
55
def conv_items(type_, items):
56
    return map_items(lambda val: cast(type_, val),
57
        xml_dom.TextEntryOnlyIter(items))
58

    
59
##### XML functions
60

    
61
# Function names must start with _ to avoid collisions with real tags
62
# Functions take arguments (items)
63

    
64
#### General
65

    
66
def _ignore(items):
67
    '''Used to "comment out" an XML subtree'''
68
    return None
69
funcs['_ignore'] = _ignore
70

    
71
#### Conditionals
72

    
73
def _eq(items):
74
    items = dict(items)
75
    try:
76
        left = items['left']
77
        right = items['right']
78
    except KeyError: return '' # a value was None
79
    return util.bool2str(left == right)
80
funcs['_eq'] = _eq
81

    
82
def _if(items):
83
    items = dict(items)
84
    try:
85
        cond = items['cond']
86
        then = items['then']
87
    except KeyError, e: raise SyntaxException(e)
88
    else_ = items.get('else', None)
89
    cond = bool(cast(str, cond))
90
    if cond: return then
91
    else: return else_
92
funcs['_if'] = _if
93

    
94
#### Combining values
95

    
96
def _alt(items):
97
    items = list(items)
98
    items.sort()
99
    try: return items[0][1] # value of lowest-numbered item
100
    except IndexError: return None # input got removed by e.g. SyntaxException
101
funcs['_alt'] = _alt
102

    
103
def _merge(items):
104
    items = list(conv_items(strings.ustr, items))
105
        # get *once* from iter and check types
106
    items.sort()
107
    return maps.merge_values(*[v for k, v in items])
108
funcs['_merge'] = _merge
109

    
110
def _label(items):
111
    items = dict(conv_items(strings.ustr, items))
112
        # get *once* from iter and check types
113
    try:
114
        label = items['label']
115
        value = items['value']
116
    except KeyError, e: raise SyntaxException(e)
117
    return label+': '+value
118
funcs['_label'] = _label
119

    
120
#### Transforming values
121

    
122
def _nullIf(items):
123
    items = dict(conv_items(str, items))
124
    try:
125
        null = items['null']
126
        value = items['value']
127
    except KeyError, e: raise SyntaxException(e)
128
    type_str = items.get('type', None)
129
    type_ = str
130
    if type_str == 'float': type_ = float
131
    return util.none_if(value, type_(null))
132
funcs['_nullIf'] = _nullIf
133

    
134
def _map(items):
135
    items = conv_items(str, items) # get *once* from iter and check types
136
    try: value = items.pop()[1] # last entry contains value
137
    except IndexError, e: raise SyntaxException(e)
138
    map_ = dict(items)
139
    closed = bool(map_.pop('_closed', False))
140
    try: return map_[value]
141
    except KeyError, e:
142
        if closed: raise SyntaxException(e)
143
        else: return value
144
funcs['_map'] = _map
145

    
146
def _replace(items):
147
    items = conv_items(str, items) # get *once* from iter and check types
148
    try: value = items.pop()[1] # last entry contains value
149
    except IndexError, e: raise SyntaxException(e)
150
    try:
151
        for repl, with_ in items:
152
            if re.match(r'^\w+$', repl):
153
                repl = r'(?<![^\W_])'+repl+r'(?![^\W_])' # match whole word
154
            value = re.sub(repl, with_, value)
155
    except sre_constants.error, e: raise SyntaxException(e)
156
    return util.none_if(value, u'') # empty strings always mean None
157
funcs['_replace'] = _replace
158

    
159
#### Quantities
160

    
161
def _units(items):
162
    items = conv_items(str, items) # get *once* from iter and check types
163
    try: last = items.pop() # last entry contains value
164
    except IndexError: return None # input is empty and no actions
165
    if last[0] != 'value': return None # input is empty
166
    str_ = last[1]
167
    
168
    quantity = units.str2quantity(str_)
169
    try:
170
        for action, units_ in items:
171
            units_ = util.none_if(units_, u'')
172
            if action == 'default': units.set_default_units(quantity, units_)
173
            elif action == 'to': quantity = units.convert(quantity, units_)
174
            else: raise SyntaxException(ValueError('Invalid action: '+action))
175
    except units.MissingUnitsException, e: raise SyntaxException(e)
176
    return units.quantity2str(quantity)
177
funcs['_units'] = _units
178

    
179
def _range(items):
180
    items = dict(conv_items(float, items))
181
    from_ = items.get('from', None)
182
    to = items.get('to', None)
183
    if from_ == None or to == None: return None
184
    return str(to - from_)
185
funcs['_range'] = _range
186

    
187
def parse_range(str_, range_sep='-'):
188
    default = (str_, None)
189
    start, sep, end = str_.partition(range_sep)
190
    if sep == '': return default # not a range
191
    if start == '' and range_sep == '-': return default # negative number
192
    return tuple(d.strip() for d in (start, end))
193

    
194
def _rangeStart(items):
195
    items = dict(conv_items(str, items))
196
    try: value = items['value']
197
    except KeyError: return None # input is empty
198
    return parse_range(value)[0]
199
funcs['_rangeStart'] = _rangeStart
200

    
201
def _rangeEnd(items):
202
    items = dict(conv_items(str, items))
203
    try: value = items['value']
204
    except KeyError: return None # input is empty
205
    return parse_range(value)[1]
206
funcs['_rangeEnd'] = _rangeEnd
207

    
208
def _avg(items):
209
    count = 0
210
    sum_ = 0.
211
    for name, value in conv_items(float, items):
212
        count += 1
213
        sum_ += value
214
    return str(sum_/count)
215
funcs['_avg'] = _avg
216

    
217
class CvException(Exception):
218
    def __init__(self):
219
        Exception.__init__(self, 'CV (coefficient of variation) values are only'
220
            ' allowed for ratio scale data '
221
            '(see <http://en.wikipedia.org/wiki/Coefficient_of_variation>)')
222

    
223
def _noCV(items):
224
    try: name, value = items.next()
225
    except StopIteration: return None
226
    if re.match('^(?i)CV *\d+$', value): raise SyntaxException(CvException())
227
    return value
228
funcs['_noCV'] = _noCV
229

    
230
#### Dates
231

    
232
def _date(items):
233
    items = conv_items(str, items) # get *once* from iter and check types
234
    try: str_ = dict(items)['date']
235
    except KeyError:
236
        items = dict(conv_items(int, items))
237
        try: items['year'] # year is required
238
        except KeyError, e:
239
            if items == {}: return None # entire date is empty
240
            else: raise SyntaxException(e)
241
        items.setdefault('month', 1)
242
        items.setdefault('day', 1)
243
        try: date = datetime.date(**items)
244
        except ValueError, e: raise SyntaxException(e)
245
    else:
246
        try: year = float(str_)
247
        except ValueError:
248
            try: date = dates.strtotime(str_)
249
            except ImportError: return str_
250
            except ValueError, e: raise SyntaxException(e)
251
        else: date = (datetime.date(int(year), 1, 1) +
252
            datetime.timedelta(round((year % 1.)*365)))
253
    try: return dates.strftime('%Y-%m-%d', date)
254
    except ValueError, e: raise FormatException(e)
255
funcs['_date'] = _date
256

    
257
def _dateRangeStart(items):
258
    items = dict(conv_items(str, items))
259
    try: value = items['value']
260
    except KeyError: return None # input is empty
261
    return dates.parse_date_range(value)[0]
262
funcs['_dateRangeStart'] = _dateRangeStart
263

    
264
def _dateRangeEnd(items):
265
    items = dict(conv_items(str, items))
266
    try: value = items['value']
267
    except KeyError: return None # input is empty
268
    return dates.parse_date_range(value)[1]
269
funcs['_dateRangeEnd'] = _dateRangeEnd
270

    
271
#### Names
272

    
273
_name_parts_slices_items = [
274
    ('first', slice(None, 1)),
275
    ('middle', slice(1, -1)),
276
    ('last', slice(-1, None)),
277
]
278
name_parts_slices = dict(_name_parts_slices_items)
279
name_parts = [name for name, slice_ in _name_parts_slices_items]
280

    
281
def _name(items):
282
    items = dict(items)
283
    parts = []
284
    for part in name_parts:
285
        if part in items: parts.append(items[part])
286
    return ' '.join(parts)
287
funcs['_name'] = _name
288

    
289
def _namePart(items):
290
    out_items = []
291
    for part, value in items:
292
        try: slice_ = name_parts_slices[part]
293
        except KeyError, e: raise SyntaxException(e)
294
        out_items.append((part, ' '.join(value.split(' ')[slice_])))
295
    return _name(out_items)
296
funcs['_namePart'] = _namePart
297

    
298
#### Paths
299

    
300
def _simplifyPath(items):
301
    items = dict(items)
302
    try:
303
        next = cast(str, items['next'])
304
        require = cast(str, items['require'])
305
        root = items['path']
306
    except KeyError, e: raise SyntaxException(e)
307
    
308
    node = root
309
    while node != None:
310
        new_node = xpath.get_1(node, next, allow_rooted=False)
311
        if xpath.get_1(node, require, allow_rooted=False) == None: # empty elem
312
            xml_dom.replace(node, new_node) # remove current elem
313
            if node is root: root = new_node # also update root
314
        node = new_node
315
    return root
316
funcs['_simplifyPath'] = _simplifyPath
(17-17/19)