/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/bzr/groupcompress_repo.py

  • Committer: Martin
  • Date: 2017-11-19 20:33:06 UTC
  • mto: This revision was merged to the branch mainline in revision 6821.
  • Revision ID: gzlist@googlemail.com-20171119203306-lm94zmwsggx4dt3z
Create a cross compatible lsprof main()

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2008, 2009, 2010 Canonical Ltd
 
1
# Copyright (C) 2008-2011 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
16
16
 
17
17
"""Repository formats using CHK inventories and groupcompress compression."""
18
18
 
 
19
from __future__ import absolute_import
 
20
 
19
21
import time
20
22
 
21
 
from bzrlib import (
22
 
    bzrdir,
23
 
    chk_map,
24
 
    chk_serializer,
 
23
from .. import (
 
24
    controldir,
25
25
    debug,
26
26
    errors,
27
 
    index as _mod_index,
28
 
    inventory,
29
 
    knit,
30
27
    osutils,
31
 
    pack,
32
28
    revision as _mod_revision,
33
29
    trace,
34
30
    ui,
35
31
    )
36
 
from bzrlib.btree_index import (
 
32
from ..bzr import (
 
33
    chk_map,
 
34
    chk_serializer,
 
35
    index as _mod_index,
 
36
    inventory,
 
37
    pack,
 
38
    versionedfile,
 
39
    )
 
40
from ..bzr.btree_index import (
37
41
    BTreeGraphIndex,
38
42
    BTreeBuilder,
39
43
    )
40
 
from bzrlib.groupcompress import (
 
44
from ..bzr.groupcompress import (
41
45
    _GCGraphIndex,
42
46
    GroupCompressVersionedFiles,
43
47
    )
44
 
from bzrlib.repofmt.pack_repo import (
 
48
from .pack_repo import (
 
49
    _DirectPackAccess,
45
50
    Pack,
46
51
    NewPack,
47
 
    KnitPackRepository,
48
 
    KnitPackStreamSource,
 
52
    PackRepository,
49
53
    PackRootCommitBuilder,
50
54
    RepositoryPackCollection,
51
55
    RepositoryFormatPack,
52
56
    ResumedPack,
53
57
    Packer,
54
58
    )
55
 
from bzrlib.static_tuple import StaticTuple
 
59
from ..bzr.vf_repository import (
 
60
    StreamSource,
 
61
    )
 
62
from ..sixish import (
 
63
    viewitems,
 
64
    viewvalues,
 
65
    )
 
66
from ..static_tuple import StaticTuple
56
67
 
57
68
 
58
69
class GCPack(NewPack):
137
148
        # robertc says- this is a closure rather than a method on the object
138
149
        # so that the variables are locals, and faster than accessing object
139
150
        # members.
140
 
        def _write_data(bytes, flush=False, _buffer=self._buffer,
 
151
        def _write_data(data, flush=False, _buffer=self._buffer,
141
152
            _write=self.write_stream.write, _update=self._hash.update):
142
 
            _buffer[0].append(bytes)
143
 
            _buffer[1] += len(bytes)
 
153
            _buffer[0].append(data)
 
154
            _buffer[1] += len(data)
144
155
            # buffer cap
145
156
            if _buffer[1] > self._cache_limit or flush:
146
 
                bytes = ''.join(_buffer[0])
147
 
                _write(bytes)
148
 
                _update(bytes)
 
157
                data = b''.join(_buffer[0])
 
158
                _write(data)
 
159
                _update(data)
149
160
                _buffer[:] = [[], 0]
150
161
        # expose this on self, for the occasion when clients want to add data.
151
162
        self._write_data = _write_data
262
273
        remaining_keys = set(keys)
263
274
        counter = [0]
264
275
        if self._gather_text_refs:
265
 
            bytes_to_info = inventory.CHKInventory._bytes_to_utf8name_key
266
276
            self._text_refs = set()
267
277
        def _get_referenced_stream(root_keys, parse_leaf_nodes=False):
268
278
            cur_keys = root_keys
271
281
                remaining_keys.difference_update(cur_keys)
272
282
                next_keys = set()
273
283
                def handle_internal_node(node):
274
 
                    for prefix, value in node._items.iteritems():
 
284
                    for prefix, value in viewitems(node._items):
275
285
                        # We don't want to request the same key twice, and we
276
286
                        # want to order it by the first time it is seen.
277
287
                        # Even further, we don't want to request a key which is
289
299
                    # Store is None, because we know we have a LeafNode, and we
290
300
                    # just want its entries
291
301
                    for file_id, bytes in node.iteritems(None):
292
 
                        name_utf8, file_id, revision_id = bytes_to_info(bytes)
293
 
                        self._text_refs.add((file_id, revision_id))
 
302
                        self._text_refs.add(chk_map._bytes_to_text_key(bytes))
294
303
                def next_stream():
295
304
                    stream = source_vf.get_record_stream(cur_keys,
296
305
                                                         'as-requested', True)
352
361
        """Build a VersionedFiles instance on top of this group of packs."""
353
362
        index_name = index_name + '_index'
354
363
        index_to_pack = {}
355
 
        access = knit._DirectPackAccess(index_to_pack,
356
 
                                        reload_func=self._reload_func)
 
364
        access = _DirectPackAccess(index_to_pack,
 
365
                                   reload_func=self._reload_func)
357
366
        if for_write:
358
367
            # Use new_pack
359
368
            if self.new_pack is None:
421
430
        inventory_keys = source_vf.keys()
422
431
        missing_inventories = set(self.revision_keys).difference(inventory_keys)
423
432
        if missing_inventories:
424
 
            missing_inventories = sorted(missing_inventories)
425
 
            raise ValueError('We are missing inventories for revisions: %s'
426
 
                % (missing_inventories,))
 
433
            # Go back to the original repo, to see if these are really missing
 
434
            # https://bugs.launchpad.net/bzr/+bug/437003
 
435
            # If we are packing a subset of the repo, it is fine to just have
 
436
            # the data in another Pack file, which is not included in this pack
 
437
            # operation.
 
438
            inv_index = self._pack_collection.repo.inventories._index
 
439
            pmap = inv_index.get_parent_map(missing_inventories)
 
440
            really_missing = missing_inventories.difference(pmap)
 
441
            if really_missing:
 
442
                missing_inventories = sorted(really_missing)
 
443
                raise ValueError('We are missing inventories for revisions: %s'
 
444
                    % (missing_inventories,))
427
445
        self._copy_stream(source_vf, target_vf, inventory_keys,
428
446
                          'inventories', self._get_filtered_inv_stream, 2)
429
447
 
 
448
    def _get_chk_vfs_for_copy(self):
 
449
        return self._build_vfs('chk', False, False)
 
450
 
430
451
    def _copy_chk_texts(self):
431
 
        source_vf, target_vf = self._build_vfs('chk', False, False)
 
452
        source_vf, target_vf = self._get_chk_vfs_for_copy()
432
453
        # TODO: This is technically spurious... if it is a performance issue,
433
454
        #       remove it
434
455
        total_keys = source_vf.keys()
498
519
class GCCHKReconcilePacker(GCCHKPacker):
499
520
    """A packer which regenerates indices etc as it copies.
500
521
 
501
 
    This is used by ``bzr reconcile`` to cause parent text pointers to be
 
522
    This is used by ``brz reconcile`` to cause parent text pointers to be
502
523
    regenerated.
503
524
    """
504
525
 
527
548
        ancestor_keys = revision_vf.get_parent_map(revision_vf.keys())
528
549
        # Strip keys back into revision_ids.
529
550
        ancestors = dict((k[0], tuple([p[0] for p in parents]))
530
 
                         for k, parents in ancestor_keys.iteritems())
 
551
                         for k, parents in viewitems(ancestor_keys))
531
552
        del ancestor_keys
532
553
        # TODO: _generate_text_key_index should be much cheaper to generate from
533
554
        #       a chk repository, rather than the current implementation
580
601
        return new_pack.data_inserted() and self._data_changed
581
602
 
582
603
 
 
604
class GCCHKCanonicalizingPacker(GCCHKPacker):
 
605
    """A packer that ensures inventories have canonical-form CHK maps.
 
606
    
 
607
    Ideally this would be part of reconcile, but it's very slow and rarely
 
608
    needed.  (It repairs repositories affected by
 
609
    https://bugs.launchpad.net/bzr/+bug/522637).
 
610
    """
 
611
 
 
612
    def __init__(self, *args, **kwargs):
 
613
        super(GCCHKCanonicalizingPacker, self).__init__(*args, **kwargs)
 
614
        self._data_changed = False
 
615
 
 
616
    def _exhaust_stream(self, source_vf, keys, message, vf_to_stream, pb_offset):
 
617
        """Create and exhaust a stream, but don't insert it.
 
618
 
 
619
        This is useful to get the side-effects of generating a stream.
 
620
        """
 
621
        self.pb.update('scanning %s' % (message,), pb_offset)
 
622
        child_pb = ui.ui_factory.nested_progress_bar()
 
623
        try:
 
624
            list(vf_to_stream(source_vf, keys, message, child_pb))
 
625
        finally:
 
626
            child_pb.finished()
 
627
 
 
628
    def _copy_inventory_texts(self):
 
629
        source_vf, target_vf = self._build_vfs('inventory', True, True)
 
630
        source_chk_vf, target_chk_vf = self._get_chk_vfs_for_copy()
 
631
        inventory_keys = source_vf.keys()
 
632
        # First, copy the existing CHKs on the assumption that most of them
 
633
        # will be correct.  This will save us from having to reinsert (and
 
634
        # recompress) these records later at the cost of perhaps preserving a
 
635
        # few unused CHKs. 
 
636
        # (Iterate but don't insert _get_filtered_inv_stream to populate the
 
637
        # variables needed by GCCHKPacker._copy_chk_texts.)
 
638
        self._exhaust_stream(source_vf, inventory_keys, 'inventories',
 
639
                self._get_filtered_inv_stream, 2)
 
640
        GCCHKPacker._copy_chk_texts(self)
 
641
        # Now copy and fix the inventories, and any regenerated CHKs.
 
642
        def chk_canonicalizing_inv_stream(source_vf, keys, message, pb=None):
 
643
            return self._get_filtered_canonicalizing_inv_stream(
 
644
                source_vf, keys, message, pb, source_chk_vf, target_chk_vf)
 
645
        self._copy_stream(source_vf, target_vf, inventory_keys,
 
646
                          'inventories', chk_canonicalizing_inv_stream, 4)
 
647
 
 
648
    def _copy_chk_texts(self):
 
649
        # No-op; in this class this happens during _copy_inventory_texts.
 
650
        pass
 
651
 
 
652
    def _get_filtered_canonicalizing_inv_stream(self, source_vf, keys, message,
 
653
            pb=None, source_chk_vf=None, target_chk_vf=None):
 
654
        """Filter the texts of inventories, regenerating CHKs to make sure they
 
655
        are canonical.
 
656
        """
 
657
        total_keys = len(keys)
 
658
        target_chk_vf = versionedfile.NoDupeAddLinesDecorator(target_chk_vf)
 
659
        def _filtered_inv_stream():
 
660
            stream = source_vf.get_record_stream(keys, 'groupcompress', True)
 
661
            search_key_name = None
 
662
            for idx, record in enumerate(stream):
 
663
                # Inventories should always be with revisions; assume success.
 
664
                bytes = record.get_bytes_as('fulltext')
 
665
                chk_inv = inventory.CHKInventory.deserialise(
 
666
                    source_chk_vf, bytes, record.key)
 
667
                if pb is not None:
 
668
                    pb.update('inv', idx, total_keys)
 
669
                chk_inv.id_to_entry._ensure_root()
 
670
                if search_key_name is None:
 
671
                    # Find the name corresponding to the search_key_func
 
672
                    search_key_reg = chk_map.search_key_registry
 
673
                    for search_key_name, func in viewitems(search_key_reg):
 
674
                        if func == chk_inv.id_to_entry._search_key_func:
 
675
                            break
 
676
                canonical_inv = inventory.CHKInventory.from_inventory(
 
677
                    target_chk_vf, chk_inv,
 
678
                    maximum_size=chk_inv.id_to_entry._root_node._maximum_size,
 
679
                    search_key_name=search_key_name)
 
680
                if chk_inv.id_to_entry.key() != canonical_inv.id_to_entry.key():
 
681
                    trace.mutter(
 
682
                        'Non-canonical CHK map for id_to_entry of inv: %s '
 
683
                        '(root is %s, should be %s)' % (chk_inv.revision_id,
 
684
                        chk_inv.id_to_entry.key()[0],
 
685
                        canonical_inv.id_to_entry.key()[0]))
 
686
                    self._data_changed = True
 
687
                p_id_map = chk_inv.parent_id_basename_to_file_id
 
688
                p_id_map._ensure_root()
 
689
                canon_p_id_map = canonical_inv.parent_id_basename_to_file_id
 
690
                if p_id_map.key() != canon_p_id_map.key():
 
691
                    trace.mutter(
 
692
                        'Non-canonical CHK map for parent_id_to_basename of '
 
693
                        'inv: %s (root is %s, should be %s)'
 
694
                        % (chk_inv.revision_id, p_id_map.key()[0],
 
695
                           canon_p_id_map.key()[0]))
 
696
                    self._data_changed = True
 
697
                yield versionedfile.ChunkedContentFactory(record.key,
 
698
                        record.parents, record.sha1,
 
699
                        canonical_inv.to_lines())
 
700
            # We have finished processing all of the inventory records, we
 
701
            # don't need these sets anymore
 
702
        return _filtered_inv_stream()
 
703
 
 
704
    def _use_pack(self, new_pack):
 
705
        """Override _use_pack to check for reconcile having changed content."""
 
706
        return new_pack.data_inserted() and self._data_changed
 
707
 
 
708
 
583
709
class GCRepositoryPackCollection(RepositoryPackCollection):
584
710
 
585
711
    pack_factory = GCPack
586
712
    resumed_pack_factory = ResumedGCPack
 
713
    normal_packer_class = GCCHKPacker
 
714
    optimising_packer_class = GCCHKPacker
587
715
 
588
716
    def _check_new_inventories(self):
589
717
        """Detect missing inventories or chk root entries for the new revisions
618
746
        # any present parent inventories, which may be used when calculating
619
747
        # deltas for streaming.
620
748
        all_inv_keys = set(corresponding_invs)
621
 
        for parent_inv_keys in inv_parent_map.itervalues():
 
749
        for parent_inv_keys in viewvalues(inv_parent_map):
622
750
            all_inv_keys.update(parent_inv_keys)
623
751
        # Filter out ghost parents.
624
752
        all_inv_keys.intersection_update(
635
763
            expected_chk_roots)
636
764
        missing_chk_roots = expected_chk_roots.difference(present_chk_roots)
637
765
        if missing_chk_roots:
638
 
            problems.append("missing referenced chk root keys: %s"
 
766
            problems.append(
 
767
                "missing referenced chk root keys: %s."
 
768
                "Run 'brz reconcile --canonicalize-chks' on the affected "
 
769
                "repository."
639
770
                % (sorted(missing_chk_roots),))
640
771
            # Don't bother checking any further.
641
772
            return problems
647
778
        chk_diff = chk_map.iter_interesting_nodes(
648
779
            chk_bytes_no_fallbacks, root_key_info.interesting_root_keys,
649
780
            root_key_info.uninteresting_root_keys)
650
 
        bytes_to_info = inventory.CHKInventory._bytes_to_utf8name_key
651
781
        text_keys = set()
652
782
        try:
653
 
            for record in _filter_text_keys(chk_diff, text_keys, bytes_to_info):
 
783
            for record in _filter_text_keys(chk_diff, text_keys,
 
784
                                            chk_map._bytes_to_text_key):
654
785
                pass
655
 
        except errors.NoSuchRevision, e:
 
786
        except errors.NoSuchRevision as e:
656
787
            # XXX: It would be nice if we could give a more precise error here.
657
788
            problems.append("missing chk node(s) for id_to_entry maps")
658
789
        chk_diff = chk_map.iter_interesting_nodes(
661
792
        try:
662
793
            for interesting_rec, interesting_map in chk_diff:
663
794
                pass
664
 
        except errors.NoSuchRevision, e:
 
795
        except errors.NoSuchRevision as e:
665
796
            problems.append(
666
797
                "missing chk node(s) for parent_id_basename_to_file_id maps")
667
798
        present_text_keys = no_fallback_texts_index.get_parent_map(text_keys)
671
802
                % (sorted(missing_text_keys),))
672
803
        return problems
673
804
 
674
 
    def _execute_pack_operations(self, pack_operations,
675
 
                                 _packer_class=GCCHKPacker,
676
 
                                 reload_func=None):
677
 
        """Execute a series of pack operations.
678
 
 
679
 
        :param pack_operations: A list of [revision_count, packs_to_combine].
680
 
        :param _packer_class: The class of packer to use (default: Packer).
681
 
        :return: None.
682
 
        """
683
 
        # XXX: Copied across from RepositoryPackCollection simply because we
684
 
        #      want to override the _packer_class ... :(
685
 
        for revision_count, packs in pack_operations:
686
 
            # we may have no-ops from the setup logic
687
 
            if len(packs) == 0:
688
 
                continue
689
 
            packer = GCCHKPacker(self, packs, '.autopack',
690
 
                                 reload_func=reload_func)
691
 
            try:
692
 
                result = packer.pack()
693
 
            except errors.RetryWithNewPacks:
694
 
                # An exception is propagating out of this context, make sure
695
 
                # this packer has cleaned up. Packer() doesn't set its new_pack
696
 
                # state into the RepositoryPackCollection object, so we only
697
 
                # have access to it directly here.
698
 
                if packer.new_pack is not None:
699
 
                    packer.new_pack.abort()
700
 
                raise
701
 
            if result is None:
702
 
                return
703
 
            for pack in packs:
704
 
                self._remove_pack_from_memory(pack)
705
 
        # record the newly available packs and stop advertising the old
706
 
        # packs
707
 
        to_be_obsoleted = []
708
 
        for _, packs in pack_operations:
709
 
            to_be_obsoleted.extend(packs)
710
 
        result = self._save_pack_names(clear_obsolete_packs=True,
711
 
                                       obsolete_packs=to_be_obsoleted)
712
 
        return result
713
 
 
714
 
 
715
 
class CHKInventoryRepository(KnitPackRepository):
716
 
    """subclass of KnitPackRepository that uses CHK based inventories."""
717
 
 
718
 
    def __init__(self, _format, a_bzrdir, control_files, _commit_builder_class,
 
805
 
 
806
class CHKInventoryRepository(PackRepository):
 
807
    """subclass of PackRepository that uses CHK based inventories."""
 
808
 
 
809
    def __init__(self, _format, a_controldir, control_files, _commit_builder_class,
719
810
        _serializer):
720
811
        """Overridden to change pack collection class."""
721
 
        KnitPackRepository.__init__(self, _format, a_bzrdir, control_files,
722
 
            _commit_builder_class, _serializer)
723
 
        # and now replace everything it did :)
 
812
        super(CHKInventoryRepository, self).__init__(_format, a_controldir,
 
813
            control_files, _commit_builder_class, _serializer)
724
814
        index_transport = self._transport.clone('indices')
725
815
        self._pack_collection = GCRepositoryPackCollection(self,
726
816
            self._transport, index_transport,
816
906
                                 ' no new_path %r' % (file_id,))
817
907
            if new_path == '':
818
908
                new_inv.root_id = file_id
819
 
                parent_id_basename_key = StaticTuple('', '').intern()
 
909
                parent_id_basename_key = StaticTuple(b'', b'').intern()
820
910
            else:
821
911
                utf8_entry_name = entry.name.encode('utf-8')
822
912
                parent_id_basename_key = StaticTuple(entry.parent_id,
864
954
        if basis_inv is None:
865
955
            if basis_revision_id == _mod_revision.NULL_REVISION:
866
956
                new_inv = self._create_inv_from_null(delta, new_revision_id)
 
957
                if new_inv.root_id is None:
 
958
                    raise errors.RootMissing()
867
959
                inv_lines = new_inv.to_lines()
868
960
                return self._inventory_add_lines(new_revision_id, parents,
869
961
                    inv_lines, check_content=False), new_inv
870
962
            else:
871
963
                basis_tree = self.revision_tree(basis_revision_id)
872
964
                basis_tree.lock_read()
873
 
                basis_inv = basis_tree.inventory
 
965
                basis_inv = basis_tree.root_inventory
874
966
        try:
875
967
            result = basis_inv.create_by_apply_delta(delta, new_revision_id,
876
968
                propagate_caches=propagate_caches)
896
988
            if record.storage_kind != 'absent':
897
989
                texts[record.key] = record.get_bytes_as('fulltext')
898
990
            else:
899
 
                raise errors.NoSuchRevision(self, record.key)
 
991
                texts[record.key] = None
900
992
        for key in keys:
901
 
            yield inventory.CHKInventory.deserialise(self.chk_bytes, texts[key], key)
 
993
            bytes = texts[key]
 
994
            if bytes is None:
 
995
                yield (None, key[-1])
 
996
            else:
 
997
                yield (inventory.CHKInventory.deserialise(
 
998
                    self.chk_bytes, bytes, key), key[-1])
902
999
 
903
 
    def _iter_inventory_xmls(self, revision_ids, ordering):
 
1000
    def _get_inventory_xml(self, revision_id):
 
1001
        """Get serialized inventory as a string."""
904
1002
        # Without a native 'xml' inventory, this method doesn't make sense.
905
1003
        # However older working trees, and older bundles want it - so we supply
906
1004
        # it allowing _get_inventory_xml to work. Bundles currently use the
907
1005
        # serializer directly; this also isn't ideal, but there isn't an xml
908
 
        # iteration interface offered at all for repositories. We could make
909
 
        # _iter_inventory_xmls be part of the contract, even if kept private.
910
 
        inv_to_str = self._serializer.write_inventory_to_string
911
 
        for inv in self.iter_inventories(revision_ids, ordering=ordering):
912
 
            yield inv_to_str(inv), inv.revision_id
 
1006
        # iteration interface offered at all for repositories.
 
1007
        return self._serializer.write_inventory_to_string(
 
1008
            self.get_inventory(revision_id))
913
1009
 
914
1010
    def _find_present_inventory_keys(self, revision_keys):
915
1011
        parent_map = self.inventories.get_parent_map(revision_keys)
939
1035
            #       inventories, not missing inventories for revision_ids
940
1036
            present_parent_inv_keys = self._find_present_inventory_keys(
941
1037
                                        parent_keys)
942
 
            present_parent_inv_ids = set(
943
 
                [k[-1] for k in present_parent_inv_keys])
 
1038
            present_parent_inv_ids = {k[-1] for k in present_parent_inv_keys}
944
1039
            inventories_to_read = set(revision_ids)
945
1040
            inventories_to_read.update(present_parent_inv_ids)
946
1041
            root_key_info = _build_interesting_key_sets(
962
1057
                    try:
963
1058
                        file_id_revisions[file_id].add(revision_id)
964
1059
                    except KeyError:
965
 
                        file_id_revisions[file_id] = set([revision_id])
 
1060
                        file_id_revisions[file_id] = {revision_id}
966
1061
        finally:
967
1062
            pb.finished()
968
1063
        return file_id_revisions
999
1094
        finally:
1000
1095
            pb.finished()
1001
1096
 
 
1097
    def reconcile_canonicalize_chks(self):
 
1098
        """Reconcile this repository to make sure all CHKs are in canonical
 
1099
        form.
 
1100
        """
 
1101
        from breezy.reconcile import PackReconciler
 
1102
        with self.lock_write():
 
1103
            reconciler = PackReconciler(self, thorough=True, canonicalize_chks=True)
 
1104
            reconciler.reconcile()
 
1105
            return reconciler
 
1106
 
1002
1107
    def _reconcile_pack(self, collection, packs, extension, revs, pb):
1003
1108
        packer = GCCHKReconcilePacker(collection, packs, extension)
1004
1109
        return packer.pack(pb)
1005
1110
 
 
1111
    def _canonicalize_chks_pack(self, collection, packs, extension, revs, pb):
 
1112
        packer = GCCHKCanonicalizingPacker(collection, packs, extension, revs)
 
1113
        return packer.pack(pb)
 
1114
 
1006
1115
    def _get_source(self, to_format):
1007
1116
        """Return a source for streaming from this repository."""
1008
1117
        if self._format._serializer == to_format._serializer:
1013
1122
            return GroupCHKStreamSource(self, to_format)
1014
1123
        return super(CHKInventoryRepository, self)._get_source(to_format)
1015
1124
 
1016
 
 
1017
 
class GroupCHKStreamSource(KnitPackStreamSource):
 
1125
    def _find_inconsistent_revision_parents(self, revisions_iterator=None):
 
1126
        """Find revisions with different parent lists in the revision object
 
1127
        and in the index graph.
 
1128
 
 
1129
        :param revisions_iterator: None, or an iterator of (revid,
 
1130
            Revision-or-None). This iterator controls the revisions checked.
 
1131
        :returns: an iterator yielding tuples of (revison-id, parents-in-index,
 
1132
            parents-in-revision).
 
1133
        """
 
1134
        if not self.is_locked():
 
1135
            raise AssertionError()
 
1136
        vf = self.revisions
 
1137
        if revisions_iterator is None:
 
1138
            revisions_iterator = self.iter_revisions(self.all_revision_ids())
 
1139
        for revid, revision in revisions_iterator:
 
1140
            if revision is None:
 
1141
                pass
 
1142
            parent_map = vf.get_parent_map([(revid,)])
 
1143
            parents_according_to_index = tuple(parent[-1] for parent in
 
1144
                parent_map[(revid,)])
 
1145
            parents_according_to_revision = tuple(revision.parent_ids)
 
1146
            if parents_according_to_index != parents_according_to_revision:
 
1147
                yield (revid, parents_according_to_index,
 
1148
                    parents_according_to_revision)
 
1149
 
 
1150
    def _check_for_inconsistent_revision_parents(self):
 
1151
        inconsistencies = list(self._find_inconsistent_revision_parents())
 
1152
        if inconsistencies:
 
1153
            raise errors.BzrCheckError(
 
1154
                "Revision index has inconsistent parents.")
 
1155
 
 
1156
 
 
1157
class GroupCHKStreamSource(StreamSource):
1018
1158
    """Used when both the source and target repo are GroupCHK repos."""
1019
1159
 
1020
1160
    def __init__(self, from_repository, to_format):
1087
1227
                uninteresting_root_keys.add(inv.id_to_entry.key())
1088
1228
                uninteresting_pid_root_keys.add(
1089
1229
                    inv.parent_id_basename_to_file_id.key())
1090
 
        bytes_to_info = inventory.CHKInventory._bytes_to_utf8name_key
1091
1230
        chk_bytes = self.from_repository.chk_bytes
1092
1231
        def _filter_id_to_entry():
1093
1232
            interesting_nodes = chk_map.iter_interesting_nodes(chk_bytes,
1094
1233
                        self._chk_id_roots, uninteresting_root_keys)
1095
1234
            for record in _filter_text_keys(interesting_nodes, self._text_keys,
1096
 
                    bytes_to_info):
 
1235
                    chk_map._bytes_to_text_key):
1097
1236
                if record is not None:
1098
1237
                    yield record
1099
1238
            # Consumed
1108
1247
            self._chk_p_id_roots = None
1109
1248
        yield 'chk_bytes', _get_parent_id_basename_to_file_id_pages()
1110
1249
 
 
1250
    def _get_text_stream(self):
 
1251
        # Note: We know we don't have to handle adding root keys, because both
 
1252
        # the source and target are the identical network name.
 
1253
        text_stream = self.from_repository.texts.get_record_stream(
 
1254
                        self._text_keys, self._text_fetch_order, False)
 
1255
        return ('texts', text_stream)
 
1256
 
1111
1257
    def get_stream(self, search):
 
1258
        def wrap_and_count(pb, rc, stream):
 
1259
            """Yield records from stream while showing progress."""
 
1260
            count = 0
 
1261
            for record in stream:
 
1262
                if count == rc.STEP:
 
1263
                    rc.increment(count)
 
1264
                    pb.update('Estimate', rc.current, rc.max)
 
1265
                    count = 0
 
1266
                count += 1
 
1267
                yield record
 
1268
 
1112
1269
        revision_ids = search.get_keys()
 
1270
        pb = ui.ui_factory.nested_progress_bar()
 
1271
        rc = self._record_counter
 
1272
        self._record_counter.setup(len(revision_ids))
1113
1273
        for stream_info in self._fetch_revision_texts(revision_ids):
1114
 
            yield stream_info
 
1274
            yield (stream_info[0],
 
1275
                wrap_and_count(pb, rc, stream_info[1]))
1115
1276
        self._revision_keys = [(rev_id,) for rev_id in revision_ids]
1116
 
        self.from_repository.revisions.clear_cache()
1117
 
        self.from_repository.signatures.clear_cache()
1118
 
        yield self._get_inventory_stream(self._revision_keys)
1119
 
        self.from_repository.inventories.clear_cache()
1120
1277
        # TODO: The keys to exclude might be part of the search recipe
1121
1278
        # For now, exclude all parents that are at the edge of ancestry, for
1122
1279
        # which we have inventories
1123
1280
        from_repo = self.from_repository
1124
1281
        parent_keys = from_repo._find_parent_keys_of_revisions(
1125
1282
                        self._revision_keys)
 
1283
        self.from_repository.revisions.clear_cache()
 
1284
        self.from_repository.signatures.clear_cache()
 
1285
        # Clear the repo's get_parent_map cache too.
 
1286
        self.from_repository._unstacked_provider.disable_cache()
 
1287
        self.from_repository._unstacked_provider.enable_cache()
 
1288
        s = self._get_inventory_stream(self._revision_keys)
 
1289
        yield (s[0], wrap_and_count(pb, rc, s[1]))
 
1290
        self.from_repository.inventories.clear_cache()
1126
1291
        for stream_info in self._get_filtered_chk_streams(parent_keys):
1127
 
            yield stream_info
 
1292
            yield (stream_info[0], wrap_and_count(pb, rc, stream_info[1]))
1128
1293
        self.from_repository.chk_bytes.clear_cache()
1129
 
        yield self._get_text_stream()
 
1294
        s = self._get_text_stream()
 
1295
        yield (s[0], wrap_and_count(pb, rc, s[1]))
1130
1296
        self.from_repository.texts.clear_cache()
 
1297
        pb.update('Done', rc.max, rc.max)
 
1298
        pb.finished()
1131
1299
 
1132
1300
    def get_stream_for_missing_keys(self, missing_keys):
1133
1301
        # missing keys can only occur when we are byte copying and not
1187
1355
    return result
1188
1356
 
1189
1357
 
1190
 
def _filter_text_keys(interesting_nodes_iterable, text_keys, bytes_to_info):
 
1358
def _filter_text_keys(interesting_nodes_iterable, text_keys, bytes_to_text_key):
1191
1359
    """Iterate the result of iter_interesting_nodes, yielding the records
1192
1360
    and adding to text_keys.
1193
1361
    """
 
1362
    text_keys_update = text_keys.update
1194
1363
    for record, items in interesting_nodes_iterable:
1195
 
        for name, bytes in items:
1196
 
            # Note: we don't care about name_utf8, because groupcompress repos
1197
 
            # are always rich-root, so there are no synthesised root records to
1198
 
            # ignore.
1199
 
            _, file_id, revision_id = bytes_to_info(bytes)
1200
 
            file_id = intern(file_id)
1201
 
            revision_id = intern(revision_id)
1202
 
            text_keys.add(StaticTuple(file_id, revision_id).intern())
 
1364
        text_keys_update([bytes_to_text_key(b) for n, b in items])
1203
1365
        yield record
1204
1366
 
1205
1367
 
1206
 
 
1207
 
 
1208
 
class RepositoryFormatCHK1(RepositoryFormatPack):
1209
 
    """A hashed CHK+group compress pack repository."""
 
1368
class RepositoryFormat2a(RepositoryFormatPack):
 
1369
    """A CHK repository that uses the bencode revision serializer."""
1210
1370
 
1211
1371
    repository_class = CHKInventoryRepository
1212
1372
    supports_external_lookups = True
1213
1373
    supports_chks = True
1214
 
    # For right now, setting this to True gives us InterModel1And2 rather
1215
 
    # than InterDifferingSerializer
1216
1374
    _commit_builder_class = PackRootCommitBuilder
1217
1375
    rich_root_data = True
1218
 
    _serializer = chk_serializer.chk_serializer_255_bigpage
 
1376
    _serializer = chk_serializer.chk_bencode_serializer
1219
1377
    _commit_inv_deltas = True
1220
1378
    # What index classes to use
1221
1379
    index_builder_class = BTreeBuilder
1232
1390
    pack_compresses = True
1233
1391
 
1234
1392
    def _get_matching_bzrdir(self):
1235
 
        return bzrdir.format_registry.make_bzrdir('development6-rich-root')
1236
 
 
1237
 
    def _ignore_setting_bzrdir(self, format):
1238
 
        pass
1239
 
 
1240
 
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
1241
 
 
1242
 
    def get_format_string(self):
1243
 
        """See RepositoryFormat.get_format_string()."""
1244
 
        return ('Bazaar development format - group compression and chk inventory'
1245
 
                ' (needs bzr.dev from 1.14)\n')
1246
 
 
1247
 
    def get_format_description(self):
1248
 
        """See RepositoryFormat.get_format_description()."""
1249
 
        return ("Development repository format - rich roots, group compression"
1250
 
            " and chk inventories")
1251
 
 
1252
 
 
1253
 
class RepositoryFormatCHK2(RepositoryFormatCHK1):
1254
 
    """A CHK repository that uses the bencode revision serializer."""
1255
 
 
1256
 
    _serializer = chk_serializer.chk_bencode_serializer
1257
 
 
1258
 
    def _get_matching_bzrdir(self):
1259
 
        return bzrdir.format_registry.make_bzrdir('development7-rich-root')
1260
 
 
1261
 
    def _ignore_setting_bzrdir(self, format):
1262
 
        pass
1263
 
 
1264
 
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
1265
 
 
1266
 
    def get_format_string(self):
1267
 
        """See RepositoryFormat.get_format_string()."""
1268
 
        return ('Bazaar development format - chk repository with bencode '
1269
 
                'revision serialization (needs bzr.dev from 1.16)\n')
1270
 
 
1271
 
 
1272
 
class RepositoryFormat2a(RepositoryFormatCHK2):
1273
 
    """A CHK repository that uses the bencode revision serializer.
1274
 
 
1275
 
    This is the same as RepositoryFormatCHK2 but with a public name.
1276
 
    """
1277
 
 
1278
 
    _serializer = chk_serializer.chk_bencode_serializer
1279
 
 
1280
 
    def _get_matching_bzrdir(self):
1281
 
        return bzrdir.format_registry.make_bzrdir('2a')
1282
 
 
1283
 
    def _ignore_setting_bzrdir(self, format):
1284
 
        pass
1285
 
 
1286
 
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
1287
 
 
1288
 
    def get_format_string(self):
 
1393
        return controldir.format_registry.make_controldir('2a')
 
1394
 
 
1395
    def _ignore_setting_bzrdir(self, format):
 
1396
        pass
 
1397
 
 
1398
    _matchingcontroldir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
1399
 
 
1400
    @classmethod
 
1401
    def get_format_string(cls):
1289
1402
        return ('Bazaar repository format 2a (needs bzr 1.16 or later)\n')
1290
1403
 
1291
1404
    def get_format_description(self):
1292
1405
        """See RepositoryFormat.get_format_description()."""
1293
1406
        return ("Repository format 2a - rich roots, group compression"
1294
1407
            " and chk inventories")
 
1408
 
 
1409
 
 
1410
class RepositoryFormat2aSubtree(RepositoryFormat2a):
 
1411
    """A 2a repository format that supports nested trees.
 
1412
 
 
1413
    """
 
1414
 
 
1415
    def _get_matching_bzrdir(self):
 
1416
        return controldir.format_registry.make_controldir('development-subtree')
 
1417
 
 
1418
    def _ignore_setting_bzrdir(self, format):
 
1419
        pass
 
1420
 
 
1421
    _matchingcontroldir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
1422
 
 
1423
    @classmethod
 
1424
    def get_format_string(cls):
 
1425
        return ('Bazaar development format 8\n')
 
1426
 
 
1427
    def get_format_description(self):
 
1428
        """See RepositoryFormat.get_format_description()."""
 
1429
        return ("Development repository format 8 - nested trees, "
 
1430
                "group compression and chk inventories")
 
1431
 
 
1432
    experimental = True
 
1433
    supports_tree_reference = True