~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/bundle/serializer/v4.py

  • Committer: Martin Pool
  • Date: 2005-05-11 10:14:09 UTC
  • Revision ID: mbp@sourcefrog.net-20050511101409-25634506a9caacfd
- move commit code into its own module
- remove some doctest tests in favour of black-box tests
- specific-file parameters for diff and status now cover all
  files inside a directory

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2007-2010 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
 
 
17
 
from cStringIO import StringIO
18
 
import bz2
19
 
import re
20
 
 
21
 
from bzrlib import (
22
 
    diff,
23
 
    errors,
24
 
    iterablefile,
25
 
    lru_cache,
26
 
    multiparent,
27
 
    osutils,
28
 
    pack,
29
 
    revision as _mod_revision,
30
 
    serializer,
31
 
    trace,
32
 
    ui,
33
 
    versionedfile as _mod_versionedfile,
34
 
    )
35
 
from bzrlib.bundle import bundle_data, serializer as bundle_serializer
36
 
from bzrlib.i18n import gettext, ngettext
37
 
from bzrlib import bencode
38
 
 
39
 
 
40
 
class _MPDiffInventoryGenerator(_mod_versionedfile._MPDiffGenerator):
41
 
    """Generate Inventory diffs serialized inventories."""
42
 
 
43
 
    def __init__(self, repo, inventory_keys):
44
 
        super(_MPDiffInventoryGenerator, self).__init__(repo.inventories,
45
 
            inventory_keys)
46
 
        self.repo = repo
47
 
        self.sha1s = {}
48
 
 
49
 
    def iter_diffs(self):
50
 
        """Compute the diffs one at a time."""
51
 
        # This is instead of compute_diffs() since we guarantee our ordering of
52
 
        # inventories, we don't have to do any buffering
53
 
        self._find_needed_keys()
54
 
        # We actually use a slightly different ordering. We grab all of the
55
 
        # parents first, and then grab the ordered requests.
56
 
        needed_ids = [k[-1] for k in self.present_parents]
57
 
        needed_ids.extend([k[-1] for k in self.ordered_keys])
58
 
        inv_to_str = self.repo._serializer.write_inventory_to_string
59
 
        for inv in self.repo.iter_inventories(needed_ids):
60
 
            revision_id = inv.revision_id
61
 
            key = (revision_id,)
62
 
            if key in self.present_parents:
63
 
                # Not a key we will transmit, which is a shame, since because
64
 
                # of that bundles don't work with stacked branches
65
 
                parent_ids = None
66
 
            else:
67
 
                parent_ids = [k[-1] for k in self.parent_map[key]]
68
 
            as_bytes = inv_to_str(inv)
69
 
            self._process_one_record(key, (as_bytes,))
70
 
            if parent_ids is None:
71
 
                continue
72
 
            diff = self.diffs.pop(key)
73
 
            sha1 = osutils.sha_string(as_bytes)
74
 
            yield revision_id, parent_ids, sha1, diff
75
 
 
76
 
 
77
 
class BundleWriter(object):
78
 
    """Writer for bundle-format files.
79
 
 
80
 
    This serves roughly the same purpose as ContainerReader, but acts as a
81
 
    layer on top of it.
82
 
 
83
 
    Provides ways of writing the specific record types supported this bundle
84
 
    format.
85
 
    """
86
 
 
87
 
    def __init__(self, fileobj):
88
 
        self._container = pack.ContainerWriter(self._write_encoded)
89
 
        self._fileobj = fileobj
90
 
        self._compressor = bz2.BZ2Compressor()
91
 
 
92
 
    def _write_encoded(self, bytes):
93
 
        """Write bzip2-encoded bytes to the file"""
94
 
        self._fileobj.write(self._compressor.compress(bytes))
95
 
 
96
 
    def begin(self):
97
 
        """Start writing the bundle"""
98
 
        self._fileobj.write(bundle_serializer._get_bundle_header(
99
 
            bundle_serializer.v4_string))
100
 
        self._fileobj.write('#\n')
101
 
        self._container.begin()
102
 
 
103
 
    def end(self):
104
 
        """Finish writing the bundle"""
105
 
        self._container.end()
106
 
        self._fileobj.write(self._compressor.flush())
107
 
 
108
 
    def add_multiparent_record(self, mp_bytes, sha1, parents, repo_kind,
109
 
                               revision_id, file_id):
110
 
        """Add a record for a multi-parent diff
111
 
 
112
 
        :mp_bytes: A multi-parent diff, as a bytestring
113
 
        :sha1: The sha1 hash of the fulltext
114
 
        :parents: a list of revision-ids of the parents
115
 
        :repo_kind: The kind of object in the repository.  May be 'file' or
116
 
            'inventory'
117
 
        :revision_id: The revision id of the mpdiff being added.
118
 
        :file_id: The file-id of the file, or None for inventories.
119
 
        """
120
 
        metadata = {'parents': parents,
121
 
                    'storage_kind': 'mpdiff',
122
 
                    'sha1': sha1}
123
 
        self._add_record(mp_bytes, metadata, repo_kind, revision_id, file_id)
124
 
 
125
 
    def add_fulltext_record(self, bytes, parents, repo_kind, revision_id):
126
 
        """Add a record for a fulltext
127
 
 
128
 
        :bytes: The fulltext, as a bytestring
129
 
        :parents: a list of revision-ids of the parents
130
 
        :repo_kind: The kind of object in the repository.  May be 'revision' or
131
 
            'signature'
132
 
        :revision_id: The revision id of the fulltext being added.
133
 
        """
134
 
        metadata = {'parents': parents,
135
 
                    'storage_kind': 'mpdiff'}
136
 
        self._add_record(bytes, {'parents': parents,
137
 
            'storage_kind': 'fulltext'}, repo_kind, revision_id, None)
138
 
 
139
 
    def add_info_record(self, **kwargs):
140
 
        """Add an info record to the bundle
141
 
 
142
 
        Any parameters may be supplied, except 'self' and 'storage_kind'.
143
 
        Values must be lists, strings, integers, dicts, or a combination.
144
 
        """
145
 
        kwargs['storage_kind'] = 'header'
146
 
        self._add_record(None, kwargs, 'info', None, None)
147
 
 
148
 
    @staticmethod
149
 
    def encode_name(content_kind, revision_id, file_id=None):
150
 
        """Encode semantic ids as a container name"""
151
 
        if content_kind not in ('revision', 'file', 'inventory', 'signature',
152
 
                'info'):
153
 
            raise ValueError(content_kind)
154
 
        if content_kind == 'file':
155
 
            if file_id is None:
156
 
                raise AssertionError()
157
 
        else:
158
 
            if file_id is not None:
159
 
                raise AssertionError()
160
 
        if content_kind == 'info':
161
 
            if revision_id is not None:
162
 
                raise AssertionError()
163
 
        elif revision_id is None:
164
 
            raise AssertionError()
165
 
        names = [n.replace('/', '//') for n in
166
 
                 (content_kind, revision_id, file_id) if n is not None]
167
 
        return '/'.join(names)
168
 
 
169
 
    def _add_record(self, bytes, metadata, repo_kind, revision_id, file_id):
170
 
        """Add a bundle record to the container.
171
 
 
172
 
        Most bundle records are recorded as header/body pairs, with the
173
 
        body being nameless.  Records with storage_kind 'header' have no
174
 
        body.
175
 
        """
176
 
        name = self.encode_name(repo_kind, revision_id, file_id)
177
 
        encoded_metadata = bencode.bencode(metadata)
178
 
        self._container.add_bytes_record(encoded_metadata, [(name, )])
179
 
        if metadata['storage_kind'] != 'header':
180
 
            self._container.add_bytes_record(bytes, [])
181
 
 
182
 
 
183
 
class BundleReader(object):
184
 
    """Reader for bundle-format files.
185
 
 
186
 
    This serves roughly the same purpose as ContainerReader, but acts as a
187
 
    layer on top of it, providing metadata, a semantic name, and a record
188
 
    body
189
 
    """
190
 
 
191
 
    def __init__(self, fileobj, stream_input=True):
192
 
        """Constructor
193
 
 
194
 
        :param fileobj: a file containing a bzip-encoded container
195
 
        :param stream_input: If True, the BundleReader stream input rather than
196
 
            reading it all into memory at once.  Reading it into memory all at
197
 
            once is (currently) faster.
198
 
        """
199
 
        line = fileobj.readline()
200
 
        if line != '\n':
201
 
            fileobj.readline()
202
 
        self.patch_lines = []
203
 
        if stream_input:
204
 
            source_file = iterablefile.IterableFile(self.iter_decode(fileobj))
205
 
        else:
206
 
            source_file = StringIO(bz2.decompress(fileobj.read()))
207
 
        self._container_file = source_file
208
 
 
209
 
    @staticmethod
210
 
    def iter_decode(fileobj):
211
 
        """Iterate through decoded fragments of the file"""
212
 
        decompressor = bz2.BZ2Decompressor()
213
 
        for line in fileobj:
214
 
            try:
215
 
                yield decompressor.decompress(line)
216
 
            except EOFError:
217
 
                return
218
 
 
219
 
    @staticmethod
220
 
    def decode_name(name):
221
 
        """Decode a name from its container form into a semantic form
222
 
 
223
 
        :retval: content_kind, revision_id, file_id
224
 
        """
225
 
        segments = re.split('(//?)', name)
226
 
        names = ['']
227
 
        for segment in segments:
228
 
            if segment == '//':
229
 
                names[-1] += '/'
230
 
            elif segment == '/':
231
 
                names.append('')
232
 
            else:
233
 
                names[-1] += segment
234
 
        content_kind = names[0]
235
 
        revision_id = None
236
 
        file_id = None
237
 
        if len(names) > 1:
238
 
            revision_id = names[1]
239
 
        if len(names) > 2:
240
 
            file_id = names[2]
241
 
        return content_kind, revision_id, file_id
242
 
 
243
 
    def iter_records(self):
244
 
        """Iterate through bundle records
245
 
 
246
 
        :return: a generator of (bytes, metadata, content_kind, revision_id,
247
 
            file_id)
248
 
        """
249
 
        iterator = pack.iter_records_from_file(self._container_file)
250
 
        for names, bytes in iterator:
251
 
            if len(names) != 1:
252
 
                raise errors.BadBundle('Record has %d names instead of 1'
253
 
                                       % len(names))
254
 
            metadata = bencode.bdecode(bytes)
255
 
            if metadata['storage_kind'] == 'header':
256
 
                bytes = None
257
 
            else:
258
 
                _unused, bytes = iterator.next()
259
 
            yield (bytes, metadata) + self.decode_name(names[0][0])
260
 
 
261
 
 
262
 
class BundleSerializerV4(bundle_serializer.BundleSerializer):
263
 
    """Implement the high-level bundle interface"""
264
 
 
265
 
    def write(self, repository, revision_ids, forced_bases, fileobj):
266
 
        """Write a bundle to a file-like object
267
 
 
268
 
        For backwards-compatibility only
269
 
        """
270
 
        write_op = BundleWriteOperation.from_old_args(repository, revision_ids,
271
 
                                                      forced_bases, fileobj)
272
 
        return write_op.do_write()
273
 
 
274
 
    def write_bundle(self, repository, target, base, fileobj):
275
 
        """Write a bundle to a file object
276
 
 
277
 
        :param repository: The repository to retrieve revision data from
278
 
        :param target: The head revision to include ancestors of
279
 
        :param base: The ancestor of the target to stop including acestors
280
 
            at.
281
 
        :param fileobj: The file-like object to write to
282
 
        """
283
 
        write_op =  BundleWriteOperation(base, target, repository, fileobj)
284
 
        return write_op.do_write()
285
 
 
286
 
    def read(self, file):
287
 
        """return a reader object for a given file"""
288
 
        bundle = BundleInfoV4(file, self)
289
 
        return bundle
290
 
 
291
 
    @staticmethod
292
 
    def get_source_serializer(info):
293
 
        """Retrieve the serializer for a given info object"""
294
 
        return serializer.format_registry.get(info['serializer'])
295
 
 
296
 
 
297
 
class BundleWriteOperation(object):
298
 
    """Perform the operation of writing revisions to a bundle"""
299
 
 
300
 
    @classmethod
301
 
    def from_old_args(cls, repository, revision_ids, forced_bases, fileobj):
302
 
        """Create a BundleWriteOperation from old-style arguments"""
303
 
        base, target = cls.get_base_target(revision_ids, forced_bases,
304
 
                                           repository)
305
 
        return BundleWriteOperation(base, target, repository, fileobj,
306
 
                                    revision_ids)
307
 
 
308
 
    def __init__(self, base, target, repository, fileobj, revision_ids=None):
309
 
        self.base = base
310
 
        self.target = target
311
 
        self.repository = repository
312
 
        bundle = BundleWriter(fileobj)
313
 
        self.bundle = bundle
314
 
        if revision_ids is not None:
315
 
            self.revision_ids = revision_ids
316
 
        else:
317
 
            graph = repository.get_graph()
318
 
            revision_ids = graph.find_unique_ancestors(target, [base])
319
 
            # Strip ghosts
320
 
            parents = graph.get_parent_map(revision_ids)
321
 
            self.revision_ids = [r for r in revision_ids if r in parents]
322
 
        self.revision_keys = set([(revid,) for revid in self.revision_ids])
323
 
 
324
 
    def do_write(self):
325
 
        """Write all data to the bundle"""
326
 
        trace.note(ngettext('Bundling %d revision.', 'Bundling %d revisions.',
327
 
                            len(self.revision_ids)), len(self.revision_ids))
328
 
        self.repository.lock_read()
329
 
        try:
330
 
            self.bundle.begin()
331
 
            self.write_info()
332
 
            self.write_files()
333
 
            self.write_revisions()
334
 
            self.bundle.end()
335
 
        finally:
336
 
            self.repository.unlock()
337
 
        return self.revision_ids
338
 
 
339
 
    def write_info(self):
340
 
        """Write format info"""
341
 
        serializer_format = self.repository.get_serializer_format()
342
 
        supports_rich_root = {True: 1, False: 0}[
343
 
            self.repository.supports_rich_root()]
344
 
        self.bundle.add_info_record(serializer=serializer_format,
345
 
                                    supports_rich_root=supports_rich_root)
346
 
 
347
 
    def write_files(self):
348
 
        """Write bundle records for all revisions of all files"""
349
 
        text_keys = []
350
 
        altered_fileids = self.repository.fileids_altered_by_revision_ids(
351
 
                self.revision_ids)
352
 
        for file_id, revision_ids in altered_fileids.iteritems():
353
 
            for revision_id in revision_ids:
354
 
                text_keys.append((file_id, revision_id))
355
 
        self._add_mp_records_keys('file', self.repository.texts, text_keys)
356
 
 
357
 
    def write_revisions(self):
358
 
        """Write bundle records for all revisions and signatures"""
359
 
        inv_vf = self.repository.inventories
360
 
        topological_order = [key[-1] for key in multiparent.topo_iter_keys(
361
 
                                inv_vf, self.revision_keys)]
362
 
        revision_order = topological_order
363
 
        if self.target is not None and self.target in self.revision_ids:
364
 
            # Make sure the target revision is always the last entry
365
 
            revision_order = list(topological_order)
366
 
            revision_order.remove(self.target)
367
 
            revision_order.append(self.target)
368
 
        if self.repository._serializer.support_altered_by_hack:
369
 
            # Repositories that support_altered_by_hack means that
370
 
            # inventories.make_mpdiffs() contains all the data about the tree
371
 
            # shape. Formats without support_altered_by_hack require
372
 
            # chk_bytes/etc, so we use a different code path.
373
 
            self._add_mp_records_keys('inventory', inv_vf,
374
 
                                      [(revid,) for revid in topological_order])
375
 
        else:
376
 
            # Inventories should always be added in pure-topological order, so
377
 
            # that we can apply the mpdiff for the child to the parent texts.
378
 
            self._add_inventory_mpdiffs_from_serializer(topological_order)
379
 
        self._add_revision_texts(revision_order)
380
 
 
381
 
    def _add_inventory_mpdiffs_from_serializer(self, revision_order):
382
 
        """Generate mpdiffs by serializing inventories.
383
 
 
384
 
        The current repository only has part of the tree shape information in
385
 
        the 'inventories' vf. So we use serializer.write_inventory_to_string to
386
 
        get a 'full' representation of the tree shape, and then generate
387
 
        mpdiffs on that data stream. This stream can then be reconstructed on
388
 
        the other side.
389
 
        """
390
 
        inventory_key_order = [(r,) for r in revision_order]
391
 
        generator = _MPDiffInventoryGenerator(self.repository,
392
 
                                              inventory_key_order)
393
 
        for revision_id, parent_ids, sha1, diff in generator.iter_diffs():
394
 
            text = ''.join(diff.to_patch())
395
 
            self.bundle.add_multiparent_record(text, sha1, parent_ids,
396
 
                                               'inventory', revision_id, None)
397
 
 
398
 
    def _add_revision_texts(self, revision_order):
399
 
        parent_map = self.repository.get_parent_map(revision_order)
400
 
        revision_to_str = self.repository._serializer.write_revision_to_string
401
 
        revisions = self.repository.get_revisions(revision_order)
402
 
        for revision in revisions:
403
 
            revision_id = revision.revision_id
404
 
            parents = parent_map.get(revision_id, None)
405
 
            revision_text = revision_to_str(revision)
406
 
            self.bundle.add_fulltext_record(revision_text, parents,
407
 
                                       'revision', revision_id)
408
 
            try:
409
 
                self.bundle.add_fulltext_record(
410
 
                    self.repository.get_signature_text(
411
 
                    revision_id), parents, 'signature', revision_id)
412
 
            except errors.NoSuchRevision:
413
 
                pass
414
 
 
415
 
    @staticmethod
416
 
    def get_base_target(revision_ids, forced_bases, repository):
417
 
        """Determine the base and target from old-style revision ids"""
418
 
        if len(revision_ids) == 0:
419
 
            return None, None
420
 
        target = revision_ids[0]
421
 
        base = forced_bases.get(target)
422
 
        if base is None:
423
 
            parents = repository.get_revision(target).parent_ids
424
 
            if len(parents) == 0:
425
 
                base = _mod_revision.NULL_REVISION
426
 
            else:
427
 
                base = parents[0]
428
 
        return base, target
429
 
 
430
 
    def _add_mp_records_keys(self, repo_kind, vf, keys):
431
 
        """Add multi-parent diff records to a bundle"""
432
 
        ordered_keys = list(multiparent.topo_iter_keys(vf, keys))
433
 
        mpdiffs = vf.make_mpdiffs(ordered_keys)
434
 
        sha1s = vf.get_sha1s(ordered_keys)
435
 
        parent_map = vf.get_parent_map(ordered_keys)
436
 
        for mpdiff, item_key, in zip(mpdiffs, ordered_keys):
437
 
            sha1 = sha1s[item_key]
438
 
            parents = [key[-1] for key in parent_map[item_key]]
439
 
            text = ''.join(mpdiff.to_patch())
440
 
            # Infer file id records as appropriate.
441
 
            if len(item_key) == 2:
442
 
                file_id = item_key[0]
443
 
            else:
444
 
                file_id = None
445
 
            self.bundle.add_multiparent_record(text, sha1, parents, repo_kind,
446
 
                                               item_key[-1], file_id)
447
 
 
448
 
 
449
 
class BundleInfoV4(object):
450
 
 
451
 
    """Provide (most of) the BundleInfo interface"""
452
 
    def __init__(self, fileobj, serializer):
453
 
        self._fileobj = fileobj
454
 
        self._serializer = serializer
455
 
        self.__real_revisions = None
456
 
        self.__revisions = None
457
 
 
458
 
    def install(self, repository):
459
 
        return self.install_revisions(repository)
460
 
 
461
 
    def install_revisions(self, repository, stream_input=True):
462
 
        """Install this bundle's revisions into the specified repository
463
 
 
464
 
        :param target_repo: The repository to install into
465
 
        :param stream_input: If True, will stream input rather than reading it
466
 
            all into memory at once.  Reading it into memory all at once is
467
 
            (currently) faster.
468
 
        """
469
 
        repository.lock_write()
470
 
        try:
471
 
            ri = RevisionInstaller(self.get_bundle_reader(stream_input),
472
 
                                   self._serializer, repository)
473
 
            return ri.install()
474
 
        finally:
475
 
            repository.unlock()
476
 
 
477
 
    def get_merge_request(self, target_repo):
478
 
        """Provide data for performing a merge
479
 
 
480
 
        Returns suggested base, suggested target, and patch verification status
481
 
        """
482
 
        return None, self.target, 'inapplicable'
483
 
 
484
 
    def get_bundle_reader(self, stream_input=True):
485
 
        """Return a new BundleReader for the associated bundle
486
 
 
487
 
        :param stream_input: If True, the BundleReader stream input rather than
488
 
            reading it all into memory at once.  Reading it into memory all at
489
 
            once is (currently) faster.
490
 
        """
491
 
        self._fileobj.seek(0)
492
 
        return BundleReader(self._fileobj, stream_input)
493
 
 
494
 
    def _get_real_revisions(self):
495
 
        if self.__real_revisions is None:
496
 
            self.__real_revisions = []
497
 
            bundle_reader = self.get_bundle_reader()
498
 
            for bytes, metadata, repo_kind, revision_id, file_id in \
499
 
                bundle_reader.iter_records():
500
 
                if repo_kind == 'info':
501
 
                    serializer =\
502
 
                        self._serializer.get_source_serializer(metadata)
503
 
                if repo_kind == 'revision':
504
 
                    rev = serializer.read_revision_from_string(bytes)
505
 
                    self.__real_revisions.append(rev)
506
 
        return self.__real_revisions
507
 
    real_revisions = property(_get_real_revisions)
508
 
 
509
 
    def _get_revisions(self):
510
 
        if self.__revisions is None:
511
 
            self.__revisions = []
512
 
            for revision in self.real_revisions:
513
 
                self.__revisions.append(
514
 
                    bundle_data.RevisionInfo.from_revision(revision))
515
 
        return self.__revisions
516
 
 
517
 
    revisions = property(_get_revisions)
518
 
 
519
 
    def _get_target(self):
520
 
        return self.revisions[-1].revision_id
521
 
 
522
 
    target = property(_get_target)
523
 
 
524
 
 
525
 
class RevisionInstaller(object):
526
 
    """Installs revisions into a repository"""
527
 
 
528
 
    def __init__(self, container, serializer, repository):
529
 
        self._container = container
530
 
        self._serializer = serializer
531
 
        self._repository = repository
532
 
        self._info = None
533
 
 
534
 
    def install(self):
535
 
        """Perform the installation.
536
 
 
537
 
        Must be called with the Repository locked.
538
 
        """
539
 
        self._repository.start_write_group()
540
 
        try:
541
 
            result = self._install_in_write_group()
542
 
        except:
543
 
            self._repository.abort_write_group()
544
 
            raise
545
 
        self._repository.commit_write_group()
546
 
        return result
547
 
 
548
 
    def _install_in_write_group(self):
549
 
        current_file = None
550
 
        current_versionedfile = None
551
 
        pending_file_records = []
552
 
        inventory_vf = None
553
 
        pending_inventory_records = []
554
 
        added_inv = set()
555
 
        target_revision = None
556
 
        for bytes, metadata, repo_kind, revision_id, file_id in\
557
 
            self._container.iter_records():
558
 
            if repo_kind == 'info':
559
 
                if self._info is not None:
560
 
                    raise AssertionError()
561
 
                self._handle_info(metadata)
562
 
            if (pending_file_records and
563
 
                (repo_kind, file_id) != ('file', current_file)):
564
 
                # Flush the data for a single file - prevents memory
565
 
                # spiking due to buffering all files in memory.
566
 
                self._install_mp_records_keys(self._repository.texts,
567
 
                    pending_file_records)
568
 
                current_file = None
569
 
                del pending_file_records[:]
570
 
            if len(pending_inventory_records) > 0 and repo_kind != 'inventory':
571
 
                self._install_inventory_records(pending_inventory_records)
572
 
                pending_inventory_records = []
573
 
            if repo_kind == 'inventory':
574
 
                pending_inventory_records.append(((revision_id,), metadata, bytes))
575
 
            if repo_kind == 'revision':
576
 
                target_revision = revision_id
577
 
                self._install_revision(revision_id, metadata, bytes)
578
 
            if repo_kind == 'signature':
579
 
                self._install_signature(revision_id, metadata, bytes)
580
 
            if repo_kind == 'file':
581
 
                current_file = file_id
582
 
                pending_file_records.append(((file_id, revision_id), metadata, bytes))
583
 
        self._install_mp_records_keys(self._repository.texts, pending_file_records)
584
 
        return target_revision
585
 
 
586
 
    def _handle_info(self, info):
587
 
        """Extract data from an info record"""
588
 
        self._info = info
589
 
        self._source_serializer = self._serializer.get_source_serializer(info)
590
 
        if (info['supports_rich_root'] == 0 and
591
 
            self._repository.supports_rich_root()):
592
 
            self.update_root = True
593
 
        else:
594
 
            self.update_root = False
595
 
 
596
 
    def _install_mp_records(self, versionedfile, records):
597
 
        if len(records) == 0:
598
 
            return
599
 
        d_func = multiparent.MultiParent.from_patch
600
 
        vf_records = [(r, m['parents'], m['sha1'], d_func(t)) for r, m, t in
601
 
                      records if r not in versionedfile]
602
 
        versionedfile.add_mpdiffs(vf_records)
603
 
 
604
 
    def _install_mp_records_keys(self, versionedfile, records):
605
 
        d_func = multiparent.MultiParent.from_patch
606
 
        vf_records = []
607
 
        for key, meta, text in records:
608
 
            # Adapt to tuple interface: A length two key is a file_id,
609
 
            # revision_id pair, a length 1 key is a
610
 
            # revision/signature/inventory. We need to do this because
611
 
            # the metadata extraction from the bundle has not yet been updated
612
 
            # to use the consistent tuple interface itself.
613
 
            if len(key) == 2:
614
 
                prefix = key[:1]
615
 
            else:
616
 
                prefix = ()
617
 
            parents = [prefix + (parent,) for parent in meta['parents']]
618
 
            vf_records.append((key, parents, meta['sha1'], d_func(text)))
619
 
        versionedfile.add_mpdiffs(vf_records)
620
 
 
621
 
    def _get_parent_inventory_texts(self, inventory_text_cache,
622
 
                                    inventory_cache, parent_ids):
623
 
        cached_parent_texts = {}
624
 
        remaining_parent_ids = []
625
 
        for parent_id in parent_ids:
626
 
            p_text = inventory_text_cache.get(parent_id, None)
627
 
            if p_text is None:
628
 
                remaining_parent_ids.append(parent_id)
629
 
            else:
630
 
                cached_parent_texts[parent_id] = p_text
631
 
        ghosts = ()
632
 
        # TODO: Use inventory_cache to grab inventories we already have in
633
 
        #       memory
634
 
        if remaining_parent_ids:
635
 
            # first determine what keys are actually present in the local
636
 
            # inventories object (don't use revisions as they haven't been
637
 
            # installed yet.)
638
 
            parent_keys = [(r,) for r in remaining_parent_ids]
639
 
            present_parent_map = self._repository.inventories.get_parent_map(
640
 
                                        parent_keys)
641
 
            present_parent_ids = []
642
 
            ghosts = set()
643
 
            for p_id in remaining_parent_ids:
644
 
                if (p_id,) in present_parent_map:
645
 
                    present_parent_ids.append(p_id)
646
 
                else:
647
 
                    ghosts.add(p_id)
648
 
            to_string = self._source_serializer.write_inventory_to_string
649
 
            for parent_inv in self._repository.iter_inventories(
650
 
                                    present_parent_ids):
651
 
                p_text = to_string(parent_inv)
652
 
                inventory_cache[parent_inv.revision_id] = parent_inv
653
 
                cached_parent_texts[parent_inv.revision_id] = p_text
654
 
                inventory_text_cache[parent_inv.revision_id] = p_text
655
 
 
656
 
        parent_texts = [cached_parent_texts[parent_id]
657
 
                        for parent_id in parent_ids
658
 
                         if parent_id not in ghosts]
659
 
        return parent_texts
660
 
 
661
 
    def _install_inventory_records(self, records):
662
 
        if (self._info['serializer'] == self._repository._serializer.format_num
663
 
            and self._repository._serializer.support_altered_by_hack):
664
 
            return self._install_mp_records_keys(self._repository.inventories,
665
 
                records)
666
 
        # Use a 10MB text cache, since these are string xml inventories. Note
667
 
        # that 10MB is fairly small for large projects (a single inventory can
668
 
        # be >5MB). Another possibility is to cache 10-20 inventory texts
669
 
        # instead
670
 
        inventory_text_cache = lru_cache.LRUSizeCache(10*1024*1024)
671
 
        # Also cache the in-memory representation. This allows us to create
672
 
        # inventory deltas to apply rather than calling add_inventory from
673
 
        # scratch each time.
674
 
        inventory_cache = lru_cache.LRUCache(10)
675
 
        pb = ui.ui_factory.nested_progress_bar()
676
 
        try:
677
 
            num_records = len(records)
678
 
            for idx, (key, metadata, bytes) in enumerate(records):
679
 
                pb.update('installing inventory', idx, num_records)
680
 
                revision_id = key[-1]
681
 
                parent_ids = metadata['parents']
682
 
                # Note: This assumes the local ghosts are identical to the
683
 
                #       ghosts in the source, as the Bundle serialization
684
 
                #       format doesn't record ghosts.
685
 
                p_texts = self._get_parent_inventory_texts(inventory_text_cache,
686
 
                                                           inventory_cache,
687
 
                                                           parent_ids)
688
 
                # Why does to_lines() take strings as the source, it seems that
689
 
                # it would have to cast to a list of lines, which we get back
690
 
                # as lines and then cast back to a string.
691
 
                target_lines = multiparent.MultiParent.from_patch(bytes
692
 
                            ).to_lines(p_texts)
693
 
                inv_text = ''.join(target_lines)
694
 
                del target_lines
695
 
                sha1 = osutils.sha_string(inv_text)
696
 
                if sha1 != metadata['sha1']:
697
 
                    raise errors.BadBundle("Can't convert to target format")
698
 
                # Add this to the cache so we don't have to extract it again.
699
 
                inventory_text_cache[revision_id] = inv_text
700
 
                target_inv = self._source_serializer.read_inventory_from_string(
701
 
                    inv_text)
702
 
                self._handle_root(target_inv, parent_ids)
703
 
                parent_inv = None
704
 
                if parent_ids:
705
 
                    parent_inv = inventory_cache.get(parent_ids[0], None)
706
 
                try:
707
 
                    if parent_inv is None:
708
 
                        self._repository.add_inventory(revision_id, target_inv,
709
 
                                                       parent_ids)
710
 
                    else:
711
 
                        delta = target_inv._make_delta(parent_inv)
712
 
                        self._repository.add_inventory_by_delta(parent_ids[0],
713
 
                            delta, revision_id, parent_ids)
714
 
                except errors.UnsupportedInventoryKind:
715
 
                    raise errors.IncompatibleRevision(repr(self._repository))
716
 
                inventory_cache[revision_id] = target_inv
717
 
        finally:
718
 
            pb.finished()
719
 
 
720
 
    def _handle_root(self, target_inv, parent_ids):
721
 
        revision_id = target_inv.revision_id
722
 
        if self.update_root:
723
 
            text_key = (target_inv.root.file_id, revision_id)
724
 
            parent_keys = [(target_inv.root.file_id, parent) for
725
 
                parent in parent_ids]
726
 
            self._repository.texts.add_lines(text_key, parent_keys, [])
727
 
        elif not self._repository.supports_rich_root():
728
 
            if target_inv.root.revision != revision_id:
729
 
                raise errors.IncompatibleRevision(repr(self._repository))
730
 
 
731
 
    def _install_revision(self, revision_id, metadata, text):
732
 
        if self._repository.has_revision(revision_id):
733
 
            return
734
 
        revision = self._source_serializer.read_revision_from_string(text)
735
 
        self._repository.add_revision(revision.revision_id, revision)
736
 
 
737
 
    def _install_signature(self, revision_id, metadata, text):
738
 
        transaction = self._repository.get_transaction()
739
 
        if self._repository.has_signature_for_revision_id(revision_id):
740
 
            return
741
 
        self._repository.add_signature_text(revision_id, text)