/
env.py
476 lines (369 loc) · 12.6 KB
/
env.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
from __future__ import unicode_literals, print_function, absolute_import, division, generators, nested_scopes
import hashlib
from datetime import datetime
import operator
import pytz
import six
from itertools import chain
from jsonpath_rw import jsonpath
from jsonpath_rw.parser import parse as parse_jsonpath
from commcare_export.misc import unwrap, unwrap_val
from commcare_export.repeatable_iterator import RepeatableIterator
JSONPATH_CACHE = {}
class CannotBind(Exception): pass
class CannotReplace(Exception): pass
class CannotEmit(Exception): pass
class NotFound(Exception): pass
class Env(object):
"""
An abstract model of an "environment" where data can be bound to
names and later looked up. Not simply a dictionary as lookup in our
case may support JsonPath, or may be a chaining of other
environments, so the abstract interface will
allow experimentation and customization.
"""
#
# Interface
#
def bind(self, name, value):
"""
(key, ??) -> Env
Returns a new environment that is equivalent
to the current except the provided key is
bound to the value passed in. If the environment
does not support such a binding, raises
CannotBind
"""
raise NotImplementedError()
def lookup(self, key):
"""
key -> ??
Note that the ?? may be None which may mean
the value was unbound or may mean it was
found and was None. This may need revisiting.
This may also raise NotFound if it is the
sort of environment that does that.
"""
raise NotImplementedError()
def replace(self, data):
"""
data -> Env
Completely replace the environment with new
data (somewhat like "this"-based Map functions a la jQuery).
Could be the same as creating a new empty env
and binding "@" in JsonPath.
May raise CannotReplace if this environment does
not support the input replacement
"""
raise NotImplementedError()
# Minor impurity of the idea of a binding env:
# also allow `Emit` to directly call into
# the environment. It is up to the env
# whether to store it, write it immediately,
# or do something clever with iterators, etc.
def emit_table(self, table_spec):
raise CannotEmit()
def has_emitted_tables(self):
return False
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
pass
#
# Fluent interface to combinators
#
def __or__(self, other):
return OrElse(self, other)
#
# Combinators
#
class OrElse(Env):
"""
An environment that chains together a left environment
and a right environment. Note that this differes from
just a bunch of bindings, as the two envs might have
entirely different mechanisms (for example a magic
environment for special operators vs a JsonPathEnv
that always returns a list and operates only on
simple data)
"""
def __init__(self, left, right):
self.left = left
self.right = right
def bind(self, name, value):
try: return OrElse(self.left.bind(name, value), self.right)
except CannotBind: return OrElse(self.left, self.right.bind(name, value))
def lookup(self, name):
try: return self.left.lookup(name)
except NotFound: return self.right.lookup(name)
def replace(self, data):
# A bit sketchy...
try: return OrElse(self.left.replace(data), self.right)
except CannotReplace: return OrElse(self.left, self.right.replace(data))
def emit_table(self, table_spec):
try: return self.left.emit_table(table_spec)
except CannotEmit: return self.right.emit_table(table_spec)
def has_emitted_tables(self):
return any([self.left.has_emitted_tables(), self.right.has_emitted_tables()])
def __enter__(self):
self.left.__enter__()
self.right.__enter__()
def __exit__(self, exc_type, exc_val, exc_tb):
try:
self.left.__exit__(exc_type, exc_val, exc_tb)
finally:
self.right.__exit__(exc_type, exc_val, exc_tb)
#
# Concrete environment classes
#
class DictEnv(Env):
"""
A simple dictionary environment; more-or-less boring!
"""
def __init__(self, d=None):
self.d = d or {}
def bind(self, name, value):
return DictEnv(dict(list(self.d.items()) + [(name, value)]))
def lookup(self, name):
try: return self.d[name]
except KeyError: raise NotFound(unwrap_val(name))
def replace(self, data):
if isinstance(data, dict): return DictEnv(data)
else: raise CannotReplace()
class JsonPathEnv(Env):
"""
An environment like those that map names
to variables, but supporting dereferencing
an JsonPath expression. Note that it never
fails a lookup, but always returns an empty
list.
It also interns all parsed expressions
"""
def __init__(self, bindings=None):
self.__bindings = bindings or {}
# Currently hardcoded because it is a global is jsonpath-rw
# Probably not widely used, but will require refactor if so
jsonpath.auto_id_field = "id"
def parse(self, jsonpath_string):
if jsonpath_string not in JSONPATH_CACHE:
JSONPATH_CACHE[jsonpath_string] = parse_jsonpath(jsonpath_string)
return JSONPATH_CACHE[jsonpath_string]
def lookup(self, name):
"str|JsonPath -> ??"
if isinstance(name, six.string_types):
jsonpath_expr = self.parse(name)
elif isinstance(name, jsonpath.JSONPath):
jsonpath_expr = name
else:
raise NotFound(unwrap_val(name))
def iter(jsonpath_expr=jsonpath_expr): # Capture closure
for datum in jsonpath_expr.find(self.__bindings):
# HACK: The auto id from jsonpath_rw is good, but we lose it when we do .value here,
# so just slap it on if not present
if isinstance(datum.value, dict) and 'id' not in datum.value:
datum.value['id'] = jsonpath.AutoIdForDatum(datum).value
yield datum
return RepeatableIterator(iter)
def bind(self, *args):
"(str, ??) -> Env | ({str: ??}) -> Env"
new_bindings = dict(self.__bindings)
if isinstance(args[0], dict):
new_bindings.update(args[0])
return self.__class__(new_bindings)
elif isinstance(args[0], six.string_types):
new_bindings[args[0]] = args[1]
return self.__class__(new_bindings)
else:
raise ValueError('Bad args to Env.bind')
def replace(self, data):
return self.__class__(data)
#
# Actual concrete environments, basically with built-in functions.
#
def _not_val(val):
return val is None or val == []
def _to_unicode(val):
if isinstance(val, bytes):
return val.decode('utf8')
elif not isinstance(val, six.text_type):
return six.text_type(val)
return val
@unwrap('val')
def str2bool(val):
if _not_val(val):
return False
if isinstance(val, bool):
return val
val = _to_unicode(val)
return bool(val) and val.lower() in {'true', 't', '1'}
@unwrap('val')
def str2num(val):
if _not_val(val):
return None
try:
return int(val)
except ValueError:
try:
return float(val)
except ValueError:
return None
@unwrap('val')
def str2date(val):
import dateutil.parser as parser
if not val:
return None
val = _to_unicode(val)
try:
date = parser.parse(val)
except ValueError:
return
if date.tzinfo is not None:
try:
date = date.astimezone(pytz.utc)
except ValueError:
pass
return date.replace(microsecond=0, tzinfo=None)
@unwrap('val')
def bool2int(val):
return int(str2bool(val))
@unwrap('val')
def sha1(val):
if _not_val(val):
return None
if not isinstance(val, bytes):
val = six.text_type(val).encode('utf8')
return hashlib.sha1(val).hexdigest()
@unwrap('val')
def selected_at(val, index):
if not val:
return None
try:
index = int(index)
except ValueError:
return "Error: index must be an integer"
val = _to_unicode(val)
try:
return val.split()[index]
except (IndexError, ValueError):
return None
@unwrap('val')
def selected(val, reference):
if not val:
return None
val = _to_unicode(val)
parts = val.split()
return reference in parts
@unwrap('val')
def count_selected(val):
if not val:
return None
val = _to_unicode(val)
return len(val.split())
def join(*args):
args = [unwrap_val(arg)for arg in args]
try:
return args[0].join(args[1:])
except TypeError:
return '""'
@unwrap('val')
def default(val, default_val):
if not val:
return default_val
return val
@unwrap('val')
def attachment_url(val):
if not val:
return None
from commcare_export.minilinq import Apply, Reference, Literal
return Apply(
Reference('template'),
Literal('{}/a/{}/api/form/attachment/{}/{}'),
Reference('commcarehq_base_url'),
Reference('$.domain'),
Reference('$.id'),
Literal(val)
)
def template(format_template, *args):
args = [unwrap_val(arg) for arg in args]
return format_template.format(*args)
def _or(*args):
unwrapped_args = (unwrap_val(arg) for arg in args)
vals = (val for val in unwrapped_args if val is not None and val != [])
try:
return next(vals)
except StopIteration:
pass
class BuiltInEnv(DictEnv):
"""
A built-in environment of operators and functions
which does not support replacement or bindings.
For convenience, this environment has been chosen to
queue up tables to be written out, since it will be
the first env involved in almost any situation.
"""
def __init__(self, d=None):
self.__tables = []
d = d or {}
d.update({
'+': operator.__add__,
'-': operator.__sub__,
'*': operator.__mul__,
'//': operator.__floordiv__,
'/': operator.__truediv__,
'>': operator.__gt__,
'>=': operator.__ge__,
'<': operator.__lt__,
'<=': operator.__le__,
'len': len,
'bool': bool,
'str2bool': str2bool,
'bool2int': bool2int,
'str2num': str2num,
'str2date': str2date,
'selected': selected,
'selected-at': selected_at,
'count-selected': count_selected,
'join': join,
'default': default,
'template': template,
'attachment_url': attachment_url,
'filter_empty': _not_val,
'or': _or,
'sha1': sha1,
})
return super(BuiltInEnv, self).__init__(d)
def bind(self, name, value): raise CannotBind()
def replace(self, data): raise CannotReplace()
class EmitterEnv(Env):
def __init__(self, writer):
self.writer = writer
self.emitted = False
def __enter__(self):
self.writer.__enter__()
def __exit__(self, exc_type, exc_val, exc_tb):
self.writer.__exit__(exc_type, exc_val, exc_tb)
def bind(self, name, value): raise CannotBind()
def replace(self, data): raise CannotReplace()
def lookup(self, key): raise NotFound()
def emit_table(self, table_spec):
self.emitted = True
table_spec.rows = self._unwrap_row_vals(table_spec.rows)
self.writer.write_table(table_spec)
def has_emitted_tables(self):
return self.emitted
@staticmethod
def _unwrap_row_vals(rows):
"""The XMLtoJSON conversion in CommCare can result in a field being a JSON object
instead of a simple field (if the XML tag has attributes or different namespace from
the default). In this case the actual value of the XML element is stored in a '#text' field.
"""
def _unwrap_val(val):
if isinstance(val, dict):
if '#text' in val:
return val.get('#text')
elif all(key == 'id' or key.startswith('@') for key in val):
# this implies the XML element was empty since all keys are from attributes
return ''
return val
for row in rows:
yield [_unwrap_val(val) for val in row]