Project

General

Profile

1 55 aaronmk
# XPath parsing
2 21 aaronmk
3 55 aaronmk
import copy
4 1009 aaronmk
import warnings
5 21 aaronmk
6
from Parser import Parser
7 892 aaronmk
import util
8 77 aaronmk
import xml_dom
9 1342 aaronmk
import xpath_func
10 21 aaronmk
11 1001 aaronmk
##### Path elements
12
13 21 aaronmk
class XpathElem:
14 1002 aaronmk
    def __init__(self, name='', value=None, is_attr=False):
15 21 aaronmk
        self.name = name
16
        self.value = value
17
        self.is_attr = is_attr
18 97 aaronmk
        self.is_positive = True
19 1238 aaronmk
        self.is_lookup_only = False
20 94 aaronmk
        self.is_ptr = False
21
        self.keys = []
22
        self.attrs = []
23 78 aaronmk
        self.other_branches = [] # temp implementation for split paths
24 21 aaronmk
25
    def __repr__(self):
26
        str_ = ''
27 141 aaronmk
        if not self.is_positive: str_ += '!'
28 21 aaronmk
        if self.is_attr: str_ += '@'
29 1004 aaronmk
        if self.name == '': str_ += '""'
30
        else: str_ += self.name
31 1238 aaronmk
        if self.is_lookup_only: str_ += '?'
32 94 aaronmk
        if self.keys != []: str_ += repr(self.keys)
33
        if self.attrs != []: str_ += ':'+repr(self.attrs)
34
        if self.is_ptr: str_ += '->'
35
        if self.other_branches != []: str_ += '{'+repr(self.other_branches)+'}'
36 25 aaronmk
        if self.value != None: str_ += '='+repr(self.value)
37 21 aaronmk
        return str_
38
39
    def __eq__(self, other): return self.__dict__ == other.__dict__
40
41 1002 aaronmk
empty_elem = XpathElem()
42
43
def elem_is_empty(elem): return elem == empty_elem
44
45 1004 aaronmk
def is_self(elem): return elem.name == '' or elem.name == '.'
46
47
def is_parent(elem): return elem.name == '..'
48
49 1001 aaronmk
##### Paths
50
51 99 aaronmk
def is_positive(path): return path[0].is_positive
52
53 1003 aaronmk
def is_rooted(path): return elem_is_empty(path[0])
54
55 24 aaronmk
def value(path): return path[-1].value
56
57 1294 aaronmk
def set_value(path, value):
58
    '''Caller must make a shallow copy of the path to prevent modifications from
59
    propagating to other copies of the path (a deep copy is not needed)'''
60
    path[-1] = copy.copy(path[-1]) # don't modify other copies of the path
61
    path[-1].value = value
62 22 aaronmk
63 32 aaronmk
def backward_id(elem):
64 171 aaronmk
    if len(elem.keys) >= 1 and value(elem.keys[0]) == None: return elem.keys[0]
65 32 aaronmk
    else: return None
66
67 1001 aaronmk
instance_level = 1 # root's grandchildren
68
69
def obj(path):
70
    obj_path = copy.deepcopy(path[:instance_level+1])
71
    obj_path[-1].is_ptr = False # prevent pointer w/o target
72
    return obj_path
73
74
def set_id(path, id_, has_types=True):
75 1294 aaronmk
    '''Caller must make a shallow copy of the path to prevent modifications from
76
    propagating to other copies of the path (a deep copy is not needed)'''
77 1001 aaronmk
    if has_types: id_level = instance_level
78
    else: id_level = 0 # root's children
79 1004 aaronmk
    if is_self(path[0]): id_level += 1 # explicit root element
80 1294 aaronmk
81
    id_elem = path[id_level] = copy.copy(path[id_level])
82
        # don't modify other copies of the path
83
    id_elem.keys = id_elem.keys[:] # don't modify other copies of the elem
84
    id_elem.keys.append([XpathElem('id', id_, True)])
85 1001 aaronmk
86
def is_id(path): return path[0].is_attr and path[0].name == 'id'
87
88 1070 aaronmk
def is_instance(elem): return elem.keys != [] and is_id(elem.keys[0])
89 1001 aaronmk
90
##### Parsing
91
92 170 aaronmk
def expand_abbr(name, repl):
93
    before, abbr, after = name.partition('*')
94
    if abbr != '': name = before+repl+after
95
    return name
96
97 154 aaronmk
_cache = {}
98
99 76 aaronmk
def parse(str_):
100 154 aaronmk
    try: return _cache[str_]
101
    except KeyError: pass
102
103 76 aaronmk
    parser = Parser(str_)
104 21 aaronmk
105 76 aaronmk
    def _path():
106 97 aaronmk
        is_positive = not parser.str_('!')
107
108 21 aaronmk
        tree = []
109
        while True:
110 38 aaronmk
            # Split path
111 76 aaronmk
            if parser.str_('{'):
112 1070 aaronmk
                last = tree[-1]
113
                last.other_branches = _paths()
114 76 aaronmk
                parser.str_('}', required=True)
115 1070 aaronmk
                if parser.str_('/'): # common subpath after {}
116
                    subpath = _path()
117
                    for branch in last.other_branches: branch += subpath
118
                tree += last.other_branches.pop(0) # use first path for now
119
                break # anything after split path has already been parsed
120 36 aaronmk
121 754 aaronmk
            elem = XpathElem(is_attr=parser.str_('@'), name=_value())
122 38 aaronmk
123 1238 aaronmk
            elem.is_lookup_only = parser.str_('?')
124
125 94 aaronmk
            # Keys used to match nodes
126 76 aaronmk
            if parser.str_('['):
127 94 aaronmk
                elem.keys = _paths()
128 76 aaronmk
                parser.str_(']', required=True)
129 36 aaronmk
130 94 aaronmk
            # Attrs created when no matching node exists
131
            if parser.str_(':'):
132
                parser.str_('[', required=True)
133
                elem.attrs = _paths()
134
                parser.str_(']', required=True)
135
136 76 aaronmk
            elem.is_ptr = parser.str_('->')
137 21 aaronmk
            tree.append(elem)
138 36 aaronmk
139
            # Lookahead assertion
140 76 aaronmk
            if parser.str_('('):
141
                parser.str_('/', required=True) # next / is inside ()
142
                path = _path()
143
                parser.str_(')', required=True)
144 94 aaronmk
                elem.keys.append(path)
145 36 aaronmk
                tree += path
146
147 76 aaronmk
            if not parser.str_('/'): break
148 32 aaronmk
149 97 aaronmk
        tree[0].is_positive = is_positive
150
151
        # Value
152 997 aaronmk
        if parser.str_('='):
153 1009 aaronmk
            if parser.str_('$'): # reference (different from a pointer)
154
                value = _path()
155
            else: value = _value() # literal value
156 997 aaronmk
            set_value(tree, value)
157 85 aaronmk
158 32 aaronmk
        # Expand * abbrs
159 70 aaronmk
        for i in reversed(xrange(len(tree))):
160
            elem = tree[i]
161 171 aaronmk
            if elem.is_ptr: offset = 2
162 32 aaronmk
            else: offset = 1
163 170 aaronmk
            try: repl = tree[i+offset].name
164 171 aaronmk
            except IndexError: pass # no replacement elem
165
            else: elem.name = expand_abbr(elem.name, repl)
166 32 aaronmk
167 21 aaronmk
        return tree
168 76 aaronmk
169 754 aaronmk
    def _value():
170
        if parser.str_('"'):
171
            value = parser.re(r'[^"]*')
172
            parser.str_('"', required=True)
173
        else: value = parser.re(r'(?:(?:\w+:)*[\w.*]+)?')
174
        return value
175
176 94 aaronmk
    def _paths():
177
        paths = []
178
        while True:
179
            paths.append(_path())
180
            if not parser.str_(','): break
181
        return paths
182
183 76 aaronmk
    path = _path()
184
    parser.end()
185 1342 aaronmk
    path = xpath_func.process(path)
186 154 aaronmk
    _cache[str_] = path
187 76 aaronmk
    return path
188 21 aaronmk
189 1001 aaronmk
##### Querying/creating XML trees
190 22 aaronmk
191 1005 aaronmk
def get(root, xpath, create=False, last_only=None, limit=1, allow_rooted=True):
192 141 aaronmk
    '''Warning: The last_only optimization may put data that should be together
193
    into separate nodes'''
194 77 aaronmk
    if last_only == None: last_only = create
195 887 aaronmk
    if limit == None or limit > 1: last_only = False
196 892 aaronmk
    if util.is_str(xpath): xpath = parse(xpath)
197 99 aaronmk
198 1005 aaronmk
    # Handle edge cases
199 998 aaronmk
    if xpath == []: return [root]
200 886 aaronmk
    if create and not is_positive(xpath): return []
201 1005 aaronmk
202
    # Define vars
203 998 aaronmk
    doc = root.ownerDocument
204 1005 aaronmk
    if allow_rooted and is_rooted(xpath): root = doc.documentElement
205 165 aaronmk
    elem = xpath[0]
206
207
    # Find possible matches
208
    children = []
209
    if elem.is_attr:
210 998 aaronmk
        child = root.getAttributeNode(elem.name)
211 165 aaronmk
        if child != None: children = [child]
212 1004 aaronmk
    elif is_self(elem): children = [root]
213
    elif is_parent(elem):
214 1000 aaronmk
        parent = xml_dom.parent(root)
215 1013 aaronmk
        if parent == None: return [] # don't try to create doc root's parent
216
        root = parent
217
        children = [root]
218 165 aaronmk
    else:
219 998 aaronmk
        children = xml_dom.by_tag_name(root, elem.name,
220 1013 aaronmk
            last_only and (elem.keys == [] or is_instance(elem)))
221 165 aaronmk
222 1009 aaronmk
    # Retrieve elem value
223
    value_ = elem.value
224
    if util.is_list(value_): # reference (different from a pointer)
225
        targets = get(root, value_)
226
        try: target = targets[0]
227
        except IndexError:
228
            warnings.warn(UserWarning('XPath reference target missing: '
229
                +str(value_)+'\nXPath: '+str(xpath)))
230
            value_ = None
231
        else: value_ = xml_dom.value(target)
232
233 165 aaronmk
    # Check each match
234 885 aaronmk
    nodes = []
235 165 aaronmk
    for child in children:
236 1009 aaronmk
        is_match = value_ == None or xml_dom.value(child) == value_
237 165 aaronmk
        for attr in elem.keys:
238
            if not is_match: break
239 1011 aaronmk
            is_match = ((get(child, attr, False, last_only,
240
                allow_rooted=False) != []) == is_positive(attr))
241 885 aaronmk
        if is_match:
242
            nodes.append(child)
243
            if limit != None and len(nodes) >= limit: break
244 165 aaronmk
245
    # Create node
246 886 aaronmk
    if nodes == []:
247 1239 aaronmk
        if not create or elem.is_lookup_only: return []
248 77 aaronmk
        if elem.is_attr:
249 998 aaronmk
            root.setAttribute(elem.name, '')
250
            node = root.getAttributeNode(elem.name)
251 1013 aaronmk
        elif util.list_eq_is(children, [root]): node = root
252 998 aaronmk
        else: node = root.appendChild(doc.createElement(elem.name))
253 1009 aaronmk
        if value_ != None: xml_dom.set_value(node, value_)
254 886 aaronmk
        nodes.append(node)
255 165 aaronmk
256 1009 aaronmk
    path_value = value(xpath)
257 165 aaronmk
    xpath = xpath[1:] # rest of XPath
258
259 886 aaronmk
    next = []
260
    for node in nodes:
261
        # Create attrs
262
        if create:
263
            for attr in elem.keys + elem.attrs:
264 1011 aaronmk
                get(node, attr, create, last_only, allow_rooted=False)
265 886 aaronmk
266
        # Follow pointer
267
        if elem.is_ptr:
268 998 aaronmk
            root = doc.documentElement
269 886 aaronmk
            xpath = copy.deepcopy(xpath)
270
            id_path = backward_id(xpath[instance_level])
271
            if id_path != None: # backward (child-to-parent) pointer with ID key
272
                id_path[0].name = expand_abbr(id_path[0].name, node.tagName)
273
                set_value(id_path, xml_dom.get_id(node)) # modify xpath's id key
274
            else: # forward (parent-to-child) pointer
275
                id_ = xml_dom.value(node)
276
                obj_xpath = obj(xpath) # target object
277
                if id_ == None or get(root, obj_xpath, False, True) == []:
278
                    # no target or target keys don't match
279
                    if not create: continue
280
281
                    # Use last target object's ID + 1
282
                    obj_xpath[-1].keys = [] # just get by tag name
283
                    last = get(root, obj_xpath, False, True)
284
                    if last != []: id_ = str(int(xml_dom.get_id(last[0])) + 1)
285
                    else: id_ = '0'
286
287
                    # Will append if target keys didn't match.
288
                    # Use lookahead assertion to avoid this.
289
                    xml_dom.set_value(node, id_)
290
                else: last_only = False
291
                set_id(xpath, id_)
292
        else: root = node
293 1005 aaronmk
        next += get(root, xpath, create, last_only, limit, allow_rooted=False)
294 886 aaronmk
295
        for branch in elem.other_branches:
296 1294 aaronmk
            branch = branch[:] # don't modify input!
297 1009 aaronmk
            set_value(branch, path_value)
298 1005 aaronmk
            next += get(node, branch, create, last_only, limit,
299
                allow_rooted=False)
300 165 aaronmk
301
    return next
302 82 aaronmk
303 1320 aaronmk
def get_1(*args, **kw_args):
304
    '''Runs get() and returns the first result'''
305
    return util.list_get(get(*args, **kw_args), 0)
306
307 141 aaronmk
def put_obj(root, xpath, id_, has_types, value=None):
308 892 aaronmk
    if util.is_str(xpath): xpath = parse(xpath)
309 155 aaronmk
310 1294 aaronmk
    xpath = xpath[:] # don't modify input!
311 82 aaronmk
    set_id(xpath, id_, has_types)
312 85 aaronmk
    if value != None: set_value(xpath, value)
313 141 aaronmk
    get(root, xpath, True)
314 133 aaronmk
315 135 aaronmk
def path2xml(xpath, first_branch=True):
316
    root = xml_dom.create_doc().documentElement
317 141 aaronmk
    get(root, xpath, True)
318 135 aaronmk
    return root
319 133 aaronmk
320 141 aaronmk
def xml_set_id(root, id_): xml_dom.set_id(root.firstChild, id_)