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 format
10
import maps
11
import strings
12
import term
13
import units
14
import util
15
import xml_dom
16
import xpath
17

    
18
##### Exceptions
19

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

    
25
class FormatException(SyntaxException): pass
26

    
27
##### Functions
28

    
29
funcs = {}
30

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

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

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

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

    
60
def pop_value(items):
61
    try: last = items.pop() # last entry contains value
62
    except IndexError: return None # input is empty and no actions
63
    if last[0] != 'value': return None # input is empty
64
    return last[1]
65

    
66
##### XML functions
67

    
68
# Function names must start with _ to avoid collisions with real tags
69
# Functions take arguments (items)
70

    
71
#### General
72

    
73
def _ignore(items):
74
    '''Used to "comment out" an XML subtree'''
75
    return None
76
funcs['_ignore'] = _ignore
77

    
78
#### Conditionals
79

    
80
def _eq(items):
81
    items = dict(items)
82
    try:
83
        left = items['left']
84
        right = items['right']
85
    except KeyError: return '' # a value was None
86
    return util.bool2str(left == right)
87
funcs['_eq'] = _eq
88

    
89
def _if(items):
90
    items = dict(items)
91
    try:
92
        cond = items['cond']
93
        then = items['then']
94
    except KeyError, e: raise SyntaxException(e)
95
    else_ = items.get('else', None)
96
    cond = bool(cast(strings.ustr, cond))
97
    if cond: return then
98
    else: return else_
99
funcs['_if'] = _if
100

    
101
#### Combining values
102

    
103
def _alt(items):
104
    items = list(items)
105
    items.sort()
106
    try: return items[0][1] # value of lowest-numbered item
107
    except IndexError: return None # input got removed by e.g. SyntaxException
108
funcs['_alt'] = _alt
109

    
110
def _merge(items):
111
    items = list(conv_items(strings.ustr, items))
112
        # get *once* from iter, check types
113
    items.sort()
114
    return maps.merge_values(*[v for k, v in items])
115
funcs['_merge'] = _merge
116

    
117
def _label(items):
118
    items = dict(conv_items(strings.ustr, items))
119
        # get *once* from iter, check types
120
    try:
121
        label = items['label']
122
        value = items['value']
123
    except KeyError, e: raise SyntaxException(e)
124
    return label+': '+value
125
funcs['_label'] = _label
126

    
127
#### Transforming values
128

    
129
types_by_name = {None: strings.ustr, 'str': strings.ustr, 'float': float}
130

    
131
def _nullIf(items):
132
    items = dict(conv_items(strings.ustr, items))
133
    try: null = items['null']
134
    except KeyError, e: raise SyntaxException(e)
135
    value = items.get('value', None)
136
    type_str = items.get('type', None)
137
    
138
    try: type_ = types_by_name[type_str]
139
    except KeyError, e: raise SyntaxException(e)
140
    null = type_(null)
141
    
142
    try: return util.none_if(value, null)
143
    except ValueError: return value # value not convertible, so can't equal null
144
funcs['_nullIf'] = _nullIf
145

    
146
def _map(items):
147
    '''Raises error if value not in map and no special '*' entry
148
    @param items
149
        <last_entry> Value
150
        <other_entries> name=value Mappings
151
            name "*" means all other input values
152
            value "*" means keep input value the same
153
            value "" means ignore input value
154
    '''
155
    items = conv_items(strings.ustr, items) # get *once* from iter, check types
156
    value = pop_value(items)
157
    if value == None: return None # input is empty
158
    map_ = dict(items)
159
    
160
    try: new_value = map_[value]
161
    except KeyError, e:
162
        # Save traceback right away in case another exception raised
163
        se = SyntaxException(e) 
164
        try: new_value = map_['*']
165
        except KeyError: raise se
166
    if new_value == '*': new_value = value # '*' means keep input value the same
167
    return util.none_if(new_value, u'') # empty map entry means None
168
funcs['_map'] = _map
169

    
170
def _replace(items):
171
    items = conv_items(strings.ustr, items) # get *once* from iter, check types
172
    value = pop_value(items)
173
    if value == None: return None # input is empty
174
    try:
175
        for repl, with_ in items:
176
            if re.match(r'^\w+$', repl):
177
                repl = r'(?<![^\W_])'+repl+r'(?![^\W_])' # match whole word
178
            value = re.sub(repl, with_, value)
179
    except sre_constants.error, e: raise SyntaxException(e)
180
    return util.none_if(value, u'') # empty strings always mean None
181
funcs['_replace'] = _replace
182

    
183
#### Quantities
184

    
185
def _units(items):
186
    items = conv_items(strings.ustr, items) # get *once* from iter, check types
187
    value = pop_value(items)
188
    if value == None: return None # input is empty
189
    
190
    quantity = units.str2quantity(value)
191
    try:
192
        for action, units_ in items:
193
            units_ = util.none_if(units_, u'')
194
            if action == 'default': units.set_default_units(quantity, units_)
195
            elif action == 'to':
196
                try: quantity = units.convert(quantity, units_)
197
                except ValueError, e: raise SyntaxException(e)
198
            else: raise SyntaxException(ValueError('Invalid action: '+action))
199
    except units.MissingUnitsException, e: raise SyntaxException(e)
200
    return units.quantity2str(quantity)
201
funcs['_units'] = _units
202

    
203
def parse_range(str_, range_sep='-'):
204
    default = (str_, None)
205
    start, sep, end = str_.partition(range_sep)
206
    if sep == '': return default # not a range
207
    if start == '' and range_sep == '-': return default # negative number
208
    return tuple(d.strip() for d in (start, end))
209

    
210
def _rangeStart(items):
211
    items = dict(conv_items(strings.ustr, items))
212
    try: value = items['value']
213
    except KeyError: return None # input is empty
214
    return parse_range(value)[0]
215
funcs['_rangeStart'] = _rangeStart
216

    
217
def _rangeEnd(items):
218
    items = dict(conv_items(strings.ustr, items))
219
    try: value = items['value']
220
    except KeyError: return None # input is empty
221
    return parse_range(value)[1]
222
funcs['_rangeEnd'] = _rangeEnd
223

    
224
def _range(items):
225
    items = dict(conv_items(float, items))
226
    from_ = items.get('from', None)
227
    to = items.get('to', None)
228
    if from_ == None or to == None: return None
229
    return str(to - from_)
230
funcs['_range'] = _range
231

    
232
def _avg(items):
233
    count = 0
234
    sum_ = 0.
235
    for name, value in conv_items(float, items):
236
        count += 1
237
        sum_ += value
238
    if count == 0: return None # input is empty
239
    else: return str(sum_/count)
240
funcs['_avg'] = _avg
241

    
242
class CvException(Exception):
243
    def __init__(self):
244
        Exception.__init__(self, 'CV (coefficient of variation) values are only'
245
            ' allowed for ratio scale data '
246
            '(see <http://en.wikipedia.org/wiki/Coefficient_of_variation>)')
247

    
248
def _noCV(items):
249
    try: name, value = items.next()
250
    except StopIteration: return None
251
    if re.match('^(?i)CV *\d+$', value): raise SyntaxException(CvException())
252
    return value
253
funcs['_noCV'] = _noCV
254

    
255
#### Dates
256

    
257
def _date(items):
258
    items = dict(conv_items(strings.ustr, items))
259
        # get *once* from iter, check types
260
    try: str_ = items['date']
261
    except KeyError:
262
        # Year is required
263
        try: items['year']
264
        except KeyError, e:
265
            if items == {}: return None # entire date is empty
266
            else: raise SyntaxException(e)
267
        
268
        # Convert month name to number
269
        try: month = items['month']
270
        except KeyError: pass
271
        else:
272
            if not month.isdigit(): # month is name
273
                try: items['month'] = str(dates.strtotime(month).month)
274
                except ValueError, e: raise SyntaxException(e)
275
        
276
        items = dict(conv_items(format.str2int, items.iteritems()))
277
        items.setdefault('month', 1)
278
        items.setdefault('day', 1)
279
        
280
        for try_num in xrange(2):
281
            try:
282
                date = datetime.date(**items)
283
                break
284
            except ValueError, e:
285
                if try_num > 0: raise SyntaxException(e)
286
                    # exception still raised after retry
287
                msg = strings.ustr(e)
288
                if msg == 'month must be in 1..12': # try swapping month and day
289
                    items['month'], items['day'] = items['day'], items['month']
290
                else: raise SyntaxException(e)
291
    else:
292
        try: year = float(str_)
293
        except ValueError:
294
            try: date = dates.strtotime(str_)
295
            except ImportError: return str_
296
            except ValueError, e: raise SyntaxException(e)
297
        else: date = (datetime.date(int(year), 1, 1) +
298
            datetime.timedelta(round((year % 1.)*365)))
299
    try: return dates.strftime('%Y-%m-%d', date)
300
    except ValueError, e: raise FormatException(e)
301
funcs['_date'] = _date
302

    
303
def _dateRangeStart(items):
304
    items = dict(conv_items(strings.ustr, items))
305
    try: value = items['value']
306
    except KeyError: return None # input is empty
307
    return dates.parse_date_range(value)[0]
308
funcs['_dateRangeStart'] = _dateRangeStart
309

    
310
def _dateRangeEnd(items):
311
    items = dict(conv_items(strings.ustr, items))
312
    try: value = items['value']
313
    except KeyError: return None # input is empty
314
    return dates.parse_date_range(value)[1]
315
funcs['_dateRangeEnd'] = _dateRangeEnd
316

    
317
#### Names
318

    
319
_name_parts_slices_items = [
320
    ('first', slice(None, 1)),
321
    ('middle', slice(1, -1)),
322
    ('last', slice(-1, None)),
323
]
324
name_parts_slices = dict(_name_parts_slices_items)
325
name_parts = [name for name, slice_ in _name_parts_slices_items]
326

    
327
def _name(items):
328
    items = dict(items)
329
    parts = []
330
    for part in name_parts:
331
        if part in items: parts.append(items[part])
332
    return ' '.join(parts)
333
funcs['_name'] = _name
334

    
335
def _namePart(items):
336
    out_items = []
337
    for part, value in items:
338
        try: slice_ = name_parts_slices[part]
339
        except KeyError, e: raise SyntaxException(e)
340
        out_items.append((part, ' '.join(value.split(' ')[slice_])))
341
    return _name(out_items)
342
funcs['_namePart'] = _namePart
343

    
344
#### Paths
345

    
346
def _simplifyPath(items):
347
    items = dict(items)
348
    try:
349
        next = cast(strings.ustr, items['next'])
350
        require = cast(strings.ustr, items['require'])
351
        root = items['path']
352
    except KeyError, e: raise SyntaxException(e)
353
    
354
    node = root
355
    while node != None:
356
        new_node = xpath.get_1(node, next, allow_rooted=False)
357
        if xpath.get_1(node, require, allow_rooted=False) == None: # empty elem
358
            xml_dom.replace(node, new_node) # remove current elem
359
            if node is root: root = new_node # also update root
360
        node = new_node
361
    return root
362
funcs['_simplifyPath'] = _simplifyPath
(17-17/19)