~bzr-pqm/bzr/bzr.dev

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# Copyright (C) 2008 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

"""Serializer object for CHK based inventory storage."""

from cStringIO import (
    StringIO,
    )

from bzrlib import (
    bencode,
    cache_utf8,
    inventory,
    osutils,
    revision as _mod_revision,
    xml5,
    xml6,
    )

_decode_utf8 = cache_utf8.decode


def _validate_properties(props):
    decode = _decode_utf8
    # TODO: we really want an 'isascii' check for key
    unicode_props = dict((key, _decode_utf8(value))
                         for key, value in props.iteritems())
    return unicode_props


def _is_format_10(value):
    if value != 10:
        raise ValueError('Format number was not recognized, expected 10 got %d'
                         % (value,))
    return 10


class BEncodeRevisionSerializer1(object):
    """Simple revision serializer based around bencode.
    """

    # Maps {key:(Revision attribute, bencode_type, validator)}
    # This tells us what kind we expect bdecode to create, what variable on
    # Revision we should be using, and a function to call to validate/transform
    # the type.
    # TODO: add a 'validate_utf8' for things like revision_id and file_id
    #       and a validator for parent-ids
    _schema = {'format': (None, int, _is_format_10),
               'committer': ('committer', str, _decode_utf8),
               'timezone': ('timezone', int, None),
               'timestamp': ('timestamp', str, float),
               'revision-id': ('revision_id', str, None),
               'parent-ids': ('parent_ids', list, tuple),
               'inventory-sha1': ('inventory_sha1', str, None),
               'message': ('message', str, _decode_utf8),
               'properties': ('properties', dict, _validate_properties),
    }

    def write_revision_to_string(self, rev):
        encode_utf8 = cache_utf8.encode
        # Use a list of tuples rather than a dict
        # This lets us control the ordering, so that we are able to create
        # smaller deltas
        ret = [
            ("format", 10),
            ("committer", encode_utf8(rev.committer)),
        ]
        if rev.timezone is not None:
            ret.append(("timezone", rev.timezone))
        # For bzr revisions, the most common property is just 'branch-nick'
        # which changes infrequently.
        revprops = {}
        for key, value in rev.properties.iteritems():
            revprops[key] = encode_utf8(value)
        ret.append(('properties', revprops))
        ret.extend([
            ("timestamp", "%.3f" % rev.timestamp),
            ("revision-id", rev.revision_id),
            ("parent-ids", rev.parent_ids),
            ("inventory-sha1", rev.inventory_sha1),
            ("message", encode_utf8(rev.message)),
        ])
        return bencode.bencode(ret)

    def write_revision(self, rev, f):
        f.write(self.write_revision_to_string(rev))

    def read_revision_from_string(self, text):
        # TODO: consider writing a Revision decoder, rather than using the
        #       generic bencode decoder
        decode_utf8 = cache_utf8.decode
        ret = bencode.bdecode(text)
        if not isinstance(ret, list):
            raise ValueError("invalid revision text")
        schema = dict(self._schema)
        bits = {}
        for key, value in ret:
            # The entry must be present in allowed keys, but only present a
            # single time
            var_name, expected_type, validator = schema.pop(key)
            if value.__class__ is not expected_type:
                raise ValueError('key %s did not conform to the expected type'
                                 ' %s, but was %s'
                                 % (key, expected_type, type(value)))
            if validator is not None:
                value = validator(value)
            if var_name is not None:
                bits[var_name] = value
        if schema.keys() not in ([], ['timezone']):
            raise ValueError('Revision text was missing expected keys %s,'
                             ' text %r' % (schema.keys(), text))
        rev = _mod_revision.Revision(**bits)
        if "timezone" not in bits:
            rev.timezone = None
        return rev

    def read_revision(self, f):
        return self.read_revision_from_string(f.read())


class CHKSerializerSubtree(BEncodeRevisionSerializer1, xml6.Serializer_v6):
    """A CHKInventory based serializer that supports tree references"""

    supported_kinds = set(['file', 'directory', 'symlink', 'tree-reference'])
    format_num = '9'
    revision_format_num = None
    support_altered_by_hack = False

    def _unpack_entry(self, elt):
        kind = elt.tag
        if not kind in self.supported_kinds:
            raise AssertionError('unsupported entry kind %s' % kind)
        if kind == 'tree-reference':
            file_id = elt.attrib['file_id']
            name = elt.attrib['name']
            parent_id = elt.attrib['parent_id']
            revision = elt.get('revision')
            reference_revision = elt.get('reference_revision')
            return inventory.TreeReference(file_id, name, parent_id, revision,
                                           reference_revision)
        else:
            return xml6.Serializer_v6._unpack_entry(self, elt)

    def __init__(self, node_size, search_key_name):
        self.maximum_size = node_size
        self.search_key_name = search_key_name


class CHKSerializer(xml5.Serializer_v5):
    """A CHKInventory based serializer with 'plain' behaviour."""

    format_num = '9'
    revision_format_num = None
    support_altered_by_hack = False

    def __init__(self, node_size, search_key_name):
        self.maximum_size = node_size
        self.search_key_name = search_key_name


chk_serializer_255_bigpage = CHKSerializer(65536, 'hash-255-way')


class CHKBEncodeSerializer(BEncodeRevisionSerializer1, CHKSerializer):
    """A CHKInventory and BEncode based serializer with 'plain' behaviour."""

    format_num = '10'


chk_bencode_serializer = CHKBEncodeSerializer(65536, 'hash-255-way')