/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/xml_serializer.py

  • Committer: Robert Collins
  • Date: 2010-05-06 11:08:10 UTC
  • mto: This revision was merged to the branch mainline in revision 5223.
  • Revision ID: robertc@robertcollins.net-20100506110810-h3j07fh5gmw54s25
Cleaner matcher matching revised unlocking protocol.

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
 
17
17
"""XML externalization support."""
18
18
 
19
 
from __future__ import absolute_import
20
 
 
21
19
# "XML is like violence: if it doesn't solve your problem, you aren't
22
20
# using enough of it." -- various
23
21
 
24
22
# importing this module is fairly slow because it has to load several
25
23
# ElementTree bits
26
24
 
27
 
import re
 
25
from bzrlib.serializer import Serializer
 
26
from bzrlib.trace import mutter
28
27
 
29
28
try:
30
 
    import xml.etree.cElementTree as elementtree
31
 
    ParseError = getattr(elementtree, "ParseError", SyntaxError)
 
29
    try:
 
30
        # it's in this package in python2.5
 
31
        from xml.etree.cElementTree import (ElementTree, SubElement, Element,
 
32
            XMLTreeBuilder, fromstring, tostring)
 
33
        import xml.etree as elementtree
 
34
    except ImportError:
 
35
        from cElementTree import (ElementTree, SubElement, Element,
 
36
                                  XMLTreeBuilder, fromstring, tostring)
 
37
        import elementtree.ElementTree
 
38
    ParseError = SyntaxError
32
39
except ImportError:
33
 
    # Fall back to pure python implementation if C extension is unavailable
34
 
    import xml.etree.ElementTree as elementtree
35
 
    try:
36
 
        from xml.etree.ElementTree import ParseError
37
 
    except ImportError:
38
 
        from xml.parsers.expat import ExpatError as ParseError
39
 
 
40
 
(ElementTree, SubElement, Element, XMLTreeBuilder, fromstring, tostring) = (
41
 
    elementtree.ElementTree, elementtree.SubElement, elementtree.Element,
42
 
    elementtree.XMLTreeBuilder, elementtree.fromstring, elementtree.tostring)
43
 
 
44
 
 
45
 
from .. import (
46
 
    cache_utf8,
47
 
    errors,
48
 
    lazy_regex,
49
 
    serializer,
50
 
    )
51
 
from . import (
52
 
    inventory,
53
 
    )
54
 
 
55
 
 
56
 
class XMLSerializer(serializer.Serializer):
 
40
    mutter('WARNING: using slower ElementTree; consider installing cElementTree'
 
41
           " and make sure it's on your PYTHONPATH")
 
42
    # this copy is shipped with bzr
 
43
    from util.elementtree.ElementTree import (ElementTree, SubElement,
 
44
                                              Element, XMLTreeBuilder,
 
45
                                              fromstring, tostring)
 
46
    import util.elementtree as elementtree
 
47
    from xml.parsers.expat import ExpatError as ParseError
 
48
 
 
49
from bzrlib import errors
 
50
 
 
51
 
 
52
class XMLSerializer(Serializer):
57
53
    """Abstract XML object serialize/deserialize"""
58
54
 
59
55
    squashes_xml_invalid_characters = True
82
78
            return self._unpack_inventory(fromstring(xml_string), revision_id,
83
79
                                          entry_cache=entry_cache,
84
80
                                          return_from_cache=return_from_cache)
85
 
        except ParseError as e:
 
81
        except ParseError, e:
86
82
            raise errors.UnexpectedInventoryFormat(e)
87
83
 
88
84
    def read_inventory(self, f, revision_id=None):
89
85
        try:
90
 
            try:
91
 
                return self._unpack_inventory(self._read_element(f),
92
 
                    revision_id=None)
93
 
            finally:
94
 
                f.close()
95
 
        except ParseError as e:
 
86
            return self._unpack_inventory(self._read_element(f),
 
87
                revision_id=None)
 
88
        except ParseError, e:
96
89
            raise errors.UnexpectedInventoryFormat(e)
97
90
 
98
91
    def write_revision(self, rev, f):
115
108
        return ElementTree().parse(f)
116
109
 
117
110
 
 
111
# performance tuning for elementree's serialiser. This should be
 
112
# sent upstream - RBC 20060523.
 
113
# the functions here are patched into elementtree at runtime.
 
114
import re
 
115
escape_re = re.compile("[&'\"<>]")
 
116
escape_map = {
 
117
    "&":'&amp;',
 
118
    "'":"&apos;", # FIXME: overkill
 
119
    "\"":"&quot;",
 
120
    "<":"&lt;",
 
121
    ">":"&gt;",
 
122
    }
 
123
def _escape_replace(match, map=escape_map):
 
124
    return map[match.group()]
 
125
 
 
126
def _escape_attrib(text, encoding=None, replace=None):
 
127
    # escape attribute value
 
128
    try:
 
129
        if encoding:
 
130
            try:
 
131
                text = elementtree.ElementTree._encode(text, encoding)
 
132
            except UnicodeError:
 
133
                return elementtree.ElementTree._encode_entity(text)
 
134
        if replace is None:
 
135
            return escape_re.sub(_escape_replace, text)
 
136
        else:
 
137
            text = replace(text, "&", "&amp;")
 
138
            text = replace(text, "'", "&apos;") # FIXME: overkill
 
139
            text = replace(text, "\"", "&quot;")
 
140
            text = replace(text, "<", "&lt;")
 
141
            text = replace(text, ">", "&gt;")
 
142
            return text
 
143
    except (TypeError, AttributeError):
 
144
        elementtree.ElementTree._raise_serialization_error(text)
 
145
 
 
146
elementtree.ElementTree._escape_attrib = _escape_attrib
 
147
 
 
148
escape_cdata_re = re.compile("[&<>]")
 
149
escape_cdata_map = {
 
150
    "&":'&amp;',
 
151
    "<":"&lt;",
 
152
    ">":"&gt;",
 
153
    }
 
154
def _escape_cdata_replace(match, map=escape_cdata_map):
 
155
    return map[match.group()]
 
156
 
 
157
def _escape_cdata(text, encoding=None, replace=None):
 
158
    # escape character data
 
159
    try:
 
160
        if encoding:
 
161
            try:
 
162
                text = elementtree.ElementTree._encode(text, encoding)
 
163
            except UnicodeError:
 
164
                return elementtree.ElementTree._encode_entity(text)
 
165
        if replace is None:
 
166
            return escape_cdata_re.sub(_escape_cdata_replace, text)
 
167
        else:
 
168
            text = replace(text, "&", "&amp;")
 
169
            text = replace(text, "<", "&lt;")
 
170
            text = replace(text, ">", "&gt;")
 
171
            return text
 
172
    except (TypeError, AttributeError):
 
173
        elementtree.ElementTree._raise_serialization_error(text)
 
174
 
 
175
elementtree.ElementTree._escape_cdata = _escape_cdata
 
176
 
 
177
 
118
178
def escape_invalid_chars(message):
119
179
    """Escape the XML-invalid characters in a commit message.
120
180
 
130
190
    return re.subn(u'[^\x09\x0A\x0D\u0020-\uD7FF\uE000-\uFFFD]+',
131
191
            lambda match: match.group(0).encode('unicode_escape'),
132
192
            message)
133
 
 
134
 
 
135
 
def get_utf8_or_ascii(a_str, _encode_utf8=cache_utf8.encode):
136
 
    """Return a cached version of the string.
137
 
 
138
 
    cElementTree will return a plain string if the XML is plain ascii. It only
139
 
    returns Unicode when it needs to. We want to work in utf-8 strings. So if
140
 
    cElementTree returns a plain string, we can just return the cached version.
141
 
    If it is Unicode, then we need to encode it.
142
 
 
143
 
    :param a_str: An 8-bit string or Unicode as returned by
144
 
                  cElementTree.Element.get()
145
 
    :return: A utf-8 encoded 8-bit string.
146
 
    """
147
 
    # This is fairly optimized because we know what cElementTree does, this is
148
 
    # not meant as a generic function for all cases. Because it is possible for
149
 
    # an 8-bit string to not be ascii or valid utf8.
150
 
    if a_str.__class__ is unicode:
151
 
        return _encode_utf8(a_str)
152
 
    else:
153
 
        return intern(a_str)
154
 
 
155
 
 
156
 
_utf8_re = lazy_regex.lazy_compile('[&<>\'\"]|[\x80-\xff]+')
157
 
_unicode_re = lazy_regex.lazy_compile(u'[&<>\'\"\u0080-\uffff]')
158
 
 
159
 
 
160
 
_xml_escape_map = {
161
 
    "&":'&amp;',
162
 
    "'":"&apos;", # FIXME: overkill
163
 
    "\"":"&quot;",
164
 
    "<":"&lt;",
165
 
    ">":"&gt;",
166
 
    }
167
 
 
168
 
 
169
 
def _unicode_escape_replace(match, _map=_xml_escape_map):
170
 
    """Replace a string of non-ascii, non XML safe characters with their escape
171
 
 
172
 
    This will escape both Standard XML escapes, like <>"', etc.
173
 
    As well as escaping non ascii characters, because ElementTree did.
174
 
    This helps us remain compatible to older versions of bzr. We may change
175
 
    our policy in the future, though.
176
 
    """
177
 
    # jam 20060816 Benchmarks show that try/KeyError is faster if you
178
 
    # expect the entity to rarely miss. There is about a 10% difference
179
 
    # in overall time. But if you miss frequently, then if None is much
180
 
    # faster. For our use case, we *rarely* have a revision id, file id
181
 
    # or path name that is unicode. So use try/KeyError.
182
 
    try:
183
 
        return _map[match.group()]
184
 
    except KeyError:
185
 
        return "&#%d;" % ord(match.group())
186
 
 
187
 
 
188
 
def _utf8_escape_replace(match, _map=_xml_escape_map):
189
 
    """Escape utf8 characters into XML safe ones.
190
 
 
191
 
    This uses 2 tricks. It is either escaping "standard" characters, like "&<>,
192
 
    or it is handling characters with the high-bit set. For ascii characters,
193
 
    we just lookup the replacement in the dictionary. For everything else, we
194
 
    decode back into Unicode, and then use the XML escape code.
195
 
    """
196
 
    try:
197
 
        return _map[match.group()]
198
 
    except KeyError:
199
 
        return ''.join('&#%d;' % ord(uni_chr)
200
 
                       for uni_chr in match.group().decode('utf8'))
201
 
 
202
 
 
203
 
_to_escaped_map = {}
204
 
 
205
 
def encode_and_escape(unicode_or_utf8_str, _map=_to_escaped_map):
206
 
    """Encode the string into utf8, and escape invalid XML characters"""
207
 
    # We frequently get entities we have not seen before, so it is better
208
 
    # to check if None, rather than try/KeyError
209
 
    text = _map.get(unicode_or_utf8_str)
210
 
    if text is None:
211
 
        if unicode_or_utf8_str.__class__ is unicode:
212
 
            # The alternative policy is to do a regular UTF8 encoding
213
 
            # and then escape only XML meta characters.
214
 
            # Performance is equivalent once you use cache_utf8. *However*
215
 
            # this makes the serialized texts incompatible with old versions
216
 
            # of bzr. So no net gain. (Perhaps the read code would handle utf8
217
 
            # better than entity escapes, but cElementTree seems to do just fine
218
 
            # either way)
219
 
            text = str(_unicode_re.sub(_unicode_escape_replace,
220
 
                                       unicode_or_utf8_str)) + '"'
221
 
        else:
222
 
            # Plain strings are considered to already be in utf-8 so we do a
223
 
            # slightly different method for escaping.
224
 
            text = _utf8_re.sub(_utf8_escape_replace,
225
 
                                unicode_or_utf8_str) + '"'
226
 
        _map[unicode_or_utf8_str] = text
227
 
    return text
228
 
 
229
 
 
230
 
def _clear_cache():
231
 
    """Clean out the unicode => escaped map"""
232
 
    _to_escaped_map.clear()
233
 
 
234
 
 
235
 
def unpack_inventory_entry(elt, entry_cache=None, return_from_cache=False):
236
 
    elt_get = elt.get
237
 
    file_id = elt_get('file_id')
238
 
    revision = elt_get('revision')
239
 
    # Check and see if we have already unpacked this exact entry
240
 
    # Some timings for "repo.revision_trees(last_100_revs)"
241
 
    #               bzr     mysql
242
 
    #   unmodified  4.1s    40.8s
243
 
    #   using lru   3.5s
244
 
    #   using fifo  2.83s   29.1s
245
 
    #   lru._cache  2.8s
246
 
    #   dict        2.75s   26.8s
247
 
    #   inv.add     2.5s    26.0s
248
 
    #   no_copy     2.00s   20.5s
249
 
    #   no_c,dict   1.95s   18.0s
250
 
    # Note that a cache of 10k nodes is more than sufficient to hold all of
251
 
    # the inventory for the last 100 revs for bzr, but not for mysql (20k
252
 
    # is enough for mysql, which saves the same 2s as using a dict)
253
 
 
254
 
    # Breakdown of mysql using time.clock()
255
 
    #   4.1s    2 calls to element.get for file_id, revision_id
256
 
    #   4.5s    cache_hit lookup
257
 
    #   7.1s    InventoryFile.copy()
258
 
    #   2.4s    InventoryDirectory.copy()
259
 
    #   0.4s    decoding unique entries
260
 
    #   1.6s    decoding entries after FIFO fills up
261
 
    #   0.8s    Adding nodes to FIFO (including flushes)
262
 
    #   0.1s    cache miss lookups
263
 
    # Using an LRU cache
264
 
    #   4.1s    2 calls to element.get for file_id, revision_id
265
 
    #   9.9s    cache_hit lookup
266
 
    #   10.8s   InventoryEntry.copy()
267
 
    #   0.3s    cache miss lookus
268
 
    #   1.2s    decoding entries
269
 
    #   1.0s    adding nodes to LRU
270
 
    if entry_cache is not None and revision is not None:
271
 
        key = (file_id, revision)
272
 
        try:
273
 
            # We copy it, because some operations may mutate it
274
 
            cached_ie = entry_cache[key]
275
 
        except KeyError:
276
 
            pass
277
 
        else:
278
 
            # Only copying directory entries drops us 2.85s => 2.35s
279
 
            if return_from_cache:
280
 
                if cached_ie.kind == 'directory':
281
 
                    return cached_ie.copy()
282
 
                return cached_ie
283
 
            return cached_ie.copy()
284
 
 
285
 
    kind = elt.tag
286
 
    if not inventory.InventoryEntry.versionable_kind(kind):
287
 
        raise AssertionError('unsupported entry kind %s' % kind)
288
 
 
289
 
    file_id = get_utf8_or_ascii(file_id)
290
 
    if revision is not None:
291
 
        revision = get_utf8_or_ascii(revision)
292
 
    parent_id = elt_get('parent_id')
293
 
    if parent_id is not None:
294
 
        parent_id = get_utf8_or_ascii(parent_id)
295
 
 
296
 
    if kind == 'directory':
297
 
        ie = inventory.InventoryDirectory(file_id,
298
 
                                          elt_get('name'),
299
 
                                          parent_id)
300
 
    elif kind == 'file':
301
 
        ie = inventory.InventoryFile(file_id,
302
 
                                     elt_get('name'),
303
 
                                     parent_id)
304
 
        ie.text_sha1 = elt_get('text_sha1')
305
 
        if elt_get('executable') == 'yes':
306
 
            ie.executable = True
307
 
        v = elt_get('text_size')
308
 
        ie.text_size = v and int(v)
309
 
    elif kind == 'symlink':
310
 
        ie = inventory.InventoryLink(file_id,
311
 
                                     elt_get('name'),
312
 
                                     parent_id)
313
 
        ie.symlink_target = elt_get('symlink_target')
314
 
    elif kind == 'tree-reference':
315
 
        file_id = elt.attrib['file_id']
316
 
        name = elt.attrib['name']
317
 
        parent_id = elt.attrib['parent_id']
318
 
        revision = elt.get('revision')
319
 
        reference_revision = elt.get('reference_revision')
320
 
        ie = inventory.TreeReference(file_id, name, parent_id, revision,
321
 
                                       reference_revision)
322
 
    else:
323
 
        raise errors.UnsupportedInventoryKind(kind)
324
 
    ie.revision = revision
325
 
    if revision is not None and entry_cache is not None:
326
 
        # We cache a copy() because callers like to mutate objects, and
327
 
        # that would cause the item in cache to mutate as well.
328
 
        # This has a small effect on many-inventory performance, because
329
 
        # the majority fraction is spent in cache hits, not misses.
330
 
        entry_cache[key] = ie.copy()
331
 
 
332
 
    return ie
333
 
 
334
 
 
335
 
def unpack_inventory_flat(elt, format_num, unpack_entry,
336
 
            entry_cache=None, return_from_cache=False):
337
 
    """Unpack a flat XML inventory.
338
 
 
339
 
    :param elt: XML element for the inventory
340
 
    :param format_num: Expected format number
341
 
    :param unpack_entry: Function for unpacking inventory entries
342
 
    :return: An inventory
343
 
    :raise UnexpectedInventoryFormat: When unexpected elements or data is
344
 
        encountered
345
 
    """
346
 
    if elt.tag != 'inventory':
347
 
        raise errors.UnexpectedInventoryFormat('Root tag is %r' % elt.tag)
348
 
    format = elt.get('format')
349
 
    if format != format_num:
350
 
        raise errors.UnexpectedInventoryFormat('Invalid format version %r'
351
 
                                               % format)
352
 
    revision_id = elt.get('revision_id')
353
 
    if revision_id is not None:
354
 
        revision_id = cache_utf8.encode(revision_id)
355
 
    inv = inventory.Inventory(root_id=None, revision_id=revision_id)
356
 
    for e in elt:
357
 
        ie = unpack_entry(e, entry_cache, return_from_cache)
358
 
        inv.add(ie)
359
 
    return inv
360
 
 
361
 
 
362
 
def serialize_inventory_flat(inv, append, root_id, supported_kinds, working):
363
 
    """Serialize an inventory to a flat XML file.
364
 
 
365
 
    :param inv: Inventory to serialize
366
 
    :param append: Function for writing a line of output
367
 
    :param working: If True skip history data - text_sha1, text_size,
368
 
        reference_revision, symlink_target.    self._check_revisions(inv)
369
 
    """
370
 
    entries = inv.iter_entries()
371
 
    # Skip the root
372
 
    root_path, root_ie = next(entries)
373
 
    for path, ie in entries:
374
 
        if ie.parent_id != root_id:
375
 
            parent_str = ' parent_id="'
376
 
            parent_id  = encode_and_escape(ie.parent_id)
377
 
        else:
378
 
            parent_str = ''
379
 
            parent_id  = ''
380
 
        if ie.kind == 'file':
381
 
            if ie.executable:
382
 
                executable = ' executable="yes"'
383
 
            else:
384
 
                executable = ''
385
 
            if not working:
386
 
                append('<file%s file_id="%s name="%s%s%s revision="%s '
387
 
                    'text_sha1="%s" text_size="%d" />\n' % (
388
 
                    executable, encode_and_escape(ie.file_id),
389
 
                    encode_and_escape(ie.name), parent_str, parent_id,
390
 
                    encode_and_escape(ie.revision), ie.text_sha1,
391
 
                    ie.text_size))
392
 
            else:
393
 
                append('<file%s file_id="%s name="%s%s%s />\n' % (
394
 
                    executable, encode_and_escape(ie.file_id),
395
 
                    encode_and_escape(ie.name), parent_str, parent_id))
396
 
        elif ie.kind == 'directory':
397
 
            if not working:
398
 
                append('<directory file_id="%s name="%s%s%s revision="%s '
399
 
                    '/>\n' % (
400
 
                    encode_and_escape(ie.file_id),
401
 
                    encode_and_escape(ie.name),
402
 
                    parent_str, parent_id,
403
 
                    encode_and_escape(ie.revision)))
404
 
            else:
405
 
                append('<directory file_id="%s name="%s%s%s />\n' % (
406
 
                    encode_and_escape(ie.file_id),
407
 
                    encode_and_escape(ie.name),
408
 
                    parent_str, parent_id))
409
 
        elif ie.kind == 'symlink':
410
 
            if not working:
411
 
                append('<symlink file_id="%s name="%s%s%s revision="%s '
412
 
                    'symlink_target="%s />\n' % (
413
 
                    encode_and_escape(ie.file_id),
414
 
                    encode_and_escape(ie.name),
415
 
                    parent_str, parent_id,
416
 
                    encode_and_escape(ie.revision),
417
 
                    encode_and_escape(ie.symlink_target)))
418
 
            else:
419
 
                append('<symlink file_id="%s name="%s%s%s />\n' % (
420
 
                    encode_and_escape(ie.file_id),
421
 
                    encode_and_escape(ie.name),
422
 
                    parent_str, parent_id))
423
 
        elif ie.kind == 'tree-reference':
424
 
            if ie.kind not in supported_kinds:
425
 
                raise errors.UnsupportedInventoryKind(ie.kind)
426
 
            if not working:
427
 
                append('<tree-reference file_id="%s name="%s%s%s '
428
 
                    'revision="%s reference_revision="%s />\n' % (
429
 
                    encode_and_escape(ie.file_id),
430
 
                    encode_and_escape(ie.name),
431
 
                    parent_str, parent_id,
432
 
                    encode_and_escape(ie.revision),
433
 
                    encode_and_escape(ie.reference_revision)))
434
 
            else:
435
 
                append('<tree-reference file_id="%s name="%s%s%s />\n' % (
436
 
                    encode_and_escape(ie.file_id),
437
 
                    encode_and_escape(ie.name),
438
 
                    parent_str, parent_id))
439
 
        else:
440
 
            raise errors.UnsupportedInventoryKind(ie.kind)
441
 
    append('</inventory>\n')