/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 breezy/bundle/serializer/v4.py

  • Committer: Jelmer Vernooij
  • Date: 2017-07-21 13:20:17 UTC
  • mfrom: (6733.1.1 move-errors-config)
  • Revision ID: jelmer@jelmer.uk-20170721132017-oratmmxasovq4r1q
Merge lp:~jelmer/brz/move-errors-config.

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