/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
4763.2.4 by John Arbash Meinel
merge bzr.2.1 in preparation for NEWS entry.
1
# Copyright (C) 2008, 2009, 2010 Canonical Ltd
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
17
"""Serializer object for CHK based inventory storage."""
18
6355.1.5 by Jelmer Vernooij
Use lazy imports.
19
from cStringIO import StringIO
20
21
from bzrlib import lazy_import
22
lazy_import.lazy_import(globals(),
23
"""
24
from bzrlib import (
25
    xml_serializer,
26
    )
27
""")
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
28
from bzrlib import (
4398.5.2 by John Arbash Meinel
Merge the chk serializer, and update it for the new bencode locations.
29
    bencode,
4290.1.1 by Jelmer Vernooij
Add simple revision serializer based on RIO.
30
    cache_utf8,
6355.1.3 by Jelmer Vernooij
Split out more stuff.
31
    errors,
4290.1.1 by Jelmer Vernooij
Add simple revision serializer based on RIO.
32
    revision as _mod_revision,
6355.1.3 by Jelmer Vernooij
Split out more stuff.
33
    serializer,
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
34
    )
35
4398.5.9 by John Arbash Meinel
it seems that codecs.utf_8_decode is quite a bit faster than codecs.get_decoder('utf-8')
36
37
def _validate_properties(props, _decode=cache_utf8._utf8_decode):
4398.5.5 by John Arbash Meinel
Update the CHK Serializer to do lots more validation.
38
    # TODO: we really want an 'isascii' check for key
4398.5.15 by John Arbash Meinel
Change how schemas are validated (down to 1.02s)
39
    # Cast the utf8 properties into Unicode 'in place'
40
    for key, value in props.iteritems():
41
        props[key] = _decode(value)[0]
42
    return props
4398.5.5 by John Arbash Meinel
Update the CHK Serializer to do lots more validation.
43
44
45
def _is_format_10(value):
46
    if value != 10:
47
        raise ValueError('Format number was not recognized, expected 10 got %d'
48
                         % (value,))
49
    return 10
50
51
4290.1.12 by Jelmer Vernooij
Use bencode rather than rio in the new revision serialiszer.
52
class BEncodeRevisionSerializer1(object):
4398.5.5 by John Arbash Meinel
Update the CHK Serializer to do lots more validation.
53
    """Simple revision serializer based around bencode.
4290.1.1 by Jelmer Vernooij
Add simple revision serializer based on RIO.
54
    """
55
4416.5.1 by Jelmer Vernooij
Move squashing of XML-invalid characters to XMLSerializer.
56
    squashes_xml_invalid_characters = False
57
4398.5.5 by John Arbash Meinel
Update the CHK Serializer to do lots more validation.
58
    # Maps {key:(Revision attribute, bencode_type, validator)}
59
    # This tells us what kind we expect bdecode to create, what variable on
60
    # Revision we should be using, and a function to call to validate/transform
61
    # the type.
62
    # TODO: add a 'validate_utf8' for things like revision_id and file_id
63
    #       and a validator for parent-ids
64
    _schema = {'format': (None, int, _is_format_10),
4398.5.9 by John Arbash Meinel
it seems that codecs.utf_8_decode is quite a bit faster than codecs.get_decoder('utf-8')
65
               'committer': ('committer', str, cache_utf8.decode),
4398.5.5 by John Arbash Meinel
Update the CHK Serializer to do lots more validation.
66
               'timezone': ('timezone', int, None),
67
               'timestamp': ('timestamp', str, float),
68
               'revision-id': ('revision_id', str, None),
4398.5.19 by John Arbash Meinel
Change parent_ids back to a list, because there are other tests that expect it.
69
               'parent-ids': ('parent_ids', list, None),
4398.5.5 by John Arbash Meinel
Update the CHK Serializer to do lots more validation.
70
               'inventory-sha1': ('inventory_sha1', str, None),
4398.5.9 by John Arbash Meinel
it seems that codecs.utf_8_decode is quite a bit faster than codecs.get_decoder('utf-8')
71
               'message': ('message', str, cache_utf8.decode),
4398.5.5 by John Arbash Meinel
Update the CHK Serializer to do lots more validation.
72
               'properties': ('properties', dict, _validate_properties),
73
    }
74
4290.1.12 by Jelmer Vernooij
Use bencode rather than rio in the new revision serialiszer.
75
    def write_revision_to_string(self, rev):
4398.5.9 by John Arbash Meinel
it seems that codecs.utf_8_decode is quite a bit faster than codecs.get_decoder('utf-8')
76
        encode_utf8 = cache_utf8._utf8_encode
4398.5.5 by John Arbash Meinel
Update the CHK Serializer to do lots more validation.
77
        # Use a list of tuples rather than a dict
78
        # This lets us control the ordering, so that we are able to create
79
        # smaller deltas
80
        ret = [
81
            ("format", 10),
4398.5.9 by John Arbash Meinel
it seems that codecs.utf_8_decode is quite a bit faster than codecs.get_decoder('utf-8')
82
            ("committer", encode_utf8(rev.committer)[0]),
4398.5.5 by John Arbash Meinel
Update the CHK Serializer to do lots more validation.
83
        ]
84
        if rev.timezone is not None:
85
            ret.append(("timezone", rev.timezone))
86
        # For bzr revisions, the most common property is just 'branch-nick'
87
        # which changes infrequently.
4290.1.12 by Jelmer Vernooij
Use bencode rather than rio in the new revision serialiszer.
88
        revprops = {}
89
        for key, value in rev.properties.iteritems():
4398.5.9 by John Arbash Meinel
it seems that codecs.utf_8_decode is quite a bit faster than codecs.get_decoder('utf-8')
90
            revprops[key] = encode_utf8(value)[0]
4398.5.5 by John Arbash Meinel
Update the CHK Serializer to do lots more validation.
91
        ret.append(('properties', revprops))
92
        ret.extend([
93
            ("timestamp", "%.3f" % rev.timestamp),
94
            ("revision-id", rev.revision_id),
95
            ("parent-ids", rev.parent_ids),
96
            ("inventory-sha1", rev.inventory_sha1),
4398.5.9 by John Arbash Meinel
it seems that codecs.utf_8_decode is quite a bit faster than codecs.get_decoder('utf-8')
97
            ("message", encode_utf8(rev.message)[0]),
4398.5.5 by John Arbash Meinel
Update the CHK Serializer to do lots more validation.
98
        ])
4398.5.2 by John Arbash Meinel
Merge the chk serializer, and update it for the new bencode locations.
99
        return bencode.bencode(ret)
4290.1.8 by Jelmer Vernooij
Some performance tweaks.
100
101
    def write_revision(self, rev, f):
4290.1.12 by Jelmer Vernooij
Use bencode rather than rio in the new revision serialiszer.
102
        f.write(self.write_revision_to_string(rev))
103
104
    def read_revision_from_string(self, text):
4398.5.5 by John Arbash Meinel
Update the CHK Serializer to do lots more validation.
105
        # TODO: consider writing a Revision decoder, rather than using the
106
        #       generic bencode decoder
4398.5.8 by John Arbash Meinel
Update the TODO comment a bit.
107
        #       However, to decode all 25k revisions of bzr takes approx 1.3s
108
        #       If we remove all extra validation that goes down to about 1.2s.
109
        #       Of that time, probably 0.6s is spend in bencode.bdecode().
110
        #       Regardless 'time bzr log' of everything is 7+s, so 1.3s to
111
        #       extract revision texts isn't a majority of time.
4398.5.2 by John Arbash Meinel
Merge the chk serializer, and update it for the new bencode locations.
112
        ret = bencode.bdecode(text)
4398.5.5 by John Arbash Meinel
Update the CHK Serializer to do lots more validation.
113
        if not isinstance(ret, list):
114
            raise ValueError("invalid revision text")
4398.5.15 by John Arbash Meinel
Change how schemas are validated (down to 1.02s)
115
        schema = self._schema
4398.5.7 by John Arbash Meinel
Spend a little bit more time optimizing the read_revision_from_string loop
116
        # timezone is allowed to be missing, but should be set
117
        bits = {'timezone': None}
4398.5.5 by John Arbash Meinel
Update the CHK Serializer to do lots more validation.
118
        for key, value in ret:
4398.5.7 by John Arbash Meinel
Spend a little bit more time optimizing the read_revision_from_string loop
119
            # Will raise KeyError if not a valid part of the schema, or an
120
            # entry is given 2 times.
4398.5.15 by John Arbash Meinel
Change how schemas are validated (down to 1.02s)
121
            var_name, expected_type, validator = schema[key]
4398.5.5 by John Arbash Meinel
Update the CHK Serializer to do lots more validation.
122
            if value.__class__ is not expected_type:
123
                raise ValueError('key %s did not conform to the expected type'
124
                                 ' %s, but was %s'
125
                                 % (key, expected_type, type(value)))
126
            if validator is not None:
127
                value = validator(value)
4398.5.7 by John Arbash Meinel
Spend a little bit more time optimizing the read_revision_from_string loop
128
            bits[var_name] = value
4398.5.15 by John Arbash Meinel
Change how schemas are validated (down to 1.02s)
129
        if len(bits) != len(schema):
130
            missing = [key for key, (var_name, _, _) in schema.iteritems()
131
                       if var_name not in bits]
132
            raise ValueError('Revision text was missing expected keys %s.'
133
                             ' text %r' % (missing, text))
134
        del bits[None]  # Get rid of 'format' since it doesn't get mapped
4398.5.5 by John Arbash Meinel
Update the CHK Serializer to do lots more validation.
135
        rev = _mod_revision.Revision(**bits)
4290.1.8 by Jelmer Vernooij
Some performance tweaks.
136
        return rev
137
138
    def read_revision(self, f):
4290.1.12 by Jelmer Vernooij
Use bencode rather than rio in the new revision serialiszer.
139
        return self.read_revision_from_string(f.read())
140
141
6355.1.3 by Jelmer Vernooij
Split out more stuff.
142
class CHKSerializer(serializer.Serializer):
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
143
    """A CHKInventory based serializer with 'plain' behaviour."""
144
145
    format_num = '9'
146
    revision_format_num = None
147
    support_altered_by_hack = False
6355.1.3 by Jelmer Vernooij
Split out more stuff.
148
    supported_kinds = set(['file', 'directory', 'symlink'])
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
149
150
    def __init__(self, node_size, search_key_name):
151
        self.maximum_size = node_size
152
        self.search_key_name = search_key_name
153
6355.1.6 by Jelmer Vernooij
Move core inventory code to xml_serializer.
154
    def _unpack_inventory(self, elt, revision_id=None, entry_cache=None,
155
                          return_from_cache=False):
156
        """Construct from XML Element"""
157
        inv = xml_serializer.unpack_inventory_flat(elt, self.format_num,
6355.1.9 by Jelmer Vernooij
Review feedback - pass entry_cache and_return_from_cache to unpack_inventory_flat.
158
            xml_serializer.unpack_inventory_entry, entry_cache,
159
            return_from_cache)
6355.1.6 by Jelmer Vernooij
Move core inventory code to xml_serializer.
160
        return inv
161
6355.1.3 by Jelmer Vernooij
Split out more stuff.
162
    def read_inventory_from_string(self, xml_string, revision_id=None,
163
                                   entry_cache=None, return_from_cache=False):
164
        """Read xml_string into an inventory object.
165
166
        :param xml_string: The xml to read.
167
        :param revision_id: If not-None, the expected revision id of the
168
            inventory.
169
        :param entry_cache: An optional cache of InventoryEntry objects. If
170
            supplied we will look up entries via (file_id, revision_id) which
171
            should map to a valid InventoryEntry (File/Directory/etc) object.
172
        :param return_from_cache: Return entries directly from the cache,
173
            rather than copying them first. This is only safe if the caller
174
            promises not to mutate the returned inventory entries, but it can
175
            make some operations significantly faster.
176
        """
177
        try:
6355.1.6 by Jelmer Vernooij
Move core inventory code to xml_serializer.
178
            return self._unpack_inventory(
179
                xml_serializer.fromstring(xml_string), revision_id,
180
                entry_cache=entry_cache,
181
                return_from_cache=return_from_cache)
6355.1.5 by Jelmer Vernooij
Use lazy imports.
182
        except xml_serializer.ParseError, e:
6355.1.3 by Jelmer Vernooij
Split out more stuff.
183
            raise errors.UnexpectedInventoryFormat(e)
184
185
    def read_inventory(self, f, revision_id=None):
6355.1.6 by Jelmer Vernooij
Move core inventory code to xml_serializer.
186
        """Read an inventory from a file-like object."""
6355.1.3 by Jelmer Vernooij
Split out more stuff.
187
        try:
188
            try:
189
                return self._unpack_inventory(self._read_element(f),
190
                    revision_id=None)
191
            finally:
192
                f.close()
6355.1.5 by Jelmer Vernooij
Use lazy imports.
193
        except xml_serializer.ParseError, e:
6355.1.3 by Jelmer Vernooij
Split out more stuff.
194
            raise errors.UnexpectedInventoryFormat(e)
195
196
    def write_inventory_to_lines(self, inv):
197
        """Return a list of lines with the encoded inventory."""
198
        return self.write_inventory(inv, None)
199
200
    def write_inventory_to_string(self, inv, working=False):
201
        """Just call write_inventory with a StringIO and return the value.
202
203
        :param working: If True skip history data - text_sha1, text_size,
204
            reference_revision, symlink_target.
205
        """
206
        sio = StringIO()
207
        self.write_inventory(inv, sio, working)
208
        return sio.getvalue()
209
210
    def write_inventory(self, inv, f, working=False):
211
        """Write inventory to a file.
212
213
        :param inv: the inventory to write.
214
        :param f: the file to write. (May be None if the lines are the desired
215
            output).
216
        :param working: If True skip history data - text_sha1, text_size,
217
            reference_revision, symlink_target.
218
        :return: The inventory as a list of lines.
219
        """
6355.1.7 by Jelmer Vernooij
Fix tests.
220
        output = []
221
        append = output.append
6355.1.6 by Jelmer Vernooij
Move core inventory code to xml_serializer.
222
        if inv.revision_id is not None:
223
            revid1 = ' revision_id="'
224
            revid2 = xml_serializer.encode_and_escape(inv.revision_id)
225
        else:
226
            revid1 = ""
227
            revid2 = ""
228
        append('<inventory format="%s"%s%s>\n' % (
229
            self.format_num, revid1, revid2))
230
        append('<directory file_id="%s name="%s revision="%s />\n' % (
231
            xml_serializer.encode_and_escape(inv.root.file_id),
232
            xml_serializer.encode_and_escape(inv.root.name),
233
            xml_serializer.encode_and_escape(inv.root.revision)))
6355.1.7 by Jelmer Vernooij
Fix tests.
234
        xml_serializer.serialize_inventory_flat(inv,
235
            append,
236
            root_id=None, supported_kinds=self.supported_kinds, 
237
            working=working)
238
        if f is not None:
239
            f.writelines(output)
240
        return output
6355.1.6 by Jelmer Vernooij
Move core inventory code to xml_serializer.
241
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
242
243
chk_serializer_255_bigpage = CHKSerializer(65536, 'hash-255-way')
4290.1.7 by Jelmer Vernooij
Add development7-rich-root format that uses the RIO Serializer.
244
245
4290.1.12 by Jelmer Vernooij
Use bencode rather than rio in the new revision serialiszer.
246
class CHKBEncodeSerializer(BEncodeRevisionSerializer1, CHKSerializer):
247
    """A CHKInventory and BEncode based serializer with 'plain' behaviour."""
4290.1.7 by Jelmer Vernooij
Add development7-rich-root format that uses the RIO Serializer.
248
249
    format_num = '10'
250
251
4290.1.12 by Jelmer Vernooij
Use bencode rather than rio in the new revision serialiszer.
252
chk_bencode_serializer = CHKBEncodeSerializer(65536, 'hash-255-way')