Project

General

Profile

1
# XPath parsing
2

    
3
import copy
4
import warnings
5

    
6
from Parser import Parser
7
import util
8
import xml_dom
9

    
10
##### Path elements
11

    
12
class XpathElem:
13
    def __init__(self, name='', value=None, is_attr=False):
14
        self.name = name
15
        self.value = value
16
        self.is_attr = is_attr
17
        self.is_positive = True
18
        self.is_lookup_only = False
19
        self.is_ptr = False
20
        self.keys = []
21
        self.attrs = []
22
        self.other_branches = [] # temp implementation for split paths
23
    
24
    def __repr__(self):
25
        str_ = ''
26
        if not self.is_positive: str_ += '!'
27
        if self.is_attr: str_ += '@'
28
        if self.name == '': str_ += '""'
29
        else: str_ += self.name
30
        if self.is_lookup_only: str_ += '?'
31
        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
        if self.value != None: str_ += '='+repr(self.value)
36
        return str_
37
    
38
    def __eq__(self, other): return self.__dict__ == other.__dict__
39

    
40
empty_elem = XpathElem()
41

    
42
def elem_is_empty(elem): return elem == empty_elem
43

    
44
def is_self(elem): return elem.name == '' or elem.name == '.'
45

    
46
def is_parent(elem): return elem.name == '..'
47

    
48
##### Paths
49

    
50
def is_positive(path): return path[0].is_positive
51

    
52
def is_rooted(path): return elem_is_empty(path[0])
53

    
54
def value(path): return path[-1].value
55

    
56
def set_value(path, value):
57
    '''Caller must make a shallow copy of the path to prevent modifications from
58
    propagating to other copies of the path (a deep copy is not needed)'''
59
    path[-1] = copy.copy(path[-1]) # don't modify other copies of the path
60
    path[-1].value = value
61

    
62
def backward_id(elem):
63
    if len(elem.keys) >= 1 and value(elem.keys[0]) == None: return elem.keys[0]
64
    else: return None
65

    
66
instance_level = 1 # root's grandchildren
67

    
68
def obj(path):
69
    obj_path = copy.deepcopy(path[:instance_level+1])
70
    obj_path[-1].is_ptr = False # prevent pointer w/o target
71
    return obj_path
72

    
73
def set_id(path, id_, has_types=True):
74
    '''Caller must make a shallow copy of the path to prevent modifications from
75
    propagating to other copies of the path (a deep copy is not needed)'''
76
    if has_types: id_level = instance_level
77
    else: id_level = 0 # root's children
78
    if is_self(path[0]): id_level += 1 # explicit root element
79
    
80
    id_elem = path[id_level] = copy.copy(path[id_level])
81
        # don't modify other copies of the path
82
    id_elem.keys = id_elem.keys[:] # don't modify other copies of the elem
83
    id_elem.keys.append([XpathElem('id', id_, True)])
84

    
85
def is_id(path): return path[0].is_attr and path[0].name == 'id'
86

    
87
def is_instance(elem): return elem.keys != [] and is_id(elem.keys[0])
88

    
89
##### Parsing
90

    
91
import xpath_func
92

    
93
def expand_abbr(name, repl):
94
    before, abbr, after = name.partition('*')
95
    if abbr != '': name = before+repl+after
96
    return name
97

    
98
_cache = {}
99

    
100
def parse(str_):
101
    try: return _cache[str_]
102
    except KeyError: pass
103
    
104
    parser = Parser(str_)
105
    
106
    def _path():
107
        is_positive = not parser.str_('!')
108
        
109
        tree = []
110
        while True:
111
            # Split path
112
            if parser.str_('{'):
113
                last = tree[-1]
114
                last.other_branches = _paths()
115
                parser.str_('}', required=True)
116
                if parser.str_('/'): # common subpath after {}
117
                    subpath = _path()
118
                    for branch in last.other_branches: branch += subpath
119
                tree += last.other_branches.pop(0) # use first path for now
120
                break # anything after split path has already been parsed
121
            
122
            elem = XpathElem(is_attr=parser.str_('@'), name=_value())
123
            
124
            elem.is_lookup_only = parser.str_('?')
125
            
126
            # Keys used to match nodes
127
            if parser.str_('['):
128
                elem.keys = _paths()
129
                parser.str_(']', required=True)
130
            
131
            # Attrs created when no matching node exists
132
            if parser.str_(':'):
133
                parser.str_('[', required=True)
134
                elem.attrs = _paths()
135
                parser.str_(']', required=True)
136
            
137
            elem.is_ptr = parser.str_('->')
138
            tree.append(elem)
139
            
140
            # Lookahead assertion
141
            if parser.str_('('):
142
                parser.str_('/', required=True) # next / is inside ()
143
                path = _path()
144
                parser.str_(')', required=True)
145
                elem.keys.append(path)
146
                tree += path
147
            
148
            if not parser.str_('/'): break
149
        
150
        tree[0].is_positive = is_positive
151
        
152
        # Value
153
        if parser.str_('='):
154
            if parser.str_('$'): # reference (different from a pointer)
155
                value = _path()
156
            else: value = _value() # literal value
157
            set_value(tree, value)
158
        
159
        # Expand * abbrs
160
        for i in reversed(xrange(len(tree))):
161
            elem = tree[i]
162
            if elem.is_ptr: offset = 2
163
            else: offset = 1
164
            try: repl = tree[i+offset].name
165
            except IndexError: pass # no replacement elem
166
            else: elem.name = expand_abbr(elem.name, repl)
167
        
168
        return tree
169
    
170
    def _value():
171
        if parser.str_('"'):
172
            value = parser.re(r'[^"]*')
173
            parser.str_('"', required=True)
174
        else: value = parser.re(r'(?:(?:\w+:)*[\w.*]+)?')
175
        return value
176
    
177
    def _paths():
178
        paths = []
179
        while True:
180
            paths.append(_path())
181
            if not parser.str_(','): break
182
        return paths
183
    
184
    path = _path()
185
    parser.end()
186
    path = xpath_func.process(path)
187
    _cache[str_] = path
188
    return path
189

    
190
##### Querying/creating XML trees
191

    
192
def get(root, xpath, create=False, last_only=None, limit=1, allow_rooted=True):
193
    '''Warning: The last_only optimization may put data that should be together
194
    into separate nodes'''
195
    if last_only == None: last_only = create
196
    if limit == None or limit > 1: last_only = False
197
    if util.is_str(xpath): xpath = parse(xpath)
198
    
199
    # Handle edge cases
200
    if xpath == []: return [root]
201
    if create and not is_positive(xpath): return []
202
    
203
    # Define vars
204
    doc = root.ownerDocument
205
    if allow_rooted and is_rooted(xpath): root = doc.documentElement
206
    elem = xpath[0]
207
    
208
    # Find possible matches
209
    children = []
210
    if elem.is_attr:
211
        child = root.getAttributeNode(elem.name)
212
        if child != None: children = [child]
213
    elif is_self(elem): children = [root]
214
    elif is_parent(elem):
215
        parent = xml_dom.parent(root)
216
        if parent == None: return [] # don't try to create doc root's parent
217
        root = parent
218
        children = [root]
219
    else:
220
        children = xml_dom.by_tag_name(root, elem.name,
221
            last_only and (elem.keys == [] or is_instance(elem)))
222
    
223
    # Retrieve elem value
224
    value_ = elem.value
225
    if util.is_list(value_): # reference (different from a pointer)
226
        targets = get(root, value_)
227
        try: target = targets[0]
228
        except IndexError:
229
            warnings.warn(UserWarning('XPath reference target missing: '
230
                +str(value_)+'\nXPath: '+str(xpath)))
231
            value_ = None
232
        else: value_ = xml_dom.value(target)
233
    
234
    # Check each match
235
    nodes = []
236
    for child in children:
237
        is_match = value_ == None or xml_dom.value(child) == value_
238
        for attr in elem.keys:
239
            if not is_match: break
240
            is_match = ((get(child, attr, False, last_only,
241
                allow_rooted=False) != []) == is_positive(attr))
242
        if is_match:
243
            nodes.append(child)
244
            if limit != None and len(nodes) >= limit: break
245
    
246
    # Create node
247
    if nodes == []:
248
        if not create or elem.is_lookup_only: return []
249
        if elem.is_attr:
250
            root.setAttribute(elem.name, '')
251
            node = root.getAttributeNode(elem.name)
252
        elif util.list_eq_is(children, [root]): node = root
253
        else: node = root.appendChild(doc.createElement(elem.name))
254
        if value_ != None: xml_dom.set_value(node, value_)
255
        nodes.append(node)
256
    
257
    path_value = value(xpath)
258
    xpath = xpath[1:] # rest of XPath
259
    
260
    next = []
261
    for node in nodes:
262
        # Create attrs
263
        if create:
264
            for attr in elem.keys + elem.attrs:
265
                get(node, attr, create, last_only, allow_rooted=False)
266
        
267
        # Follow pointer
268
        if elem.is_ptr:
269
            root = doc.documentElement
270
            xpath = copy.deepcopy(xpath)
271
            id_path = backward_id(xpath[instance_level])
272
            if id_path != None: # backward (child-to-parent) pointer with ID key
273
                id_path[0].name = expand_abbr(id_path[0].name, node.tagName)
274
                set_value(id_path, xml_dom.get_id(node)) # modify xpath's id key
275
            else: # forward (parent-to-child) pointer
276
                id_ = xml_dom.value(node)
277
                obj_xpath = obj(xpath) # target object
278
                if id_ == None or get(root, obj_xpath, False, True) == []:
279
                    # no target or target keys don't match
280
                    if not create: continue
281
                    
282
                    # Use last target object's ID + 1
283
                    obj_xpath[-1].keys = [] # just get by tag name
284
                    last = get(root, obj_xpath, False, True)
285
                    if last != []: id_ = str(int(xml_dom.get_id(last[0])) + 1)
286
                    else: id_ = '0'
287
                    
288
                    # Will append if target keys didn't match.
289
                    # Use lookahead assertion to avoid this.
290
                    xml_dom.set_value(node, id_)
291
                else: last_only = False
292
                set_id(xpath, id_)
293
        else: root = node
294
        next += get(root, xpath, create, last_only, limit, allow_rooted=False)
295
        
296
        for branch in elem.other_branches:
297
            branch = branch[:] # don't modify input!
298
            set_value(branch, path_value)
299
            next += get(node, branch, create, last_only, limit,
300
                allow_rooted=False)
301
    
302
    return next
303

    
304
def get_1(*args, **kw_args):
305
    '''Runs get() and returns the first result'''
306
    return util.list_get(get(*args, **kw_args), 0)
307

    
308
def put_obj(root, xpath, id_, has_types, value=None):
309
    if util.is_str(xpath): xpath = parse(xpath)
310
    
311
    xpath = xpath[:] # don't modify input!
312
    set_id(xpath, id_, has_types)
313
    if value != None: set_value(xpath, value)
314
    get(root, xpath, True)
315

    
316
def path2xml(xpath, first_branch=True):
317
    root = xml_dom.create_doc().documentElement
318
    get(root, xpath, True)
319
    return root
320

    
321
def xml_set_id(root, id_): xml_dom.set_id(root.firstChild, id_)
(16-16/17)