~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

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

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2011-08-17 18:13:57 UTC
  • mfrom: (5268.7.29 transport-segments)
  • Revision ID: pqm@pqm.ubuntu.com-20110817181357-y5q5eth1hk8bl3om
(jelmer) Allow specifying the colocated branch to use in the branch URL,
 and retrieving the branch name using ControlDir._get_selected_branch.
 (Jelmer Vernooij)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2007 Canonical Ltd
 
1
# Copyright (C) 2007-2010 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
from cStringIO import StringIO
18
18
import bz2
22
22
    diff,
23
23
    errors,
24
24
    iterablefile,
 
25
    lru_cache,
25
26
    multiparent,
26
27
    osutils,
27
28
    pack,
28
29
    revision as _mod_revision,
 
30
    serializer,
29
31
    trace,
30
 
    xml_serializer,
 
32
    ui,
 
33
    versionedfile as _mod_versionedfile,
31
34
    )
32
 
from bzrlib.bundle import bundle_data, serializer
33
 
from bzrlib.util import bencode
 
35
from bzrlib.bundle import bundle_data, serializer as bundle_serializer
 
36
from bzrlib import bencode
 
37
 
 
38
 
 
39
class _MPDiffInventoryGenerator(_mod_versionedfile._MPDiffGenerator):
 
40
    """Generate Inventory diffs serialized inventories."""
 
41
 
 
42
    def __init__(self, repo, inventory_keys):
 
43
        super(_MPDiffInventoryGenerator, self).__init__(repo.inventories,
 
44
            inventory_keys)
 
45
        self.repo = repo
 
46
        self.sha1s = {}
 
47
 
 
48
    def iter_diffs(self):
 
49
        """Compute the diffs one at a time."""
 
50
        # This is instead of compute_diffs() since we guarantee our ordering of
 
51
        # inventories, we don't have to do any buffering
 
52
        self._find_needed_keys()
 
53
        # We actually use a slightly different ordering. We grab all of the
 
54
        # parents first, and then grab the ordered requests.
 
55
        needed_ids = [k[-1] for k in self.present_parents]
 
56
        needed_ids.extend([k[-1] for k in self.ordered_keys])
 
57
        inv_to_str = self.repo._serializer.write_inventory_to_string
 
58
        for inv in self.repo.iter_inventories(needed_ids):
 
59
            revision_id = inv.revision_id
 
60
            key = (revision_id,)
 
61
            if key in self.present_parents:
 
62
                # Not a key we will transmit, which is a shame, since because
 
63
                # of that bundles don't work with stacked branches
 
64
                parent_ids = None
 
65
            else:
 
66
                parent_ids = [k[-1] for k in self.parent_map[key]]
 
67
            as_bytes = inv_to_str(inv)
 
68
            self._process_one_record(key, (as_bytes,))
 
69
            if parent_ids is None:
 
70
                continue
 
71
            diff = self.diffs.pop(key)
 
72
            sha1 = osutils.sha_string(as_bytes)
 
73
            yield revision_id, parent_ids, sha1, diff
34
74
 
35
75
 
36
76
class BundleWriter(object):
54
94
 
55
95
    def begin(self):
56
96
        """Start writing the bundle"""
57
 
        self._fileobj.write(serializer._get_bundle_header(
58
 
            serializer.v4_string))
 
97
        self._fileobj.write(bundle_serializer._get_bundle_header(
 
98
            bundle_serializer.v4_string))
59
99
        self._fileobj.write('#\n')
60
100
        self._container.begin()
61
101
 
218
258
            yield (bytes, metadata) + self.decode_name(names[0][0])
219
259
 
220
260
 
221
 
class BundleSerializerV4(serializer.BundleSerializer):
 
261
class BundleSerializerV4(bundle_serializer.BundleSerializer):
222
262
    """Implement the high-level bundle interface"""
223
263
 
224
264
    def write(self, repository, revision_ids, forced_bases, fileobj):
250
290
    @staticmethod
251
291
    def get_source_serializer(info):
252
292
        """Retrieve the serializer for a given info object"""
253
 
        return xml_serializer.format_registry.get(info['serializer'])
 
293
        return serializer.format_registry.get(info['serializer'])
254
294
 
255
295
 
256
296
class BundleWriteOperation(object):
270
310
        self.repository = repository
271
311
        bundle = BundleWriter(fileobj)
272
312
        self.bundle = bundle
273
 
        self.base_ancestry = set(repository.get_ancestry(base,
274
 
                                                         topo_sorted=False))
275
313
        if revision_ids is not None:
276
314
            self.revision_ids = revision_ids
277
315
        else:
278
 
            revision_ids = set(repository.get_ancestry(target,
279
 
                                                       topo_sorted=False))
280
 
            self.revision_ids = revision_ids.difference(self.base_ancestry)
 
316
            graph = repository.get_graph()
 
317
            revision_ids = graph.find_unique_ancestors(target, [base])
 
318
            # Strip ghosts
 
319
            parents = graph.get_parent_map(revision_ids)
 
320
            self.revision_ids = [r for r in revision_ids if r in parents]
281
321
        self.revision_keys = set([(revid,) for revid in self.revision_ids])
282
322
 
283
323
    def do_write(self):
284
324
        """Write all data to the bundle"""
 
325
        trace.note('Bundling %d revision(s).', len(self.revision_ids))
285
326
        self.repository.lock_read()
286
327
        try:
287
328
            self.bundle.begin()
314
355
    def write_revisions(self):
315
356
        """Write bundle records for all revisions and signatures"""
316
357
        inv_vf = self.repository.inventories
317
 
        revision_order = [key[-1] for key in multiparent.topo_iter_keys(inv_vf,
318
 
            self.revision_keys)]
 
358
        topological_order = [key[-1] for key in multiparent.topo_iter_keys(
 
359
                                inv_vf, self.revision_keys)]
 
360
        revision_order = topological_order
319
361
        if self.target is not None and self.target in self.revision_ids:
 
362
            # Make sure the target revision is always the last entry
 
363
            revision_order = list(topological_order)
320
364
            revision_order.remove(self.target)
321
365
            revision_order.append(self.target)
322
 
        self._add_mp_records_keys('inventory', inv_vf, [(revid,) for revid in revision_order])
 
366
        if self.repository._serializer.support_altered_by_hack:
 
367
            # Repositories that support_altered_by_hack means that
 
368
            # inventories.make_mpdiffs() contains all the data about the tree
 
369
            # shape. Formats without support_altered_by_hack require
 
370
            # chk_bytes/etc, so we use a different code path.
 
371
            self._add_mp_records_keys('inventory', inv_vf,
 
372
                                      [(revid,) for revid in topological_order])
 
373
        else:
 
374
            # Inventories should always be added in pure-topological order, so
 
375
            # that we can apply the mpdiff for the child to the parent texts.
 
376
            self._add_inventory_mpdiffs_from_serializer(topological_order)
 
377
        self._add_revision_texts(revision_order)
 
378
 
 
379
    def _add_inventory_mpdiffs_from_serializer(self, revision_order):
 
380
        """Generate mpdiffs by serializing inventories.
 
381
 
 
382
        The current repository only has part of the tree shape information in
 
383
        the 'inventories' vf. So we use serializer.write_inventory_to_string to
 
384
        get a 'full' representation of the tree shape, and then generate
 
385
        mpdiffs on that data stream. This stream can then be reconstructed on
 
386
        the other side.
 
387
        """
 
388
        inventory_key_order = [(r,) for r in revision_order]
 
389
        generator = _MPDiffInventoryGenerator(self.repository,
 
390
                                              inventory_key_order)
 
391
        for revision_id, parent_ids, sha1, diff in generator.iter_diffs():
 
392
            text = ''.join(diff.to_patch())
 
393
            self.bundle.add_multiparent_record(text, sha1, parent_ids,
 
394
                                               'inventory', revision_id, None)
 
395
 
 
396
    def _add_revision_texts(self, revision_order):
323
397
        parent_map = self.repository.get_parent_map(revision_order)
324
 
        for revision_id in revision_order:
 
398
        revision_to_str = self.repository._serializer.write_revision_to_string
 
399
        revisions = self.repository.get_revisions(revision_order)
 
400
        for revision in revisions:
 
401
            revision_id = revision.revision_id
325
402
            parents = parent_map.get(revision_id, None)
326
 
            revision_text = self.repository.get_revision_xml(revision_id)
 
403
            revision_text = revision_to_str(revision)
327
404
            self.bundle.add_fulltext_record(revision_text, parents,
328
405
                                       'revision', revision_id)
329
406
            try:
454
531
 
455
532
    def install(self):
456
533
        """Perform the installation.
457
 
        
 
534
 
458
535
        Must be called with the Repository locked.
459
536
        """
460
537
        self._repository.start_write_group()
539
616
            vf_records.append((key, parents, meta['sha1'], d_func(text)))
540
617
        versionedfile.add_mpdiffs(vf_records)
541
618
 
 
619
    def _get_parent_inventory_texts(self, inventory_text_cache,
 
620
                                    inventory_cache, parent_ids):
 
621
        cached_parent_texts = {}
 
622
        remaining_parent_ids = []
 
623
        for parent_id in parent_ids:
 
624
            p_text = inventory_text_cache.get(parent_id, None)
 
625
            if p_text is None:
 
626
                remaining_parent_ids.append(parent_id)
 
627
            else:
 
628
                cached_parent_texts[parent_id] = p_text
 
629
        ghosts = ()
 
630
        # TODO: Use inventory_cache to grab inventories we already have in
 
631
        #       memory
 
632
        if remaining_parent_ids:
 
633
            # first determine what keys are actually present in the local
 
634
            # inventories object (don't use revisions as they haven't been
 
635
            # installed yet.)
 
636
            parent_keys = [(r,) for r in remaining_parent_ids]
 
637
            present_parent_map = self._repository.inventories.get_parent_map(
 
638
                                        parent_keys)
 
639
            present_parent_ids = []
 
640
            ghosts = set()
 
641
            for p_id in remaining_parent_ids:
 
642
                if (p_id,) in present_parent_map:
 
643
                    present_parent_ids.append(p_id)
 
644
                else:
 
645
                    ghosts.add(p_id)
 
646
            to_string = self._source_serializer.write_inventory_to_string
 
647
            for parent_inv in self._repository.iter_inventories(
 
648
                                    present_parent_ids):
 
649
                p_text = to_string(parent_inv)
 
650
                inventory_cache[parent_inv.revision_id] = parent_inv
 
651
                cached_parent_texts[parent_inv.revision_id] = p_text
 
652
                inventory_text_cache[parent_inv.revision_id] = p_text
 
653
 
 
654
        parent_texts = [cached_parent_texts[parent_id]
 
655
                        for parent_id in parent_ids
 
656
                         if parent_id not in ghosts]
 
657
        return parent_texts
 
658
 
542
659
    def _install_inventory_records(self, records):
543
 
        if self._info['serializer'] == self._repository._serializer.format_num:
 
660
        if (self._info['serializer'] == self._repository._serializer.format_num
 
661
            and self._repository._serializer.support_altered_by_hack):
544
662
            return self._install_mp_records_keys(self._repository.inventories,
545
663
                records)
546
 
        for key, metadata, bytes in records:
547
 
            revision_id = key[-1]
548
 
            parent_ids = metadata['parents']
549
 
            parents = [self._repository.get_inventory(p)
550
 
                       for p in parent_ids]
551
 
            p_texts = [self._source_serializer.write_inventory_to_string(p)
552
 
                       for p in parents]
553
 
            target_lines = multiparent.MultiParent.from_patch(bytes).to_lines(
554
 
                p_texts)
555
 
            sha1 = osutils.sha_strings(target_lines)
556
 
            if sha1 != metadata['sha1']:
557
 
                raise errors.BadBundle("Can't convert to target format")
558
 
            target_inv = self._source_serializer.read_inventory_from_string(
559
 
                ''.join(target_lines))
560
 
            self._handle_root(target_inv, parent_ids)
561
 
            try:
562
 
                self._repository.add_inventory(revision_id, target_inv,
563
 
                                               parent_ids)
564
 
            except errors.UnsupportedInventoryKind:
565
 
                raise errors.IncompatibleRevision(repr(self._repository))
 
664
        # Use a 10MB text cache, since these are string xml inventories. Note
 
665
        # that 10MB is fairly small for large projects (a single inventory can
 
666
        # be >5MB). Another possibility is to cache 10-20 inventory texts
 
667
        # instead
 
668
        inventory_text_cache = lru_cache.LRUSizeCache(10*1024*1024)
 
669
        # Also cache the in-memory representation. This allows us to create
 
670
        # inventory deltas to apply rather than calling add_inventory from
 
671
        # scratch each time.
 
672
        inventory_cache = lru_cache.LRUCache(10)
 
673
        pb = ui.ui_factory.nested_progress_bar()
 
674
        try:
 
675
            num_records = len(records)
 
676
            for idx, (key, metadata, bytes) in enumerate(records):
 
677
                pb.update('installing inventory', idx, num_records)
 
678
                revision_id = key[-1]
 
679
                parent_ids = metadata['parents']
 
680
                # Note: This assumes the local ghosts are identical to the
 
681
                #       ghosts in the source, as the Bundle serialization
 
682
                #       format doesn't record ghosts.
 
683
                p_texts = self._get_parent_inventory_texts(inventory_text_cache,
 
684
                                                           inventory_cache,
 
685
                                                           parent_ids)
 
686
                # Why does to_lines() take strings as the source, it seems that
 
687
                # it would have to cast to a list of lines, which we get back
 
688
                # as lines and then cast back to a string.
 
689
                target_lines = multiparent.MultiParent.from_patch(bytes
 
690
                            ).to_lines(p_texts)
 
691
                inv_text = ''.join(target_lines)
 
692
                del target_lines
 
693
                sha1 = osutils.sha_string(inv_text)
 
694
                if sha1 != metadata['sha1']:
 
695
                    raise errors.BadBundle("Can't convert to target format")
 
696
                # Add this to the cache so we don't have to extract it again.
 
697
                inventory_text_cache[revision_id] = inv_text
 
698
                target_inv = self._source_serializer.read_inventory_from_string(
 
699
                    inv_text)
 
700
                self._handle_root(target_inv, parent_ids)
 
701
                parent_inv = None
 
702
                if parent_ids:
 
703
                    parent_inv = inventory_cache.get(parent_ids[0], None)
 
704
                try:
 
705
                    if parent_inv is None:
 
706
                        self._repository.add_inventory(revision_id, target_inv,
 
707
                                                       parent_ids)
 
708
                    else:
 
709
                        delta = target_inv._make_delta(parent_inv)
 
710
                        self._repository.add_inventory_by_delta(parent_ids[0],
 
711
                            delta, revision_id, parent_ids)
 
712
                except errors.UnsupportedInventoryKind:
 
713
                    raise errors.IncompatibleRevision(repr(self._repository))
 
714
                inventory_cache[revision_id] = target_inv
 
715
        finally:
 
716
            pb.finished()
566
717
 
567
718
    def _handle_root(self, target_inv, parent_ids):
568
719
        revision_id = target_inv.revision_id