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