~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/xml5.py

  • Committer: Robert Collins
  • Date: 2007-03-01 05:02:47 UTC
  • mto: (2255.11.3 dirstate)
  • mto: This revision was merged to the branch mainline in revision 2322.
  • Revision ID: robertc@robertcollins.net-20070301050247-ufh99m2ze45d7mol
Whitespace fix.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
import cStringIO
 
18
import re
 
19
 
 
20
from bzrlib import (
 
21
    cache_utf8,
 
22
    inventory,
 
23
    )
 
24
from bzrlib.xml_serializer import SubElement, Element, Serializer
 
25
from bzrlib.inventory import ROOT_ID, Inventory, InventoryEntry
 
26
from bzrlib.revision import Revision
 
27
from bzrlib.errors import BzrError
 
28
 
 
29
 
 
30
_utf8_re = None
 
31
_unicode_re = None
 
32
_xml_escape_map = {
 
33
    "&":'&',
 
34
    "'":"'", # FIXME: overkill
 
35
    "\"":""",
 
36
    "<":"&lt;",
 
37
    ">":"&gt;",
 
38
    }
 
39
 
 
40
 
 
41
def _ensure_utf8_re():
 
42
    """Make sure the _utf8_re and _unicode_re regexes have been compiled."""
 
43
    global _utf8_re, _unicode_re
 
44
    if _utf8_re is None:
 
45
        _utf8_re = re.compile('[&<>\'\"]|[\x80-\xff]+')
 
46
    if _unicode_re is None:
 
47
        _unicode_re = re.compile(u'[&<>\'\"\u0080-\uffff]')
 
48
 
 
49
 
 
50
def _unicode_escape_replace(match, _map=_xml_escape_map):
 
51
    """Replace a string of non-ascii, non XML safe characters with their escape
 
52
 
 
53
    This will escape both Standard XML escapes, like <>"', etc.
 
54
    As well as escaping non ascii characters, because ElementTree did.
 
55
    This helps us remain compatible to older versions of bzr. We may change
 
56
    our policy in the future, though.
 
57
    """
 
58
    # jam 20060816 Benchmarks show that try/KeyError is faster if you
 
59
    # expect the entity to rarely miss. There is about a 10% difference
 
60
    # in overall time. But if you miss frequently, then if None is much
 
61
    # faster. For our use case, we *rarely* have a revision id, file id
 
62
    # or path name that is unicode. So use try/KeyError.
 
63
    try:
 
64
        return _map[match.group()]
 
65
    except KeyError:
 
66
        return "&#%d;" % ord(match.group())
 
67
 
 
68
 
 
69
def _utf8_escape_replace(match, _map=_xml_escape_map):
 
70
    """Escape utf8 characters into XML safe ones.
 
71
 
 
72
    This uses 2 tricks. It is either escaping "standard" characters, like "&<>,
 
73
    or it is handling characters with the high-bit set. For ascii characters,
 
74
    we just lookup the replacement in the dictionary. For everything else, we
 
75
    decode back into Unicode, and then use the XML escape code.
 
76
    """
 
77
    try:
 
78
        return _map[match.group()]
 
79
    except KeyError:
 
80
        return ''.join('&#%d;' % ord(uni_chr)
 
81
                       for uni_chr in match.group().decode('utf8'))
 
82
 
 
83
 
 
84
_to_escaped_map = {}
 
85
 
 
86
def _encode_and_escape(unicode_or_utf8_str, _map=_to_escaped_map):
 
87
    """Encode the string into utf8, and escape invalid XML characters"""
 
88
    # We frequently get entities we have not seen before, so it is better
 
89
    # to check if None, rather than try/KeyError
 
90
    text = _map.get(unicode_or_utf8_str)
 
91
    if text is None:
 
92
        if unicode_or_utf8_str.__class__ == unicode:
 
93
            # The alternative policy is to do a regular UTF8 encoding
 
94
            # and then escape only XML meta characters.
 
95
            # Performance is equivalent once you use cache_utf8. *However*
 
96
            # this makes the serialized texts incompatible with old versions
 
97
            # of bzr. So no net gain. (Perhaps the read code would handle utf8
 
98
            # better than entity escapes, but cElementTree seems to do just fine
 
99
            # either way)
 
100
            text = str(_unicode_re.sub(_unicode_escape_replace,
 
101
                                       unicode_or_utf8_str)) + '"'
 
102
        else:
 
103
            # Plain strings are considered to already be in utf-8 so we do a
 
104
            # slightly different method for escaping.
 
105
            text = _utf8_re.sub(_utf8_escape_replace,
 
106
                                unicode_or_utf8_str) + '"'
 
107
        _map[unicode_or_utf8_str] = text
 
108
    return text
 
109
 
 
110
 
 
111
def _get_utf8_or_ascii(a_str,
 
112
                       _encode_utf8=cache_utf8.encode,
 
113
                       _get_cached_ascii=cache_utf8.get_cached_ascii):
 
114
    """Return a cached version of the string.
 
115
 
 
116
    cElementTree will return a plain string if the XML is plain ascii. It only
 
117
    returns Unicode when it needs to. We want to work in utf-8 strings. So if
 
118
    cElementTree returns a plain string, we can just return the cached version.
 
119
    If it is Unicode, then we need to encode it.
 
120
 
 
121
    :param a_str: An 8-bit string or Unicode as returned by
 
122
                  cElementTree.Element.get()
 
123
    :return: A utf-8 encoded 8-bit string.
 
124
    """
 
125
    # This is fairly optimized because we know what cElementTree does, this is
 
126
    # not meant as a generic function for all cases. Because it is possible for
 
127
    # an 8-bit string to not be ascii or valid utf8.
 
128
    if a_str.__class__ == unicode:
 
129
        return _encode_utf8(a_str)
 
130
    else:
 
131
        return _get_cached_ascii(a_str)
 
132
 
 
133
 
 
134
def _clear_cache():
 
135
    """Clean out the unicode => escaped map"""
 
136
    _to_escaped_map.clear()
 
137
 
 
138
 
 
139
class Serializer_v5(Serializer):
 
140
    """Version 5 serializer
 
141
 
 
142
    Packs objects into XML and vice versa.
 
143
    """
 
144
    
 
145
    __slots__ = []
 
146
 
 
147
    support_altered_by_hack = True
 
148
    # This format supports the altered-by hack that reads file ids directly out
 
149
    # of the versionedfile, without doing XML parsing.
 
150
 
 
151
    def write_inventory_to_string(self, inv):
 
152
        """Just call write_inventory with a StringIO and return the value"""
 
153
        sio = cStringIO.StringIO()
 
154
        self.write_inventory(inv, sio)
 
155
        return sio.getvalue()
 
156
 
 
157
    def write_inventory(self, inv, f):
 
158
        """Write inventory to a file.
 
159
        
 
160
        :param inv: the inventory to write.
 
161
        :param f: the file to write.
 
162
        """
 
163
        _ensure_utf8_re()
 
164
        output = []
 
165
        append = output.append
 
166
        self._append_inventory_root(append, inv)
 
167
        entries = inv.iter_entries()
 
168
        # Skip the root
 
169
        root_path, root_ie = entries.next()
 
170
        for path, ie in entries:
 
171
            self._append_entry(append, ie)
 
172
        append('</inventory>\n')
 
173
        f.writelines(output)
 
174
        # Just to keep the cache from growing without bounds
 
175
        # but we may actually not want to do clear the cache
 
176
        #_clear_cache()
 
177
 
 
178
    def _append_inventory_root(self, append, inv):
 
179
        """Append the inventory root to output."""
 
180
        append('<inventory')
 
181
        if inv.root.file_id not in (None, ROOT_ID):
 
182
            append(' file_id="')
 
183
            append(_encode_and_escape(inv.root.file_id))
 
184
        append(' format="5"')
 
185
        if inv.revision_id is not None:
 
186
            append(' revision_id="')
 
187
            append(_encode_and_escape(inv.revision_id))
 
188
        append('>\n')
 
189
        
 
190
    def _append_entry(self, append, ie):
 
191
        """Convert InventoryEntry to XML element and append to output."""
 
192
        # TODO: should just be a plain assertion
 
193
        assert InventoryEntry.versionable_kind(ie.kind), \
 
194
            'unsupported entry kind %s' % ie.kind
 
195
 
 
196
        append("<")
 
197
        append(ie.kind)
 
198
        if ie.executable:
 
199
            append(' executable="yes"')
 
200
        append(' file_id="')
 
201
        append(_encode_and_escape(ie.file_id))
 
202
        append(' name="')
 
203
        append(_encode_and_escape(ie.name))
 
204
        if self._parent_condition(ie):
 
205
            assert isinstance(ie.parent_id, basestring)
 
206
            append(' parent_id="')
 
207
            append(_encode_and_escape(ie.parent_id))
 
208
        if ie.revision is not None:
 
209
            append(' revision="')
 
210
            append(_encode_and_escape(ie.revision))
 
211
        if ie.symlink_target is not None:
 
212
            append(' symlink_target="')
 
213
            append(_encode_and_escape(ie.symlink_target))
 
214
        if ie.text_sha1 is not None:
 
215
            append(' text_sha1="')
 
216
            append(ie.text_sha1)
 
217
            append('"')
 
218
        if ie.text_size is not None:
 
219
            append(' text_size="%d"' % ie.text_size)
 
220
        append(" />\n")
 
221
        return
 
222
 
 
223
    def _parent_condition(self, ie):
 
224
        return ie.parent_id != ROOT_ID
 
225
 
 
226
    def _pack_revision(self, rev):
 
227
        """Revision object -> xml tree"""
 
228
        # For the XML format, we need to write them as Unicode rather than as
 
229
        # utf-8 strings. So that cElementTree can handle properly escaping
 
230
        # them.
 
231
        decode_utf8 = cache_utf8.decode
 
232
        revision_id = rev.revision_id
 
233
        if isinstance(revision_id, str):
 
234
            revision_id = decode_utf8(revision_id)
 
235
        root = Element('revision',
 
236
                       committer = rev.committer,
 
237
                       timestamp = '%.3f' % rev.timestamp,
 
238
                       revision_id = revision_id,
 
239
                       inventory_sha1 = rev.inventory_sha1,
 
240
                       format='5',
 
241
                       )
 
242
        if rev.timezone is not None:
 
243
            root.set('timezone', str(rev.timezone))
 
244
        root.text = '\n'
 
245
        msg = SubElement(root, 'message')
 
246
        msg.text = rev.message
 
247
        msg.tail = '\n'
 
248
        if rev.parent_ids:
 
249
            pelts = SubElement(root, 'parents')
 
250
            pelts.tail = pelts.text = '\n'
 
251
            for parent_id in rev.parent_ids:
 
252
                assert isinstance(parent_id, basestring)
 
253
                p = SubElement(pelts, 'revision_ref')
 
254
                p.tail = '\n'
 
255
                if isinstance(parent_id, str):
 
256
                    parent_id = decode_utf8(parent_id)
 
257
                p.set('revision_id', parent_id)
 
258
        if rev.properties:
 
259
            self._pack_revision_properties(rev, root)
 
260
        return root
 
261
 
 
262
    def _pack_revision_properties(self, rev, under_element):
 
263
        top_elt = SubElement(under_element, 'properties')
 
264
        for prop_name, prop_value in sorted(rev.properties.items()):
 
265
            assert isinstance(prop_name, basestring) 
 
266
            assert isinstance(prop_value, basestring) 
 
267
            prop_elt = SubElement(top_elt, 'property')
 
268
            prop_elt.set('name', prop_name)
 
269
            prop_elt.text = prop_value
 
270
            prop_elt.tail = '\n'
 
271
        top_elt.tail = '\n'
 
272
 
 
273
    def _unpack_inventory(self, elt):
 
274
        """Construct from XML Element
 
275
        """
 
276
        assert elt.tag == 'inventory'
 
277
        root_id = elt.get('file_id') or ROOT_ID
 
278
        root_id = _get_utf8_or_ascii(root_id)
 
279
 
 
280
        format = elt.get('format')
 
281
        if format is not None:
 
282
            if format != '5':
 
283
                raise BzrError("invalid format version %r on inventory"
 
284
                                % format)
 
285
        revision_id = elt.get('revision_id')
 
286
        if revision_id is not None:
 
287
            revision_id = cache_utf8.encode(revision_id)
 
288
        inv = Inventory(root_id, revision_id=revision_id)
 
289
        for e in elt:
 
290
            ie = self._unpack_entry(e)
 
291
            if ie.parent_id is None:
 
292
                ie.parent_id = root_id
 
293
            inv.add(ie)
 
294
        return inv
 
295
 
 
296
    def _unpack_entry(self, elt):
 
297
        kind = elt.tag
 
298
        if not InventoryEntry.versionable_kind(kind):
 
299
            raise AssertionError('unsupported entry kind %s' % kind)
 
300
 
 
301
        get_cached = _get_utf8_or_ascii
 
302
 
 
303
        parent_id = elt.get('parent_id')
 
304
        if parent_id is not None:
 
305
            parent_id = get_cached(parent_id)
 
306
        file_id = get_cached(elt.get('file_id'))
 
307
 
 
308
        if kind == 'directory':
 
309
            ie = inventory.InventoryDirectory(file_id,
 
310
                                              elt.get('name'),
 
311
                                              parent_id)
 
312
        elif kind == 'file':
 
313
            ie = inventory.InventoryFile(file_id,
 
314
                                         elt.get('name'),
 
315
                                         parent_id)
 
316
            ie.text_sha1 = elt.get('text_sha1')
 
317
            if elt.get('executable') == 'yes':
 
318
                ie.executable = True
 
319
            v = elt.get('text_size')
 
320
            ie.text_size = v and int(v)
 
321
        elif kind == 'symlink':
 
322
            ie = inventory.InventoryLink(file_id,
 
323
                                         elt.get('name'),
 
324
                                         parent_id)
 
325
            ie.symlink_target = elt.get('symlink_target')
 
326
        else:
 
327
            raise BzrError("unknown kind %r" % kind)
 
328
        revision = elt.get('revision')
 
329
        if revision is not None:
 
330
            revision = get_cached(revision)
 
331
        ie.revision = revision
 
332
 
 
333
        return ie
 
334
 
 
335
    def _unpack_revision(self, elt):
 
336
        """XML Element -> Revision object"""
 
337
        assert elt.tag == 'revision'
 
338
        format = elt.get('format')
 
339
        if format is not None:
 
340
            if format != '5':
 
341
                raise BzrError("invalid format version %r on inventory"
 
342
                                % format)
 
343
        get_cached = _get_utf8_or_ascii
 
344
        rev = Revision(committer = elt.get('committer'),
 
345
                       timestamp = float(elt.get('timestamp')),
 
346
                       revision_id = get_cached(elt.get('revision_id')),
 
347
                       inventory_sha1 = elt.get('inventory_sha1')
 
348
                       )
 
349
        parents = elt.find('parents') or []
 
350
        for p in parents:
 
351
            assert p.tag == 'revision_ref', \
 
352
                   "bad parent node tag %r" % p.tag
 
353
            rev.parent_ids.append(get_cached(p.get('revision_id')))
 
354
        self._unpack_revision_properties(elt, rev)
 
355
        v = elt.get('timezone')
 
356
        if v is None:
 
357
            rev.timezone = 0
 
358
        else:
 
359
            rev.timezone = int(v)
 
360
        rev.message = elt.findtext('message') # text of <message>
 
361
        return rev
 
362
 
 
363
    def _unpack_revision_properties(self, elt, rev):
 
364
        """Unpack properties onto a revision."""
 
365
        props_elt = elt.find('properties')
 
366
        assert len(rev.properties) == 0
 
367
        if not props_elt:
 
368
            return
 
369
        for prop_elt in props_elt:
 
370
            assert prop_elt.tag == 'property', \
 
371
                "bad tag under properties list: %r" % prop_elt.tag
 
372
            name = prop_elt.get('name')
 
373
            value = prop_elt.text
 
374
            # If a property had an empty value ('') cElementTree reads
 
375
            # that back as None, convert it back to '', so that all
 
376
            # properties have string values
 
377
            if value is None:
 
378
                value = ''
 
379
            assert name not in rev.properties, \
 
380
                "repeated property %r" % name
 
381
            rev.properties[name] = value
 
382
 
 
383
 
 
384
serializer_v5 = Serializer_v5()