/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/inventory_delta.py

  • Committer: Marius Kruger
  • Date: 2010-07-10 21:28:56 UTC
  • mto: (5384.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 5385.
  • Revision ID: marius.kruger@enerweb.co.za-20100710212856-uq4ji3go0u5se7hx
* Update documentation
* add NEWS

Show diffs side-by-side

added added

removed removed

Lines of Context:
24
24
 
25
25
__all__ = ['InventoryDeltaSerializer']
26
26
 
27
 
from .. import errors
28
 
from ..osutils import basename
29
 
from . import inventory
30
 
from ..revision import NULL_REVISION
 
27
from bzrlib import errors
 
28
from bzrlib.osutils import basename
 
29
from bzrlib import inventory
 
30
from bzrlib.revision import NULL_REVISION
31
31
 
32
 
FORMAT_1 = b'bzr inventory delta v1 (bzr 1.14)'
 
32
FORMAT_1 = 'bzr inventory delta v1 (bzr 1.14)'
33
33
 
34
34
 
35
35
class InventoryDeltaError(errors.BzrError):
36
36
    """An error when serializing or deserializing an inventory delta."""
37
 
 
 
37
    
38
38
    # Most errors when serializing and deserializing are due to bugs, although
39
39
    # damaged input (i.e. a bug in a different process) could cause
40
40
    # deserialization errors too.
41
41
    internal_error = True
42
42
 
43
 
    def __init__(self, format_string, **kwargs):
44
 
        # Let each error supply a custom format string and arguments.
45
 
        self._fmt = format_string
46
 
        super(InventoryDeltaError, self).__init__(**kwargs)
47
 
 
48
43
 
49
44
class IncompatibleInventoryDelta(errors.BzrError):
50
45
    """The delta could not be deserialised because its contents conflict with
56
51
 
57
52
def _directory_content(entry):
58
53
    """Serialize the content component of entry which is a directory.
59
 
 
 
54
    
60
55
    :param entry: An InventoryDirectory.
61
56
    """
62
 
    return b"dir"
 
57
    return "dir"
63
58
 
64
59
 
65
60
def _file_content(entry):
66
61
    """Serialize the content component of entry which is a file.
67
 
 
 
62
    
68
63
    :param entry: An InventoryFile.
69
64
    """
70
65
    if entry.executable:
71
 
        exec_bytes = b'Y'
 
66
        exec_bytes = 'Y'
72
67
    else:
73
 
        exec_bytes = b''
74
 
    size_exec_sha = entry.text_size, exec_bytes, entry.text_sha1
 
68
        exec_bytes = ''
 
69
    size_exec_sha = (entry.text_size, exec_bytes, entry.text_sha1)
75
70
    if None in size_exec_sha:
76
 
        raise InventoryDeltaError(
77
 
            'Missing size or sha for %(fileid)r', fileid=entry.file_id)
78
 
    return b"file\x00%d\x00%s\x00%s" % size_exec_sha
 
71
        raise InventoryDeltaError('Missing size or sha for %s' % entry.file_id)
 
72
    return "file\x00%d\x00%s\x00%s" % size_exec_sha
79
73
 
80
74
 
81
75
def _link_content(entry):
82
76
    """Serialize the content component of entry which is a symlink.
83
 
 
 
77
    
84
78
    :param entry: An InventoryLink.
85
79
    """
86
80
    target = entry.symlink_target
87
81
    if target is None:
88
 
        raise InventoryDeltaError(
89
 
            'Missing target for %(fileid)r', fileid=entry.file_id)
90
 
    return b"link\x00%s" % target.encode('utf8')
 
82
        raise InventoryDeltaError('Missing target for %s' % entry.file_id)
 
83
    return "link\x00%s" % target.encode('utf8')
91
84
 
92
85
 
93
86
def _reference_content(entry):
94
87
    """Serialize the content component of entry which is a tree-reference.
95
 
 
 
88
    
96
89
    :param entry: A TreeReference.
97
90
    """
98
91
    tree_revision = entry.reference_revision
99
92
    if tree_revision is None:
100
93
        raise InventoryDeltaError(
101
 
            'Missing reference revision for %(fileid)r', fileid=entry.file_id)
102
 
    return b"tree\x00%s" % tree_revision
 
94
            'Missing reference revision for %s' % entry.file_id)
 
95
    return "tree\x00%s" % tree_revision
103
96
 
104
97
 
105
98
def _dir_to_entry(content, name, parent_id, file_id, last_modified,
106
 
                  _type=inventory.InventoryDirectory):
 
99
    _type=inventory.InventoryDirectory):
107
100
    """Convert a dir content record to an InventoryDirectory."""
108
101
    result = _type(file_id, name, parent_id)
109
102
    result.revision = last_modified
111
104
 
112
105
 
113
106
def _file_to_entry(content, name, parent_id, file_id, last_modified,
114
 
                   _type=inventory.InventoryFile):
 
107
    _type=inventory.InventoryFile):
115
108
    """Convert a dir content record to an InventoryFile."""
116
109
    result = _type(file_id, name, parent_id)
117
110
    result.revision = last_modified
125
118
 
126
119
 
127
120
def _link_to_entry(content, name, parent_id, file_id, last_modified,
128
 
                   _type=inventory.InventoryLink):
 
121
    _type=inventory.InventoryLink):
129
122
    """Convert a link content record to an InventoryLink."""
130
123
    result = _type(file_id, name, parent_id)
131
124
    result.revision = last_modified
134
127
 
135
128
 
136
129
def _tree_to_entry(content, name, parent_id, file_id, last_modified,
137
 
                   _type=inventory.TreeReference):
 
130
    _type=inventory.TreeReference):
138
131
    """Convert a tree content record to a TreeReference."""
139
132
    result = _type(file_id, name, parent_id)
140
133
    result.revision = last_modified
177
170
            takes.
178
171
        :return: The serialized delta as lines.
179
172
        """
180
 
        if not isinstance(old_name, bytes):
 
173
        if type(old_name) is not str:
181
174
            raise TypeError('old_name should be str, got %r' % (old_name,))
182
 
        if not isinstance(new_name, bytes):
 
175
        if type(new_name) is not str:
183
176
            raise TypeError('new_name should be str, got %r' % (new_name,))
184
 
        lines = [b'', b'', b'', b'', b'']
 
177
        lines = ['', '', '', '', '']
185
178
        to_line = self._delta_item_to_line
186
179
        for delta_item in delta_to_new:
187
180
            line = to_line(delta_item, new_name)
188
 
            # GZ 2017-06-09: Not really worth asserting this here
189
 
            if line.__class__ != bytes:
 
181
            if line.__class__ != str:
190
182
                raise InventoryDeltaError(
191
 
                    'to_line gave non-bytes output %(line)r', line=lines[-1])
 
183
                    'to_line generated non-str output %r' % lines[-1])
192
184
            lines.append(line)
193
185
        lines.sort()
194
 
        lines[0] = b"format: %s\n" % FORMAT_1
195
 
        lines[1] = b"parent: %s\n" % old_name
196
 
        lines[2] = b"version: %s\n" % new_name
197
 
        lines[3] = b"versioned_root: %s\n" % self._serialize_bool(
 
186
        lines[0] = "format: %s\n" % FORMAT_1
 
187
        lines[1] = "parent: %s\n" % old_name
 
188
        lines[2] = "version: %s\n" % new_name
 
189
        lines[3] = "versioned_root: %s\n" % self._serialize_bool(
198
190
            self._versioned_root)
199
 
        lines[4] = b"tree_references: %s\n" % self._serialize_bool(
 
191
        lines[4] = "tree_references: %s\n" % self._serialize_bool(
200
192
            self._tree_references)
201
193
        return lines
202
194
 
203
195
    def _serialize_bool(self, value):
204
196
        if value:
205
 
            return b"true"
 
197
            return "true"
206
198
        else:
207
 
            return b"false"
 
199
            return "false"
208
200
 
209
201
    def _delta_item_to_line(self, delta_item, new_version):
210
202
        """Convert delta_item to a line."""
211
203
        oldpath, newpath, file_id, entry = delta_item
212
204
        if newpath is None:
213
205
            # delete
214
 
            oldpath_utf8 = b'/' + oldpath.encode('utf8')
215
 
            newpath_utf8 = b'None'
216
 
            parent_id = b''
 
206
            oldpath_utf8 = '/' + oldpath.encode('utf8')
 
207
            newpath_utf8 = 'None'
 
208
            parent_id = ''
217
209
            last_modified = NULL_REVISION
218
 
            content = b'deleted\x00\x00'
 
210
            content = 'deleted\x00\x00'
219
211
        else:
220
212
            if oldpath is None:
221
 
                oldpath_utf8 = b'None'
 
213
                oldpath_utf8 = 'None'
222
214
            else:
223
 
                oldpath_utf8 = b'/' + oldpath.encode('utf8')
 
215
                oldpath_utf8 = '/' + oldpath.encode('utf8')
224
216
            if newpath == '/':
225
217
                raise AssertionError(
226
218
                    "Bad inventory delta: '/' is not a valid newpath "
227
219
                    "(should be '') in delta item %r" % (delta_item,))
228
220
            # TODO: Test real-world utf8 cache hit rate. It may be a win.
229
 
            newpath_utf8 = b'/' + newpath.encode('utf8')
 
221
            newpath_utf8 = '/' + newpath.encode('utf8')
230
222
            # Serialize None as ''
231
 
            parent_id = entry.parent_id or b''
 
223
            parent_id = entry.parent_id or ''
232
224
            # Serialize unknown revisions as NULL_REVISION
233
225
            last_modified = entry.revision
234
226
            # special cases for /
235
 
            if newpath_utf8 == b'/' and not self._versioned_root:
 
227
            if newpath_utf8 == '/' and not self._versioned_root:
236
228
                # This is an entry for the root, this inventory does not
237
229
                # support versioned roots.  So this must be an unversioned
238
230
                # root, i.e. last_modified == new revision.  Otherwise, this
242
234
                # xml5 serializer.
243
235
                if last_modified != new_version:
244
236
                    raise InventoryDeltaError(
245
 
                        'Version present for / in %(fileid)r'
246
 
                        ' (%(last)r != %(new)r)',
247
 
                        fileid=file_id, last=last_modified, new=new_version)
 
237
                        'Version present for / in %s (%s != %s)'
 
238
                        % (file_id, last_modified, new_version))
248
239
            if last_modified is None:
249
 
                raise InventoryDeltaError(
250
 
                    "no version for fileid %(fileid)r", fileid=file_id)
 
240
                raise InventoryDeltaError("no version for fileid %s" % file_id)
251
241
            content = self._entry_to_content[entry.kind](entry)
252
 
        return (b"%s\x00%s\x00%s\x00%s\x00%s\x00%s\n" %
253
 
                (oldpath_utf8, newpath_utf8, file_id, parent_id, last_modified,
254
 
                 content))
 
242
        return ("%s\x00%s\x00%s\x00%s\x00%s\x00%s\n" %
 
243
            (oldpath_utf8, newpath_utf8, file_id, parent_id, last_modified,
 
244
                content))
255
245
 
256
246
 
257
247
class InventoryDeltaDeserializer(object):
268
258
        self._allow_tree_references = allow_tree_references
269
259
 
270
260
    def _deserialize_bool(self, value):
271
 
        if value == b"true":
 
261
        if value == "true":
272
262
            return True
273
 
        elif value == b"false":
 
263
        elif value == "false":
274
264
            return False
275
265
        else:
276
 
            raise InventoryDeltaError("value %(val)r is not a bool", val=value)
 
266
            raise InventoryDeltaError("value %r is not a bool" % (value,))
277
267
 
278
 
    def parse_text_bytes(self, lines):
 
268
    def parse_text_bytes(self, bytes):
279
269
        """Parse the text bytes of a serialized inventory delta.
280
270
 
281
271
        If versioned_root and/or tree_references flags were set via
282
272
        require_flags, then the parsed flags must match or a BzrError will be
283
273
        raised.
284
274
 
285
 
        :param lines: The lines to parse. This can be obtained by calling
286
 
            delta_to_lines.
 
275
        :param bytes: The bytes to parse. This can be obtained by calling
 
276
            delta_to_lines and then doing ''.join(delta_lines).
287
277
        :return: (parent_id, new_id, versioned_root, tree_references,
288
278
            inventory_delta)
289
279
        """
290
 
        if not lines:
291
 
            raise InventoryDeltaError(
292
 
                'inventory delta is empty')
293
 
        if not lines[-1].endswith(b'\n'):
294
 
            raise InventoryDeltaError(
295
 
                'last line not empty: %(line)r', line=lines[-1])
296
 
        lines = [line.rstrip(b'\n') for line in lines]  # discard the last empty line
297
 
        if not lines or lines[0] != b'format: %s' % FORMAT_1:
298
 
            raise InventoryDeltaError(
299
 
                'unknown format %(line)r', line=lines[0:1])
300
 
        if len(lines) < 2 or not lines[1].startswith(b'parent: '):
 
280
        if bytes[-1:] != '\n':
 
281
            last_line = bytes.rsplit('\n', 1)[-1]
 
282
            raise InventoryDeltaError('last line not empty: %r' % (last_line,))
 
283
        lines = bytes.split('\n')[:-1] # discard the last empty line
 
284
        if not lines or lines[0] != 'format: %s' % FORMAT_1:
 
285
            raise InventoryDeltaError('unknown format %r' % lines[0:1])
 
286
        if len(lines) < 2 or not lines[1].startswith('parent: '):
301
287
            raise InventoryDeltaError('missing parent: marker')
302
288
        delta_parent_id = lines[1][8:]
303
 
        if len(lines) < 3 or not lines[2].startswith(b'version: '):
 
289
        if len(lines) < 3 or not lines[2].startswith('version: '):
304
290
            raise InventoryDeltaError('missing version: marker')
305
291
        delta_version_id = lines[2][9:]
306
 
        if len(lines) < 4 or not lines[3].startswith(b'versioned_root: '):
 
292
        if len(lines) < 4 or not lines[3].startswith('versioned_root: '):
307
293
            raise InventoryDeltaError('missing versioned_root: marker')
308
294
        delta_versioned_root = self._deserialize_bool(lines[3][16:])
309
 
        if len(lines) < 5 or not lines[4].startswith(b'tree_references: '):
 
295
        if len(lines) < 5 or not lines[4].startswith('tree_references: '):
310
296
            raise InventoryDeltaError('missing tree_references: marker')
311
297
        delta_tree_references = self._deserialize_bool(lines[4][17:])
312
298
        if (not self._allow_versioned_root and delta_versioned_root):
315
301
        seen_ids = set()
316
302
        line_iter = iter(lines)
317
303
        for i in range(5):
318
 
            next(line_iter)
 
304
            line_iter.next()
319
305
        for line in line_iter:
320
306
            (oldpath_utf8, newpath_utf8, file_id, parent_id, last_modified,
321
 
                content) = line.split(b'\x00', 5)
 
307
                content) = line.split('\x00', 5)
322
308
            parent_id = parent_id or None
323
309
            if file_id in seen_ids:
324
310
                raise InventoryDeltaError(
325
 
                    "duplicate file id %(fileid)r", fileid=file_id)
 
311
                    "duplicate file id in inventory delta %r" % lines)
326
312
            seen_ids.add(file_id)
327
 
            if (newpath_utf8 == b'/' and not delta_versioned_root and
328
 
                    last_modified != delta_version_id):
329
 
                # Delta claims to be not have a versioned root, yet here's
330
 
                # a root entry with a non-default version.
331
 
                raise InventoryDeltaError(
332
 
                    "Versioned root found: %(line)r", line=line)
333
 
            elif newpath_utf8 != b'None' and last_modified[-1:] == b':':
 
313
            if (newpath_utf8 == '/' and not delta_versioned_root and
 
314
                last_modified != delta_version_id):
 
315
                    # Delta claims to be not have a versioned root, yet here's
 
316
                    # a root entry with a non-default version.
 
317
                    raise InventoryDeltaError("Versioned root found: %r" % line)
 
318
            elif newpath_utf8 != 'None' and last_modified[-1] == ':':
334
319
                # Deletes have a last_modified of null:, but otherwise special
335
320
                # revision ids should not occur.
336
 
                raise InventoryDeltaError(
337
 
                    'special revisionid found: %(line)r', line=line)
338
 
            if content.startswith(b'tree\x00'):
 
321
                raise InventoryDeltaError('special revisionid found: %r' % line)
 
322
            if content.startswith('tree\x00'):
339
323
                if delta_tree_references is False:
340
324
                    raise InventoryDeltaError(
341
 
                        "Tree reference found (but header said "
342
 
                        "tree_references: false): %(line)r", line=line)
 
325
                            "Tree reference found (but header said "
 
326
                            "tree_references: false): %r" % line)
343
327
                elif not self._allow_tree_references:
344
328
                    raise IncompatibleInventoryDelta(
345
329
                        "Tree reference not allowed")
346
 
            if oldpath_utf8 == b'None':
 
330
            if oldpath_utf8 == 'None':
347
331
                oldpath = None
348
 
            elif oldpath_utf8[:1] != b'/':
 
332
            elif oldpath_utf8[:1] != '/':
349
333
                raise InventoryDeltaError(
350
 
                    "oldpath invalid (does not start with /): %(path)r",
351
 
                    path=oldpath_utf8)
 
334
                    "oldpath invalid (does not start with /): %r"
 
335
                    % (oldpath_utf8,))
352
336
            else:
353
337
                oldpath_utf8 = oldpath_utf8[1:]
354
338
                oldpath = oldpath_utf8.decode('utf8')
355
 
            if newpath_utf8 == b'None':
 
339
            if newpath_utf8 == 'None':
356
340
                newpath = None
357
 
            elif newpath_utf8[:1] != b'/':
 
341
            elif newpath_utf8[:1] != '/':
358
342
                raise InventoryDeltaError(
359
 
                    "newpath invalid (does not start with /): %(path)r",
360
 
                    path=newpath_utf8)
 
343
                    "newpath invalid (does not start with /): %r"
 
344
                    % (newpath_utf8,))
361
345
            else:
362
346
                # Trim leading slash
363
347
                newpath_utf8 = newpath_utf8[1:]
364
348
                newpath = newpath_utf8.decode('utf8')
365
 
            content_tuple = tuple(content.split(b'\x00'))
366
 
            if content_tuple[0] == b'deleted':
 
349
            content_tuple = tuple(content.split('\x00'))
 
350
            if content_tuple[0] == 'deleted':
367
351
                entry = None
368
352
            else:
369
353
                entry = _parse_entry(
376
360
 
377
361
def _parse_entry(path, file_id, parent_id, last_modified, content):
378
362
    entry_factory = {
379
 
        b'dir': _dir_to_entry,
380
 
        b'file': _file_to_entry,
381
 
        b'link': _link_to_entry,
382
 
        b'tree': _tree_to_entry,
 
363
        'dir': _dir_to_entry,
 
364
        'file': _file_to_entry,
 
365
        'link': _link_to_entry,
 
366
        'tree': _tree_to_entry,
383
367
    }
384
368
    kind = content[0]
385
369
    if path.startswith('/'):
386
370
        raise AssertionError
387
371
    name = basename(path)
388
372
    return entry_factory[content[0]](
389
 
        content, name, parent_id, file_id, last_modified)
 
373
            content, name, parent_id, file_id, last_modified)
 
374
 
 
375