Project

General

Profile

1 55 aaronmk
# XPath parsing
2 21 aaronmk
3 55 aaronmk
import copy
4 21 aaronmk
5
from Parser import Parser
6 892 aaronmk
import util
7 77 aaronmk
import xml_dom
8 21 aaronmk
9
class XpathElem:
10 94 aaronmk
    def __init__(self, name, value=None, is_attr=False):
11 156 aaronmk
        if name == '': name = '.'
12 21 aaronmk
        self.name = name
13
        self.value = value
14
        self.is_attr = is_attr
15 97 aaronmk
        self.is_positive = True
16 94 aaronmk
        self.is_ptr = False
17
        self.keys = []
18
        self.attrs = []
19 78 aaronmk
        self.other_branches = [] # temp implementation for split paths
20 21 aaronmk
21
    def __repr__(self):
22
        str_ = ''
23 141 aaronmk
        if not self.is_positive: str_ += '!'
24 21 aaronmk
        if self.is_attr: str_ += '@'
25 25 aaronmk
        str_ += self.name
26 94 aaronmk
        if self.keys != []: str_ += repr(self.keys)
27
        if self.attrs != []: str_ += ':'+repr(self.attrs)
28
        if self.is_ptr: str_ += '->'
29
        if self.other_branches != []: str_ += '{'+repr(self.other_branches)+'}'
30 25 aaronmk
        if self.value != None: str_ += '='+repr(self.value)
31 21 aaronmk
        return str_
32
33
    def __eq__(self, other): return self.__dict__ == other.__dict__
34
35 99 aaronmk
def is_positive(path): return path[0].is_positive
36
37 24 aaronmk
def value(path): return path[-1].value
38
39 22 aaronmk
def set_value(path, value): path[-1].value = value
40
41 32 aaronmk
def backward_id(elem):
42 171 aaronmk
    if len(elem.keys) >= 1 and value(elem.keys[0]) == None: return elem.keys[0]
43 32 aaronmk
    else: return None
44
45 170 aaronmk
def expand_abbr(name, repl):
46
    before, abbr, after = name.partition('*')
47
    if abbr != '': name = before+repl+after
48
    return name
49
50 154 aaronmk
_cache = {}
51
52 76 aaronmk
def parse(str_):
53 154 aaronmk
    try: return _cache[str_]
54
    except KeyError: pass
55
56 76 aaronmk
    parser = Parser(str_)
57 21 aaronmk
58 76 aaronmk
    def _path():
59 97 aaronmk
        is_positive = not parser.str_('!')
60
61 21 aaronmk
        tree = []
62
        while True:
63 38 aaronmk
            # Split path
64 76 aaronmk
            if parser.str_('{'):
65 94 aaronmk
                tree[-1].other_branches = _paths()
66 76 aaronmk
                parser.str_('}', required=True)
67 94 aaronmk
                tree += tree[-1].other_branches.pop(0) # use first path for now
68 38 aaronmk
                break # nothing allowed after split path
69 36 aaronmk
70 754 aaronmk
            elem = XpathElem(is_attr=parser.str_('@'), name=_value())
71 38 aaronmk
72 94 aaronmk
            # Keys used to match nodes
73 76 aaronmk
            if parser.str_('['):
74 94 aaronmk
                elem.keys = _paths()
75 76 aaronmk
                parser.str_(']', required=True)
76 36 aaronmk
77 94 aaronmk
            # Attrs created when no matching node exists
78
            if parser.str_(':'):
79
                parser.str_('[', required=True)
80
                elem.attrs = _paths()
81
                parser.str_(']', required=True)
82
83 76 aaronmk
            elem.is_ptr = parser.str_('->')
84 21 aaronmk
            tree.append(elem)
85 36 aaronmk
86
            # Lookahead assertion
87 76 aaronmk
            if parser.str_('('):
88
                parser.str_('/', required=True) # next / is inside ()
89
                path = _path()
90
                parser.str_(')', required=True)
91 94 aaronmk
                elem.keys.append(path)
92 36 aaronmk
                tree += path
93
94 76 aaronmk
            if not parser.str_('/'): break
95 32 aaronmk
96 97 aaronmk
        tree[0].is_positive = is_positive
97
98
        # Value
99 754 aaronmk
        if parser.str_('='): set_value(tree, _value())
100 85 aaronmk
101 32 aaronmk
        # Expand * abbrs
102 70 aaronmk
        for i in reversed(xrange(len(tree))):
103
            elem = tree[i]
104 171 aaronmk
            if elem.is_ptr: offset = 2
105 32 aaronmk
            else: offset = 1
106 170 aaronmk
            try: repl = tree[i+offset].name
107 171 aaronmk
            except IndexError: pass # no replacement elem
108
            else: elem.name = expand_abbr(elem.name, repl)
109 32 aaronmk
110 21 aaronmk
        return tree
111 76 aaronmk
112 754 aaronmk
    def _value():
113
        if parser.str_('"'):
114
            value = parser.re(r'[^"]*')
115
            parser.str_('"', required=True)
116
        else: value = parser.re(r'(?:(?:\w+:)*[\w.*]+)?')
117
        return value
118
119 94 aaronmk
    def _paths():
120
        paths = []
121
        while True:
122
            paths.append(_path())
123
            if not parser.str_(','): break
124
        return paths
125
126 76 aaronmk
    path = _path()
127
    parser.end()
128 154 aaronmk
    _cache[str_] = path
129 76 aaronmk
    return path
130 21 aaronmk
131 758 aaronmk
instance_level = 1 # root's grandchildren
132 22 aaronmk
133 26 aaronmk
def obj(path):
134 55 aaronmk
    obj_path = copy.deepcopy(path[:instance_level+1])
135 26 aaronmk
    obj_path[-1].is_ptr = False # prevent pointer w/o target
136
    return obj_path
137
138 22 aaronmk
def set_id(path, id_, has_types=True):
139 26 aaronmk
    if has_types: id_level = instance_level
140 758 aaronmk
    else: id_level = 0 # root's children
141
    if path[0].name == '.': id_level += 1 # explicit root element
142 94 aaronmk
    path[id_level].keys.append([XpathElem('id', id_, True)])
143 62 aaronmk
144
def is_id(path): return path[0].is_attr and path[0].name == 'id'
145
146 94 aaronmk
def is_instance(elem): return elem.keys != [] and is_id(elem.keys[0])
147 77 aaronmk
148 885 aaronmk
def get(parent, xpath, create=False, last_only=None, limit=1):
149 141 aaronmk
    '''Warning: The last_only optimization may put data that should be together
150
    into separate nodes'''
151 77 aaronmk
    if last_only == None: last_only = create
152 887 aaronmk
    if limit == None or limit > 1: last_only = False
153 892 aaronmk
    if util.is_str(xpath): xpath = parse(xpath)
154 99 aaronmk
155 886 aaronmk
    if xpath == []: return [parent]
156
    if create and not is_positive(xpath): return []
157 135 aaronmk
    doc = parent.ownerDocument
158 141 aaronmk
    root = doc.documentElement
159 165 aaronmk
    elem = xpath[0]
160
161
    # Find possible matches
162
    children = []
163
    if elem.is_attr:
164
        child = parent.getAttributeNode(elem.name)
165
        if child != None: children = [child]
166
    elif elem.name == '.': children = [parent]
167
    else:
168
        children = xml_dom.by_tag_name(parent, elem.name,
169
        last_only and (elem.keys == [] or is_instance(elem)))
170
171
    # Check each match
172 885 aaronmk
    nodes = []
173 165 aaronmk
    for child in children:
174
        is_match = elem.value == None or xml_dom.value(child) == elem.value
175
        for attr in elem.keys:
176
            if not is_match: break
177 886 aaronmk
            is_match = ((get(child, attr, False, last_only) != [])
178
                == is_positive(attr))
179 885 aaronmk
        if is_match:
180
            nodes.append(child)
181
            if limit != None and len(nodes) >= limit: break
182 165 aaronmk
183
    # Create node
184 886 aaronmk
    if nodes == []:
185
        if not create: return []
186 77 aaronmk
        if elem.is_attr:
187 165 aaronmk
            parent.setAttribute(elem.name, '')
188
            node = parent.getAttributeNode(elem.name)
189
        else: node = parent.appendChild(doc.createElement(elem.name))
190
        if elem.value != None: xml_dom.set_value(node, elem.value)
191 886 aaronmk
        nodes.append(node)
192 165 aaronmk
193 971 aaronmk
    value_ = value(xpath)
194 165 aaronmk
    xpath = xpath[1:] # rest of XPath
195
196 886 aaronmk
    next = []
197
    for node in nodes:
198
        # Create attrs
199
        if create:
200
            for attr in elem.keys + elem.attrs:
201
                get(node, attr, create, last_only)
202
203
        # Follow pointer
204
        if elem.is_ptr:
205
            xpath = copy.deepcopy(xpath)
206
            id_path = backward_id(xpath[instance_level])
207
            if id_path != None: # backward (child-to-parent) pointer with ID key
208
                id_path[0].name = expand_abbr(id_path[0].name, node.tagName)
209
                set_value(id_path, xml_dom.get_id(node)) # modify xpath's id key
210
            else: # forward (parent-to-child) pointer
211
                id_ = xml_dom.value(node)
212
                obj_xpath = obj(xpath) # target object
213
                if id_ == None or get(root, obj_xpath, False, True) == []:
214
                    # no target or target keys don't match
215
                    if not create: continue
216
217
                    # Use last target object's ID + 1
218
                    obj_xpath[-1].keys = [] # just get by tag name
219
                    last = get(root, obj_xpath, False, True)
220
                    if last != []: id_ = str(int(xml_dom.get_id(last[0])) + 1)
221
                    else: id_ = '0'
222
223
                    # Will append if target keys didn't match.
224
                    # Use lookahead assertion to avoid this.
225
                    xml_dom.set_value(node, id_)
226
                else: last_only = False
227
                set_id(xpath, id_)
228
        else: root = node
229 889 aaronmk
        next += get(root, xpath, create, last_only, limit)
230 886 aaronmk
231
        for branch in elem.other_branches:
232
            branch = copy.deepcopy(branch)
233 971 aaronmk
            set_value(branch, value_)
234 889 aaronmk
            next += get(node, branch, create, last_only, limit)
235 165 aaronmk
236
    return next
237 82 aaronmk
238 141 aaronmk
def put_obj(root, xpath, id_, has_types, value=None):
239 892 aaronmk
    if util.is_str(xpath): xpath = parse(xpath)
240 155 aaronmk
241 82 aaronmk
    xpath = copy.deepcopy(xpath) # don't modify input!
242
    set_id(xpath, id_, has_types)
243 85 aaronmk
    if value != None: set_value(xpath, value)
244 141 aaronmk
    get(root, xpath, True)
245 133 aaronmk
246 135 aaronmk
def path2xml(xpath, first_branch=True):
247
    root = xml_dom.create_doc().documentElement
248 141 aaronmk
    get(root, xpath, True)
249 135 aaronmk
    return root
250 133 aaronmk
251 141 aaronmk
def xml_set_id(root, id_): xml_dom.set_id(root.firstChild, id_)