/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: John Ferlito
  • Date: 2009-09-02 04:31:45 UTC
  • mto: (4665.7.1 serve-init)
  • mto: This revision was merged to the branch mainline in revision 4913.
  • Revision ID: johnf@inodes.org-20090902043145-gxdsfw03ilcwbyn5
Add a debian init script for bzr --serve

Show diffs side-by-side

added added

removed removed

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