1 |
1341
|
aaronmk
|
# XPath "function" elements that transform their subpaths
|
2 |
|
|
|
3 |
1346
|
aaronmk
|
import util
|
4 |
1341
|
aaronmk
|
import xpath
|
5 |
|
|
|
6 |
|
|
##### Functions
|
7 |
|
|
|
8 |
|
|
funcs = {}
|
9 |
|
|
|
10 |
|
|
def process(path):
|
11 |
|
|
if path == []: return path
|
12 |
|
|
|
13 |
1482
|
aaronmk
|
# Process subpaths
|
14 |
1341
|
aaronmk
|
path[1:] = process(path[1:])
|
15 |
1482
|
aaronmk
|
branches = path[0].other_branches
|
16 |
|
|
for i, branch in enumerate(branches): branches[i] = process(branch)
|
17 |
|
|
|
18 |
1341
|
aaronmk
|
name = path[0].name
|
19 |
1343
|
aaronmk
|
if name.startswith('_') and name in funcs:
|
20 |
|
|
return funcs[name](path.pop(0).attrs, path)
|
21 |
1341
|
aaronmk
|
else: return path
|
22 |
|
|
|
23 |
|
|
#### XPath functions
|
24 |
|
|
|
25 |
|
|
# Function names must start with _ to avoid collisions with real tags
|
26 |
1343
|
aaronmk
|
# Functions take arguments (args, path)
|
27 |
1341
|
aaronmk
|
|
28 |
1346
|
aaronmk
|
def _forEach(args, path):
|
29 |
1351
|
aaronmk
|
'''Replaces '_val' in `do` with each item in the `in` list'''
|
30 |
|
|
in_, do = [a[0] for a in args]
|
31 |
|
|
assert in_.name == 'in'
|
32 |
|
|
assert do.name == 'do'
|
33 |
|
|
in_ = in_.attrs
|
34 |
|
|
do = do.value
|
35 |
1343
|
aaronmk
|
|
36 |
|
|
for_path = []
|
37 |
1351
|
aaronmk
|
for with_, in in_: for_path += xpath.parse(do.replace('_val', with_.name))
|
38 |
1343
|
aaronmk
|
return for_path + path
|
39 |
1346
|
aaronmk
|
funcs['_forEach'] = _forEach
|