~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/repofmt/pack_repo.py

  • Committer: Andrew Bennetts
  • Date: 2009-08-07 04:17:51 UTC
  • mto: This revision was merged to the branch mainline in revision 4608.
  • Revision ID: andrew.bennetts@canonical.com-20090807041751-0vhb0y0g7k49hr45
Review comments from John.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2007-2011 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2008 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
24
24
 
25
25
from bzrlib import (
26
26
    chk_map,
27
 
    cleanup,
28
27
    debug,
29
28
    graph,
30
29
    osutils,
31
30
    pack,
32
31
    transactions,
33
 
    tsort,
34
32
    ui,
 
33
    xml5,
 
34
    xml6,
 
35
    xml7,
35
36
    )
36
37
from bzrlib.index import (
37
38
    CombinedGraphIndex,
38
39
    GraphIndexPrefixAdapter,
39
40
    )
 
41
from bzrlib.knit import (
 
42
    KnitPlainFactory,
 
43
    KnitVersionedFiles,
 
44
    _KnitGraphIndex,
 
45
    _DirectPackAccess,
 
46
    )
 
47
from bzrlib import tsort
40
48
""")
41
49
from bzrlib import (
42
 
    btree_index,
 
50
    bzrdir,
43
51
    errors,
44
52
    lockable_files,
45
53
    lockdir,
 
54
    revision as _mod_revision,
46
55
    )
47
56
 
48
 
from bzrlib.decorators import (
49
 
    needs_read_lock,
50
 
    needs_write_lock,
51
 
    only_raises,
52
 
    )
53
 
from bzrlib.lock import LogicalLockResult
 
57
from bzrlib.decorators import needs_write_lock
 
58
from bzrlib.btree_index import (
 
59
    BTreeGraphIndex,
 
60
    BTreeBuilder,
 
61
    )
 
62
from bzrlib.index import (
 
63
    GraphIndex,
 
64
    InMemoryGraphIndex,
 
65
    )
 
66
from bzrlib.repofmt.knitrepo import KnitRepository
54
67
from bzrlib.repository import (
55
 
    _LazyListJoin,
56
 
    MetaDirRepository,
 
68
    CommitBuilder,
 
69
    MetaDirRepositoryFormat,
57
70
    RepositoryFormat,
58
 
    RepositoryWriteLockResult,
59
 
    )
60
 
from bzrlib.vf_repository import (
61
 
    MetaDirVersionedFileRepository,
62
 
    MetaDirVersionedFileRepositoryFormat,
63
 
    VersionedFileCommitBuilder,
64
 
    VersionedFileRootCommitBuilder,
 
71
    RootCommitBuilder,
 
72
    StreamSource,
65
73
    )
66
74
from bzrlib.trace import (
67
75
    mutter,
68
 
    note,
69
76
    warning,
70
77
    )
71
78
 
72
79
 
73
 
class PackCommitBuilder(VersionedFileCommitBuilder):
74
 
    """Subclass of VersionedFileCommitBuilder to add texts with pack semantics.
 
80
class PackCommitBuilder(CommitBuilder):
 
81
    """A subclass of CommitBuilder to add texts with pack semantics.
75
82
 
76
83
    Specifically this uses one knit object rather than one knit object per
77
84
    added text, reducing memory and object pressure.
79
86
 
80
87
    def __init__(self, repository, parents, config, timestamp=None,
81
88
                 timezone=None, committer=None, revprops=None,
82
 
                 revision_id=None, lossy=False):
83
 
        VersionedFileCommitBuilder.__init__(self, repository, parents, config,
 
89
                 revision_id=None):
 
90
        CommitBuilder.__init__(self, repository, parents, config,
84
91
            timestamp=timestamp, timezone=timezone, committer=committer,
85
 
            revprops=revprops, revision_id=revision_id, lossy=lossy)
 
92
            revprops=revprops, revision_id=revision_id)
86
93
        self._file_graph = graph.Graph(
87
94
            repository._pack_collection.text_index.combined_index)
88
95
 
91
98
        return set([key[1] for key in self._file_graph.heads(keys)])
92
99
 
93
100
 
94
 
class PackRootCommitBuilder(VersionedFileRootCommitBuilder):
 
101
class PackRootCommitBuilder(RootCommitBuilder):
95
102
    """A subclass of RootCommitBuilder to add texts with pack semantics.
96
103
 
97
104
    Specifically this uses one knit object rather than one knit object per
100
107
 
101
108
    def __init__(self, repository, parents, config, timestamp=None,
102
109
                 timezone=None, committer=None, revprops=None,
103
 
                 revision_id=None, lossy=False):
104
 
        super(PackRootCommitBuilder, self).__init__(repository, parents,
105
 
            config, timestamp=timestamp, timezone=timezone,
106
 
            committer=committer, revprops=revprops, revision_id=revision_id,
107
 
            lossy=lossy)
 
110
                 revision_id=None):
 
111
        CommitBuilder.__init__(self, repository, parents, config,
 
112
            timestamp=timestamp, timezone=timezone, committer=committer,
 
113
            revprops=revprops, revision_id=revision_id)
108
114
        self._file_graph = graph.Graph(
109
115
            repository._pack_collection.text_index.combined_index)
110
116
 
218
224
        return self.index_name('text', name)
219
225
 
220
226
    def _replace_index_with_readonly(self, index_type):
221
 
        unlimited_cache = False
222
 
        if index_type == 'chk':
223
 
            unlimited_cache = True
224
 
        index = self.index_class(self.index_transport,
225
 
                    self.index_name(index_type, self.name),
226
 
                    self.index_sizes[self.index_offset(index_type)],
227
 
                    unlimited_cache=unlimited_cache)
228
 
        if index_type == 'chk':
229
 
            index._leaf_factory = btree_index._gcchk_factory
230
 
        setattr(self, index_type + '_index', index)
 
227
        setattr(self, index_type + '_index',
 
228
            self.index_class(self.index_transport,
 
229
                self.index_name(index_type, self.name),
 
230
                self.index_sizes[self.index_offset(index_type)]))
231
231
 
232
232
 
233
233
class ExistingPack(Pack):
314
314
        for index_type in index_types:
315
315
            old_name = self.index_name(index_type, self.name)
316
316
            new_name = '../indices/' + old_name
317
 
            self.upload_transport.move(old_name, new_name)
 
317
            self.upload_transport.rename(old_name, new_name)
318
318
            self._replace_index_with_readonly(index_type)
319
319
        new_name = '../packs/' + self.file_name()
320
 
        self.upload_transport.move(self.file_name(), new_name)
 
320
        self.upload_transport.rename(self.file_name(), new_name)
321
321
        self._state = 'finished'
322
322
 
323
323
    def _get_external_refs(self, index):
503
503
        new_name = self.name + '.pack'
504
504
        if not suspend:
505
505
            new_name = '../packs/' + new_name
506
 
        self.upload_transport.move(self.random_name, new_name)
 
506
        self.upload_transport.rename(self.random_name, new_name)
507
507
        self._state = 'finished'
508
508
        if 'pack' in debug.debug_flags:
509
509
            # XXX: size might be interesting?
581
581
                                             flush_func=flush_func)
582
582
        self.add_callback = None
583
583
 
 
584
    def replace_indices(self, index_to_pack, indices):
 
585
        """Replace the current mappings with fresh ones.
 
586
 
 
587
        This should probably not be used eventually, rather incremental add and
 
588
        removal of indices. It has been added during refactoring of existing
 
589
        code.
 
590
 
 
591
        :param index_to_pack: A mapping from index objects to
 
592
            (transport, name) tuples for the pack file data.
 
593
        :param indices: A list of indices.
 
594
        """
 
595
        # refresh the revision pack map dict without replacing the instance.
 
596
        self.index_to_pack.clear()
 
597
        self.index_to_pack.update(index_to_pack)
 
598
        # XXX: API break - clearly a 'replace' method would be good?
 
599
        self.combined_index._indices[:] = indices
 
600
        # the current add nodes callback for the current writable index if
 
601
        # there is one.
 
602
        self.add_callback = None
 
603
 
584
604
    def add_index(self, index, pack):
585
605
        """Add index to the aggregate, which is an index for Pack pack.
586
606
 
593
613
        # expose it to the index map
594
614
        self.index_to_pack[index] = pack.access_tuple()
595
615
        # put it at the front of the linear index list
596
 
        self.combined_index.insert_index(0, index, pack.name)
 
616
        self.combined_index.insert_index(0, index)
597
617
 
598
618
    def add_writable_index(self, index, pack):
599
619
        """Add an index which is able to have data added to it.
619
639
        self.data_access.set_writer(None, None, (None, None))
620
640
        self.index_to_pack.clear()
621
641
        del self.combined_index._indices[:]
622
 
        del self.combined_index._index_names[:]
623
642
        self.add_callback = None
624
643
 
625
 
    def remove_index(self, index):
 
644
    def remove_index(self, index, pack):
626
645
        """Remove index from the indices used to answer queries.
627
646
 
628
647
        :param index: An index from the pack parameter.
 
648
        :param pack: A Pack instance.
629
649
        """
630
650
        del self.index_to_pack[index]
631
 
        pos = self.combined_index._indices.index(index)
632
 
        del self.combined_index._indices[pos]
633
 
        del self.combined_index._index_names[pos]
 
651
        self.combined_index._indices.remove(index)
634
652
        if (self.add_callback is not None and
635
653
            getattr(index, 'add_nodes', None) == self.add_callback):
636
654
            self.add_callback = None
666
684
        # What text keys to copy. None for 'all texts'. This is set by
667
685
        # _copy_inventory_texts
668
686
        self._text_filter = None
 
687
        self._extra_init()
 
688
 
 
689
    def _extra_init(self):
 
690
        """A template hook to allow extending the constructor trivially."""
 
691
 
 
692
    def _pack_map_and_index_list(self, index_attribute):
 
693
        """Convert a list of packs to an index pack map and index list.
 
694
 
 
695
        :param index_attribute: The attribute that the desired index is found
 
696
            on.
 
697
        :return: A tuple (map, list) where map contains the dict from
 
698
            index:pack_tuple, and list contains the indices in the preferred
 
699
            access order.
 
700
        """
 
701
        indices = []
 
702
        pack_map = {}
 
703
        for pack_obj in self.packs:
 
704
            index = getattr(pack_obj, index_attribute)
 
705
            indices.append(index)
 
706
            pack_map[index] = pack_obj
 
707
        return pack_map, indices
 
708
 
 
709
    def _index_contents(self, indices, key_filter=None):
 
710
        """Get an iterable of the index contents from a pack_map.
 
711
 
 
712
        :param indices: The list of indices to query
 
713
        :param key_filter: An optional filter to limit the keys returned.
 
714
        """
 
715
        all_index = CombinedGraphIndex(indices)
 
716
        if key_filter is None:
 
717
            return all_index.iter_all_entries()
 
718
        else:
 
719
            return all_index.iter_entries(key_filter)
669
720
 
670
721
    def pack(self, pb=None):
671
722
        """Create a new pack by reading data from other packs.
682
733
        :return: A Pack object, or None if nothing was copied.
683
734
        """
684
735
        # open a pack - using the same name as the last temporary file
685
 
        # - which has already been flushed, so it's safe.
 
736
        # - which has already been flushed, so its safe.
686
737
        # XXX: - duplicate code warning with start_write_group; fix before
687
738
        #      considering 'done'.
688
739
        if self._pack_collection._new_pack is not None:
720
771
        new_pack.signature_index.set_optimize(combine_backing_indices=False)
721
772
        return new_pack
722
773
 
 
774
    def _update_pack_order(self, entries, index_to_pack_map):
 
775
        """Determine how we want our packs to be ordered.
 
776
 
 
777
        This changes the sort order of the self.packs list so that packs unused
 
778
        by 'entries' will be at the end of the list, so that future requests
 
779
        can avoid probing them.  Used packs will be at the front of the
 
780
        self.packs list, in the order of their first use in 'entries'.
 
781
 
 
782
        :param entries: A list of (index, ...) tuples
 
783
        :param index_to_pack_map: A mapping from index objects to pack objects.
 
784
        """
 
785
        packs = []
 
786
        seen_indexes = set()
 
787
        for entry in entries:
 
788
            index = entry[0]
 
789
            if index not in seen_indexes:
 
790
                packs.append(index_to_pack_map[index])
 
791
                seen_indexes.add(index)
 
792
        if len(packs) == len(self.packs):
 
793
            if 'pack' in debug.debug_flags:
 
794
                mutter('Not changing pack list, all packs used.')
 
795
            return
 
796
        seen_packs = set(packs)
 
797
        for pack in self.packs:
 
798
            if pack not in seen_packs:
 
799
                packs.append(pack)
 
800
                seen_packs.add(pack)
 
801
        if 'pack' in debug.debug_flags:
 
802
            old_names = [p.access_tuple()[1] for p in self.packs]
 
803
            new_names = [p.access_tuple()[1] for p in packs]
 
804
            mutter('Reordering packs\nfrom: %s\n  to: %s',
 
805
                   old_names, new_names)
 
806
        self.packs = packs
 
807
 
723
808
    def _copy_revision_texts(self):
724
809
        """Copy revision data to the new pack."""
725
 
        raise NotImplementedError(self._copy_revision_texts)
 
810
        # select revisions
 
811
        if self.revision_ids:
 
812
            revision_keys = [(revision_id,) for revision_id in self.revision_ids]
 
813
        else:
 
814
            revision_keys = None
 
815
        # select revision keys
 
816
        revision_index_map, revision_indices = self._pack_map_and_index_list(
 
817
            'revision_index')
 
818
        revision_nodes = self._index_contents(revision_indices, revision_keys)
 
819
        revision_nodes = list(revision_nodes)
 
820
        self._update_pack_order(revision_nodes, revision_index_map)
 
821
        # copy revision keys and adjust values
 
822
        self.pb.update("Copying revision texts", 1)
 
823
        total_items, readv_group_iter = self._revision_node_readv(revision_nodes)
 
824
        list(self._copy_nodes_graph(revision_index_map, self.new_pack._writer,
 
825
            self.new_pack.revision_index, readv_group_iter, total_items))
 
826
        if 'pack' in debug.debug_flags:
 
827
            mutter('%s: create_pack: revisions copied: %s%s %d items t+%6.3fs',
 
828
                time.ctime(), self._pack_collection._upload_transport.base,
 
829
                self.new_pack.random_name,
 
830
                self.new_pack.revision_index.key_count(),
 
831
                time.time() - self.new_pack.start_time)
 
832
        self._revision_keys = revision_keys
726
833
 
727
834
    def _copy_inventory_texts(self):
728
835
        """Copy the inventory texts to the new pack.
731
838
 
732
839
        Sets self._text_filter appropriately.
733
840
        """
734
 
        raise NotImplementedError(self._copy_inventory_texts)
 
841
        # select inventory keys
 
842
        inv_keys = self._revision_keys # currently the same keyspace, and note that
 
843
        # querying for keys here could introduce a bug where an inventory item
 
844
        # is missed, so do not change it to query separately without cross
 
845
        # checking like the text key check below.
 
846
        inventory_index_map, inventory_indices = self._pack_map_and_index_list(
 
847
            'inventory_index')
 
848
        inv_nodes = self._index_contents(inventory_indices, inv_keys)
 
849
        # copy inventory keys and adjust values
 
850
        # XXX: Should be a helper function to allow different inv representation
 
851
        # at this point.
 
852
        self.pb.update("Copying inventory texts", 2)
 
853
        total_items, readv_group_iter = self._least_readv_node_readv(inv_nodes)
 
854
        # Only grab the output lines if we will be processing them
 
855
        output_lines = bool(self.revision_ids)
 
856
        inv_lines = self._copy_nodes_graph(inventory_index_map,
 
857
            self.new_pack._writer, self.new_pack.inventory_index,
 
858
            readv_group_iter, total_items, output_lines=output_lines)
 
859
        if self.revision_ids:
 
860
            self._process_inventory_lines(inv_lines)
 
861
        else:
 
862
            # eat the iterator to cause it to execute.
 
863
            list(inv_lines)
 
864
            self._text_filter = None
 
865
        if 'pack' in debug.debug_flags:
 
866
            mutter('%s: create_pack: inventories copied: %s%s %d items t+%6.3fs',
 
867
                time.ctime(), self._pack_collection._upload_transport.base,
 
868
                self.new_pack.random_name,
 
869
                self.new_pack.inventory_index.key_count(),
 
870
                time.time() - self.new_pack.start_time)
735
871
 
736
872
    def _copy_text_texts(self):
737
 
        raise NotImplementedError(self._copy_text_texts)
 
873
        # select text keys
 
874
        text_index_map, text_nodes = self._get_text_nodes()
 
875
        if self._text_filter is not None:
 
876
            # We could return the keys copied as part of the return value from
 
877
            # _copy_nodes_graph but this doesn't work all that well with the
 
878
            # need to get line output too, so we check separately, and as we're
 
879
            # going to buffer everything anyway, we check beforehand, which
 
880
            # saves reading knit data over the wire when we know there are
 
881
            # mising records.
 
882
            text_nodes = set(text_nodes)
 
883
            present_text_keys = set(_node[1] for _node in text_nodes)
 
884
            missing_text_keys = set(self._text_filter) - present_text_keys
 
885
            if missing_text_keys:
 
886
                # TODO: raise a specific error that can handle many missing
 
887
                # keys.
 
888
                mutter("missing keys during fetch: %r", missing_text_keys)
 
889
                a_missing_key = missing_text_keys.pop()
 
890
                raise errors.RevisionNotPresent(a_missing_key[1],
 
891
                    a_missing_key[0])
 
892
        # copy text keys and adjust values
 
893
        self.pb.update("Copying content texts", 3)
 
894
        total_items, readv_group_iter = self._least_readv_node_readv(text_nodes)
 
895
        list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
 
896
            self.new_pack.text_index, readv_group_iter, total_items))
 
897
        self._log_copied_texts()
738
898
 
739
899
    def _create_pack_from_packs(self):
740
 
        raise NotImplementedError(self._create_pack_from_packs)
 
900
        self.pb.update("Opening pack", 0, 5)
 
901
        self.new_pack = self.open_pack()
 
902
        new_pack = self.new_pack
 
903
        # buffer data - we won't be reading-back during the pack creation and
 
904
        # this makes a significant difference on sftp pushes.
 
905
        new_pack.set_write_cache_size(1024*1024)
 
906
        if 'pack' in debug.debug_flags:
 
907
            plain_pack_list = ['%s%s' % (a_pack.pack_transport.base, a_pack.name)
 
908
                for a_pack in self.packs]
 
909
            if self.revision_ids is not None:
 
910
                rev_count = len(self.revision_ids)
 
911
            else:
 
912
                rev_count = 'all'
 
913
            mutter('%s: create_pack: creating pack from source packs: '
 
914
                '%s%s %s revisions wanted %s t=0',
 
915
                time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
 
916
                plain_pack_list, rev_count)
 
917
        self._copy_revision_texts()
 
918
        self._copy_inventory_texts()
 
919
        self._copy_text_texts()
 
920
        # select signature keys
 
921
        signature_filter = self._revision_keys # same keyspace
 
922
        signature_index_map, signature_indices = self._pack_map_and_index_list(
 
923
            'signature_index')
 
924
        signature_nodes = self._index_contents(signature_indices,
 
925
            signature_filter)
 
926
        # copy signature keys and adjust values
 
927
        self.pb.update("Copying signature texts", 4)
 
928
        self._copy_nodes(signature_nodes, signature_index_map, new_pack._writer,
 
929
            new_pack.signature_index)
 
930
        if 'pack' in debug.debug_flags:
 
931
            mutter('%s: create_pack: revision signatures copied: %s%s %d items t+%6.3fs',
 
932
                time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
 
933
                new_pack.signature_index.key_count(),
 
934
                time.time() - new_pack.start_time)
 
935
        # copy chk contents
 
936
        # NB XXX: how to check CHK references are present? perhaps by yielding
 
937
        # the items? How should that interact with stacked repos?
 
938
        if new_pack.chk_index is not None:
 
939
            self._copy_chks()
 
940
            if 'pack' in debug.debug_flags:
 
941
                mutter('%s: create_pack: chk content copied: %s%s %d items t+%6.3fs',
 
942
                    time.ctime(), self._pack_collection._upload_transport.base,
 
943
                    new_pack.random_name,
 
944
                    new_pack.chk_index.key_count(),
 
945
                    time.time() - new_pack.start_time)
 
946
        new_pack._check_references()
 
947
        if not self._use_pack(new_pack):
 
948
            new_pack.abort()
 
949
            return None
 
950
        self.pb.update("Finishing pack", 5)
 
951
        new_pack.finish()
 
952
        self._pack_collection.allocate(new_pack)
 
953
        return new_pack
 
954
 
 
955
    def _copy_chks(self, refs=None):
 
956
        # XXX: Todo, recursive follow-pointers facility when fetching some
 
957
        # revisions only.
 
958
        chk_index_map, chk_indices = self._pack_map_and_index_list(
 
959
            'chk_index')
 
960
        chk_nodes = self._index_contents(chk_indices, refs)
 
961
        new_refs = set()
 
962
        # TODO: This isn't strictly tasteful as we are accessing some private
 
963
        #       variables (_serializer). Perhaps a better way would be to have
 
964
        #       Repository._deserialise_chk_node()
 
965
        search_key_func = chk_map.search_key_registry.get(
 
966
            self._pack_collection.repo._serializer.search_key_name)
 
967
        def accumlate_refs(lines):
 
968
            # XXX: move to a generic location
 
969
            # Yay mismatch:
 
970
            bytes = ''.join(lines)
 
971
            node = chk_map._deserialise(bytes, ("unknown",), search_key_func)
 
972
            new_refs.update(node.refs())
 
973
        self._copy_nodes(chk_nodes, chk_index_map, self.new_pack._writer,
 
974
            self.new_pack.chk_index, output_lines=accumlate_refs)
 
975
        return new_refs
 
976
 
 
977
    def _copy_nodes(self, nodes, index_map, writer, write_index,
 
978
        output_lines=None):
 
979
        """Copy knit nodes between packs with no graph references.
 
980
 
 
981
        :param output_lines: Output full texts of copied items.
 
982
        """
 
983
        pb = ui.ui_factory.nested_progress_bar()
 
984
        try:
 
985
            return self._do_copy_nodes(nodes, index_map, writer,
 
986
                write_index, pb, output_lines=output_lines)
 
987
        finally:
 
988
            pb.finished()
 
989
 
 
990
    def _do_copy_nodes(self, nodes, index_map, writer, write_index, pb,
 
991
        output_lines=None):
 
992
        # for record verification
 
993
        knit = KnitVersionedFiles(None, None)
 
994
        # plan a readv on each source pack:
 
995
        # group by pack
 
996
        nodes = sorted(nodes)
 
997
        # how to map this into knit.py - or knit.py into this?
 
998
        # we don't want the typical knit logic, we want grouping by pack
 
999
        # at this point - perhaps a helper library for the following code
 
1000
        # duplication points?
 
1001
        request_groups = {}
 
1002
        for index, key, value in nodes:
 
1003
            if index not in request_groups:
 
1004
                request_groups[index] = []
 
1005
            request_groups[index].append((key, value))
 
1006
        record_index = 0
 
1007
        pb.update("Copied record", record_index, len(nodes))
 
1008
        for index, items in request_groups.iteritems():
 
1009
            pack_readv_requests = []
 
1010
            for key, value in items:
 
1011
                # ---- KnitGraphIndex.get_position
 
1012
                bits = value[1:].split(' ')
 
1013
                offset, length = int(bits[0]), int(bits[1])
 
1014
                pack_readv_requests.append((offset, length, (key, value[0])))
 
1015
            # linear scan up the pack
 
1016
            pack_readv_requests.sort()
 
1017
            # copy the data
 
1018
            pack_obj = index_map[index]
 
1019
            transport, path = pack_obj.access_tuple()
 
1020
            try:
 
1021
                reader = pack.make_readv_reader(transport, path,
 
1022
                    [offset[0:2] for offset in pack_readv_requests])
 
1023
            except errors.NoSuchFile:
 
1024
                if self._reload_func is not None:
 
1025
                    self._reload_func()
 
1026
                raise
 
1027
            for (names, read_func), (_1, _2, (key, eol_flag)) in \
 
1028
                izip(reader.iter_records(), pack_readv_requests):
 
1029
                raw_data = read_func(None)
 
1030
                # check the header only
 
1031
                if output_lines is not None:
 
1032
                    output_lines(knit._parse_record(key[-1], raw_data)[0])
 
1033
                else:
 
1034
                    df, _ = knit._parse_record_header(key, raw_data)
 
1035
                    df.close()
 
1036
                pos, size = writer.add_bytes_record(raw_data, names)
 
1037
                write_index.add_node(key, eol_flag + "%d %d" % (pos, size))
 
1038
                pb.update("Copied record", record_index)
 
1039
                record_index += 1
 
1040
 
 
1041
    def _copy_nodes_graph(self, index_map, writer, write_index,
 
1042
        readv_group_iter, total_items, output_lines=False):
 
1043
        """Copy knit nodes between packs.
 
1044
 
 
1045
        :param output_lines: Return lines present in the copied data as
 
1046
            an iterator of line,version_id.
 
1047
        """
 
1048
        pb = ui.ui_factory.nested_progress_bar()
 
1049
        try:
 
1050
            for result in self._do_copy_nodes_graph(index_map, writer,
 
1051
                write_index, output_lines, pb, readv_group_iter, total_items):
 
1052
                yield result
 
1053
        except Exception:
 
1054
            # Python 2.4 does not permit try:finally: in a generator.
 
1055
            pb.finished()
 
1056
            raise
 
1057
        else:
 
1058
            pb.finished()
 
1059
 
 
1060
    def _do_copy_nodes_graph(self, index_map, writer, write_index,
 
1061
        output_lines, pb, readv_group_iter, total_items):
 
1062
        # for record verification
 
1063
        knit = KnitVersionedFiles(None, None)
 
1064
        # for line extraction when requested (inventories only)
 
1065
        if output_lines:
 
1066
            factory = KnitPlainFactory()
 
1067
        record_index = 0
 
1068
        pb.update("Copied record", record_index, total_items)
 
1069
        for index, readv_vector, node_vector in readv_group_iter:
 
1070
            # copy the data
 
1071
            pack_obj = index_map[index]
 
1072
            transport, path = pack_obj.access_tuple()
 
1073
            try:
 
1074
                reader = pack.make_readv_reader(transport, path, readv_vector)
 
1075
            except errors.NoSuchFile:
 
1076
                if self._reload_func is not None:
 
1077
                    self._reload_func()
 
1078
                raise
 
1079
            for (names, read_func), (key, eol_flag, references) in \
 
1080
                izip(reader.iter_records(), node_vector):
 
1081
                raw_data = read_func(None)
 
1082
                if output_lines:
 
1083
                    # read the entire thing
 
1084
                    content, _ = knit._parse_record(key[-1], raw_data)
 
1085
                    if len(references[-1]) == 0:
 
1086
                        line_iterator = factory.get_fulltext_content(content)
 
1087
                    else:
 
1088
                        line_iterator = factory.get_linedelta_content(content)
 
1089
                    for line in line_iterator:
 
1090
                        yield line, key
 
1091
                else:
 
1092
                    # check the header only
 
1093
                    df, _ = knit._parse_record_header(key, raw_data)
 
1094
                    df.close()
 
1095
                pos, size = writer.add_bytes_record(raw_data, names)
 
1096
                write_index.add_node(key, eol_flag + "%d %d" % (pos, size), references)
 
1097
                pb.update("Copied record", record_index)
 
1098
                record_index += 1
 
1099
 
 
1100
    def _get_text_nodes(self):
 
1101
        text_index_map, text_indices = self._pack_map_and_index_list(
 
1102
            'text_index')
 
1103
        return text_index_map, self._index_contents(text_indices,
 
1104
            self._text_filter)
 
1105
 
 
1106
    def _least_readv_node_readv(self, nodes):
 
1107
        """Generate request groups for nodes using the least readv's.
 
1108
 
 
1109
        :param nodes: An iterable of graph index nodes.
 
1110
        :return: Total node count and an iterator of the data needed to perform
 
1111
            readvs to obtain the data for nodes. Each item yielded by the
 
1112
            iterator is a tuple with:
 
1113
            index, readv_vector, node_vector. readv_vector is a list ready to
 
1114
            hand to the transport readv method, and node_vector is a list of
 
1115
            (key, eol_flag, references) for the the node retrieved by the
 
1116
            matching readv_vector.
 
1117
        """
 
1118
        # group by pack so we do one readv per pack
 
1119
        nodes = sorted(nodes)
 
1120
        total = len(nodes)
 
1121
        request_groups = {}
 
1122
        for index, key, value, references in nodes:
 
1123
            if index not in request_groups:
 
1124
                request_groups[index] = []
 
1125
            request_groups[index].append((key, value, references))
 
1126
        result = []
 
1127
        for index, items in request_groups.iteritems():
 
1128
            pack_readv_requests = []
 
1129
            for key, value, references in items:
 
1130
                # ---- KnitGraphIndex.get_position
 
1131
                bits = value[1:].split(' ')
 
1132
                offset, length = int(bits[0]), int(bits[1])
 
1133
                pack_readv_requests.append(
 
1134
                    ((offset, length), (key, value[0], references)))
 
1135
            # linear scan up the pack to maximum range combining.
 
1136
            pack_readv_requests.sort()
 
1137
            # split out the readv and the node data.
 
1138
            pack_readv = [readv for readv, node in pack_readv_requests]
 
1139
            node_vector = [node for readv, node in pack_readv_requests]
 
1140
            result.append((index, pack_readv, node_vector))
 
1141
        return total, result
741
1142
 
742
1143
    def _log_copied_texts(self):
743
1144
        if 'pack' in debug.debug_flags:
747
1148
                self.new_pack.text_index.key_count(),
748
1149
                time.time() - self.new_pack.start_time)
749
1150
 
 
1151
    def _process_inventory_lines(self, inv_lines):
 
1152
        """Use up the inv_lines generator and setup a text key filter."""
 
1153
        repo = self._pack_collection.repo
 
1154
        fileid_revisions = repo._find_file_ids_from_xml_inventory_lines(
 
1155
            inv_lines, self.revision_keys)
 
1156
        text_filter = []
 
1157
        for fileid, file_revids in fileid_revisions.iteritems():
 
1158
            text_filter.extend([(fileid, file_revid) for file_revid in file_revids])
 
1159
        self._text_filter = text_filter
 
1160
 
 
1161
    def _revision_node_readv(self, revision_nodes):
 
1162
        """Return the total revisions and the readv's to issue.
 
1163
 
 
1164
        :param revision_nodes: The revision index contents for the packs being
 
1165
            incorporated into the new pack.
 
1166
        :return: As per _least_readv_node_readv.
 
1167
        """
 
1168
        return self._least_readv_node_readv(revision_nodes)
 
1169
 
750
1170
    def _use_pack(self, new_pack):
751
1171
        """Return True if new_pack should be used.
752
1172
 
756
1176
        return new_pack.data_inserted()
757
1177
 
758
1178
 
 
1179
class OptimisingPacker(Packer):
 
1180
    """A packer which spends more time to create better disk layouts."""
 
1181
 
 
1182
    def _revision_node_readv(self, revision_nodes):
 
1183
        """Return the total revisions and the readv's to issue.
 
1184
 
 
1185
        This sort places revisions in topological order with the ancestors
 
1186
        after the children.
 
1187
 
 
1188
        :param revision_nodes: The revision index contents for the packs being
 
1189
            incorporated into the new pack.
 
1190
        :return: As per _least_readv_node_readv.
 
1191
        """
 
1192
        # build an ancestors dict
 
1193
        ancestors = {}
 
1194
        by_key = {}
 
1195
        for index, key, value, references in revision_nodes:
 
1196
            ancestors[key] = references[0]
 
1197
            by_key[key] = (index, value, references)
 
1198
        order = tsort.topo_sort(ancestors)
 
1199
        total = len(order)
 
1200
        # Single IO is pathological, but it will work as a starting point.
 
1201
        requests = []
 
1202
        for key in reversed(order):
 
1203
            index, value, references = by_key[key]
 
1204
            # ---- KnitGraphIndex.get_position
 
1205
            bits = value[1:].split(' ')
 
1206
            offset, length = int(bits[0]), int(bits[1])
 
1207
            requests.append(
 
1208
                (index, [(offset, length)], [(key, value[0], references)]))
 
1209
        # TODO: combine requests in the same index that are in ascending order.
 
1210
        return total, requests
 
1211
 
 
1212
    def open_pack(self):
 
1213
        """Open a pack for the pack we are creating."""
 
1214
        new_pack = super(OptimisingPacker, self).open_pack()
 
1215
        # Turn on the optimization flags for all the index builders.
 
1216
        new_pack.revision_index.set_optimize(for_size=True)
 
1217
        new_pack.inventory_index.set_optimize(for_size=True)
 
1218
        new_pack.text_index.set_optimize(for_size=True)
 
1219
        new_pack.signature_index.set_optimize(for_size=True)
 
1220
        return new_pack
 
1221
 
 
1222
 
 
1223
class ReconcilePacker(Packer):
 
1224
    """A packer which regenerates indices etc as it copies.
 
1225
 
 
1226
    This is used by ``bzr reconcile`` to cause parent text pointers to be
 
1227
    regenerated.
 
1228
    """
 
1229
 
 
1230
    def _extra_init(self):
 
1231
        self._data_changed = False
 
1232
 
 
1233
    def _process_inventory_lines(self, inv_lines):
 
1234
        """Generate a text key reference map rather for reconciling with."""
 
1235
        repo = self._pack_collection.repo
 
1236
        refs = repo._find_text_key_references_from_xml_inventory_lines(
 
1237
            inv_lines)
 
1238
        self._text_refs = refs
 
1239
        # during reconcile we:
 
1240
        #  - convert unreferenced texts to full texts
 
1241
        #  - correct texts which reference a text not copied to be full texts
 
1242
        #  - copy all others as-is but with corrected parents.
 
1243
        #  - so at this point we don't know enough to decide what becomes a full
 
1244
        #    text.
 
1245
        self._text_filter = None
 
1246
 
 
1247
    def _copy_text_texts(self):
 
1248
        """generate what texts we should have and then copy."""
 
1249
        self.pb.update("Copying content texts", 3)
 
1250
        # we have three major tasks here:
 
1251
        # 1) generate the ideal index
 
1252
        repo = self._pack_collection.repo
 
1253
        ancestors = dict([(key[0], tuple(ref[0] for ref in refs[0])) for
 
1254
            _1, key, _2, refs in
 
1255
            self.new_pack.revision_index.iter_all_entries()])
 
1256
        ideal_index = repo._generate_text_key_index(self._text_refs, ancestors)
 
1257
        # 2) generate a text_nodes list that contains all the deltas that can
 
1258
        #    be used as-is, with corrected parents.
 
1259
        ok_nodes = []
 
1260
        bad_texts = []
 
1261
        discarded_nodes = []
 
1262
        NULL_REVISION = _mod_revision.NULL_REVISION
 
1263
        text_index_map, text_nodes = self._get_text_nodes()
 
1264
        for node in text_nodes:
 
1265
            # 0 - index
 
1266
            # 1 - key
 
1267
            # 2 - value
 
1268
            # 3 - refs
 
1269
            try:
 
1270
                ideal_parents = tuple(ideal_index[node[1]])
 
1271
            except KeyError:
 
1272
                discarded_nodes.append(node)
 
1273
                self._data_changed = True
 
1274
            else:
 
1275
                if ideal_parents == (NULL_REVISION,):
 
1276
                    ideal_parents = ()
 
1277
                if ideal_parents == node[3][0]:
 
1278
                    # no change needed.
 
1279
                    ok_nodes.append(node)
 
1280
                elif ideal_parents[0:1] == node[3][0][0:1]:
 
1281
                    # the left most parent is the same, or there are no parents
 
1282
                    # today. Either way, we can preserve the representation as
 
1283
                    # long as we change the refs to be inserted.
 
1284
                    self._data_changed = True
 
1285
                    ok_nodes.append((node[0], node[1], node[2],
 
1286
                        (ideal_parents, node[3][1])))
 
1287
                    self._data_changed = True
 
1288
                else:
 
1289
                    # Reinsert this text completely
 
1290
                    bad_texts.append((node[1], ideal_parents))
 
1291
                    self._data_changed = True
 
1292
        # we're finished with some data.
 
1293
        del ideal_index
 
1294
        del text_nodes
 
1295
        # 3) bulk copy the ok data
 
1296
        total_items, readv_group_iter = self._least_readv_node_readv(ok_nodes)
 
1297
        list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
 
1298
            self.new_pack.text_index, readv_group_iter, total_items))
 
1299
        # 4) adhoc copy all the other texts.
 
1300
        # We have to topologically insert all texts otherwise we can fail to
 
1301
        # reconcile when parts of a single delta chain are preserved intact,
 
1302
        # and other parts are not. E.g. Discarded->d1->d2->d3. d1 will be
 
1303
        # reinserted, and if d3 has incorrect parents it will also be
 
1304
        # reinserted. If we insert d3 first, d2 is present (as it was bulk
 
1305
        # copied), so we will try to delta, but d2 is not currently able to be
 
1306
        # extracted because it's basis d1 is not present. Topologically sorting
 
1307
        # addresses this. The following generates a sort for all the texts that
 
1308
        # are being inserted without having to reference the entire text key
 
1309
        # space (we only topo sort the revisions, which is smaller).
 
1310
        topo_order = tsort.topo_sort(ancestors)
 
1311
        rev_order = dict(zip(topo_order, range(len(topo_order))))
 
1312
        bad_texts.sort(key=lambda key:rev_order.get(key[0][1], 0))
 
1313
        transaction = repo.get_transaction()
 
1314
        file_id_index = GraphIndexPrefixAdapter(
 
1315
            self.new_pack.text_index,
 
1316
            ('blank', ), 1,
 
1317
            add_nodes_callback=self.new_pack.text_index.add_nodes)
 
1318
        data_access = _DirectPackAccess(
 
1319
                {self.new_pack.text_index:self.new_pack.access_tuple()})
 
1320
        data_access.set_writer(self.new_pack._writer, self.new_pack.text_index,
 
1321
            self.new_pack.access_tuple())
 
1322
        output_texts = KnitVersionedFiles(
 
1323
            _KnitGraphIndex(self.new_pack.text_index,
 
1324
                add_callback=self.new_pack.text_index.add_nodes,
 
1325
                deltas=True, parents=True, is_locked=repo.is_locked),
 
1326
            data_access=data_access, max_delta_chain=200)
 
1327
        for key, parent_keys in bad_texts:
 
1328
            # We refer to the new pack to delta data being output.
 
1329
            # A possible improvement would be to catch errors on short reads
 
1330
            # and only flush then.
 
1331
            self.new_pack.flush()
 
1332
            parents = []
 
1333
            for parent_key in parent_keys:
 
1334
                if parent_key[0] != key[0]:
 
1335
                    # Graph parents must match the fileid
 
1336
                    raise errors.BzrError('Mismatched key parent %r:%r' %
 
1337
                        (key, parent_keys))
 
1338
                parents.append(parent_key[1])
 
1339
            text_lines = osutils.split_lines(repo.texts.get_record_stream(
 
1340
                [key], 'unordered', True).next().get_bytes_as('fulltext'))
 
1341
            output_texts.add_lines(key, parent_keys, text_lines,
 
1342
                random_id=True, check_content=False)
 
1343
        # 5) check that nothing inserted has a reference outside the keyspace.
 
1344
        missing_text_keys = self.new_pack.text_index._external_references()
 
1345
        if missing_text_keys:
 
1346
            raise errors.BzrCheckError('Reference to missing compression parents %r'
 
1347
                % (missing_text_keys,))
 
1348
        self._log_copied_texts()
 
1349
 
 
1350
    def _use_pack(self, new_pack):
 
1351
        """Override _use_pack to check for reconcile having changed content."""
 
1352
        # XXX: we might be better checking this at the copy time.
 
1353
        original_inventory_keys = set()
 
1354
        inv_index = self._pack_collection.inventory_index.combined_index
 
1355
        for entry in inv_index.iter_all_entries():
 
1356
            original_inventory_keys.add(entry[1])
 
1357
        new_inventory_keys = set()
 
1358
        for entry in new_pack.inventory_index.iter_all_entries():
 
1359
            new_inventory_keys.add(entry[1])
 
1360
        if new_inventory_keys != original_inventory_keys:
 
1361
            self._data_changed = True
 
1362
        return new_pack.data_inserted() and self._data_changed
 
1363
 
 
1364
 
759
1365
class RepositoryPackCollection(object):
760
1366
    """Management of packs within a repository.
761
1367
 
762
1368
    :ivar _names: map of {pack_name: (index_size,)}
763
1369
    """
764
1370
 
765
 
    pack_factory = None
766
 
    resumed_pack_factory = None
767
 
    normal_packer_class = None
768
 
    optimising_packer_class = None
 
1371
    pack_factory = NewPack
 
1372
    resumed_pack_factory = ResumedPack
769
1373
 
770
1374
    def __init__(self, repo, transport, index_transport, upload_transport,
771
1375
                 pack_transport, index_builder_class, index_class,
806
1410
        self.inventory_index = AggregateIndex(self.reload_pack_names, flush)
807
1411
        self.text_index = AggregateIndex(self.reload_pack_names, flush)
808
1412
        self.signature_index = AggregateIndex(self.reload_pack_names, flush)
809
 
        all_indices = [self.revision_index, self.inventory_index,
810
 
                self.text_index, self.signature_index]
811
1413
        if use_chk_index:
812
1414
            self.chk_index = AggregateIndex(self.reload_pack_names, flush)
813
 
            all_indices.append(self.chk_index)
814
1415
        else:
815
1416
            # used to determine if we're using a chk_index elsewhere.
816
1417
            self.chk_index = None
817
 
        # Tell all the CombinedGraphIndex objects about each other, so they can
818
 
        # share hints about which pack names to search first.
819
 
        all_combined = [agg_idx.combined_index for agg_idx in all_indices]
820
 
        for combined_idx in all_combined:
821
 
            combined_idx.set_sibling_indices(
822
 
                set(all_combined).difference([combined_idx]))
823
1418
        # resumed packs
824
1419
        self._resumed_packs = []
825
1420
 
826
 
    def __repr__(self):
827
 
        return '%s(%r)' % (self.__class__.__name__, self.repo)
828
 
 
829
1421
    def add_pack_to_memory(self, pack):
830
1422
        """Make a Pack object available to the repository to satisfy queries.
831
1423
 
912
1504
            'containing %d revisions. Packing %d files into %d affecting %d'
913
1505
            ' revisions', self, total_packs, total_revisions, num_old_packs,
914
1506
            num_new_packs, num_revs_affected)
915
 
        result = self._execute_pack_operations(pack_operations, packer_class=self.normal_packer_class,
 
1507
        result = self._execute_pack_operations(pack_operations,
916
1508
                                      reload_func=self._restart_autopack)
917
1509
        mutter('Auto-packing repository %s completed', self)
918
1510
        return result
919
1511
 
920
 
    def _execute_pack_operations(self, pack_operations, packer_class,
921
 
            reload_func=None):
 
1512
    def _execute_pack_operations(self, pack_operations, _packer_class=Packer,
 
1513
                                 reload_func=None):
922
1514
        """Execute a series of pack operations.
923
1515
 
924
1516
        :param pack_operations: A list of [revision_count, packs_to_combine].
925
 
        :param packer_class: The class of packer to use
 
1517
        :param _packer_class: The class of packer to use (default: Packer).
926
1518
        :return: The new pack names.
927
1519
        """
928
1520
        for revision_count, packs in pack_operations:
929
1521
            # we may have no-ops from the setup logic
930
1522
            if len(packs) == 0:
931
1523
                continue
932
 
            packer = packer_class(self, packs, '.autopack',
 
1524
            packer = _packer_class(self, packs, '.autopack',
933
1525
                                   reload_func=reload_func)
934
1526
            try:
935
 
                result = packer.pack()
 
1527
                packer.pack()
936
1528
            except errors.RetryWithNewPacks:
937
1529
                # An exception is propagating out of this context, make sure
938
1530
                # this packer has cleaned up. Packer() doesn't set its new_pack
941
1533
                if packer.new_pack is not None:
942
1534
                    packer.new_pack.abort()
943
1535
                raise
944
 
            if result is None:
945
 
                return
946
1536
            for pack in packs:
947
1537
                self._remove_pack_from_memory(pack)
948
1538
        # record the newly available packs and stop advertising the old
949
1539
        # packs
950
 
        to_be_obsoleted = []
951
 
        for _, packs in pack_operations:
952
 
            to_be_obsoleted.extend(packs)
953
 
        result = self._save_pack_names(clear_obsolete_packs=True,
954
 
                                       obsolete_packs=to_be_obsoleted)
 
1540
        result = self._save_pack_names(clear_obsolete_packs=True)
 
1541
        # Move the old packs out of the way now they are no longer referenced.
 
1542
        for revision_count, packs in pack_operations:
 
1543
            self._obsolete_packs(packs)
955
1544
        return result
956
1545
 
957
1546
    def _flush_new_pack(self):
970
1559
        """Is the collection already packed?"""
971
1560
        return not (self.repo._format.pack_compresses or (len(self._names) > 1))
972
1561
 
973
 
    def pack(self, hint=None, clean_obsolete_packs=False):
 
1562
    def pack(self, hint=None):
974
1563
        """Pack the pack collection totally."""
975
1564
        self.ensure_loaded()
976
1565
        total_packs = len(self._names)
982
1571
        mutter('Packing repository %s, which has %d pack files, '
983
1572
            'containing %d revisions with hint %r.', self, total_packs,
984
1573
            total_revisions, hint)
985
 
        while True:
986
 
            try:
987
 
                self._try_pack_operations(hint)
988
 
            except RetryPackOperations:
989
 
                continue
990
 
            break
991
 
 
992
 
        if clean_obsolete_packs:
993
 
            self._clear_obsolete_packs()
994
 
 
995
 
    def _try_pack_operations(self, hint):
996
 
        """Calculate the pack operations based on the hint (if any), and
997
 
        execute them.
998
 
        """
999
1574
        # determine which packs need changing
1000
1575
        pack_operations = [[0, []]]
1001
1576
        for pack in self.all_packs():
1002
1577
            if hint is None or pack.name in hint:
1003
 
                # Either no hint was provided (so we are packing everything),
1004
 
                # or this pack was included in the hint.
1005
1578
                pack_operations[-1][0] += pack.get_revision_count()
1006
1579
                pack_operations[-1][1].append(pack)
1007
 
        self._execute_pack_operations(pack_operations,
1008
 
            packer_class=self.optimising_packer_class,
1009
 
            reload_func=self._restart_pack_operations)
 
1580
        self._execute_pack_operations(pack_operations, OptimisingPacker)
1010
1581
 
1011
1582
    def plan_autopack_combinations(self, existing_packs, pack_distribution):
1012
1583
        """Plan a pack operation.
1022
1593
        pack_operations = [[0, []]]
1023
1594
        # plan out what packs to keep, and what to reorganise
1024
1595
        while len(existing_packs):
1025
 
            # take the largest pack, and if it's less than the head of the
 
1596
            # take the largest pack, and if its less than the head of the
1026
1597
            # distribution chart we will include its contents in the new pack
1027
 
            # for that position. If it's larger, we remove its size from the
 
1598
            # for that position. If its larger, we remove its size from the
1028
1599
            # distribution chart
1029
1600
            next_pack_rev_count, next_pack = existing_packs.pop(0)
1030
1601
            if next_pack_rev_count >= pack_distribution[0]:
1065
1636
 
1066
1637
        :return: True if the disk names had not been previously read.
1067
1638
        """
1068
 
        # NB: if you see an assertion error here, it's probably access against
 
1639
        # NB: if you see an assertion error here, its probably access against
1069
1640
        # an unlocked repo. Naughty.
1070
1641
        if not self.repo.is_locked():
1071
1642
            raise errors.ObjectNotLocked(self.repo)
1101
1672
            txt_index = self._make_index(name, '.tix')
1102
1673
            sig_index = self._make_index(name, '.six')
1103
1674
            if self.chk_index is not None:
1104
 
                chk_index = self._make_index(name, '.cix', is_chk=True)
 
1675
                chk_index = self._make_index(name, '.cix')
1105
1676
            else:
1106
1677
                chk_index = None
1107
1678
            result = ExistingPack(self._pack_transport, name, rev_index,
1126
1697
            txt_index = self._make_index(name, '.tix', resume=True)
1127
1698
            sig_index = self._make_index(name, '.six', resume=True)
1128
1699
            if self.chk_index is not None:
1129
 
                chk_index = self._make_index(name, '.cix', resume=True,
1130
 
                                             is_chk=True)
 
1700
                chk_index = self._make_index(name, '.cix', resume=True)
1131
1701
            else:
1132
1702
                chk_index = None
1133
1703
            result = self.resumed_pack_factory(name, rev_index, inv_index,
1163
1733
        return self._index_class(self.transport, 'pack-names', None
1164
1734
                ).iter_all_entries()
1165
1735
 
1166
 
    def _make_index(self, name, suffix, resume=False, is_chk=False):
 
1736
    def _make_index(self, name, suffix, resume=False):
1167
1737
        size_offset = self._suffix_offsets[suffix]
1168
1738
        index_name = name + suffix
1169
1739
        if resume:
1172
1742
        else:
1173
1743
            transport = self._index_transport
1174
1744
            index_size = self._names[name][size_offset]
1175
 
        index = self._index_class(transport, index_name, index_size,
1176
 
                                  unlimited_cache=is_chk)
1177
 
        if is_chk and self._index_class is btree_index.BTreeGraphIndex: 
1178
 
            index._leaf_factory = btree_index._gcchk_factory
1179
 
        return index
 
1745
        return self._index_class(transport, index_name, index_size)
1180
1746
 
1181
1747
    def _max_pack_count(self, total_revisions):
1182
1748
        """Return the maximum number of packs to use for total revisions.
1210
1776
        :param return: None.
1211
1777
        """
1212
1778
        for pack in packs:
1213
 
            try:
1214
 
                pack.pack_transport.move(pack.file_name(),
1215
 
                    '../obsolete_packs/' + pack.file_name())
1216
 
            except (errors.PathError, errors.TransportError), e:
1217
 
                # TODO: Should these be warnings or mutters?
1218
 
                mutter("couldn't rename obsolete pack, skipping it:\n%s"
1219
 
                       % (e,))
 
1779
            pack.pack_transport.rename(pack.file_name(),
 
1780
                '../obsolete_packs/' + pack.file_name())
1220
1781
            # TODO: Probably needs to know all possible indices for this pack
1221
1782
            # - or maybe list the directory and move all indices matching this
1222
1783
            # name whether we recognize it or not?
1224
1785
            if self.chk_index is not None:
1225
1786
                suffixes.append('.cix')
1226
1787
            for suffix in suffixes:
1227
 
                try:
1228
 
                    self._index_transport.move(pack.name + suffix,
1229
 
                        '../obsolete_packs/' + pack.name + suffix)
1230
 
                except (errors.PathError, errors.TransportError), e:
1231
 
                    mutter("couldn't rename obsolete index, skipping it:\n%s"
1232
 
                           % (e,))
 
1788
                self._index_transport.rename(pack.name + suffix,
 
1789
                    '../obsolete_packs/' + pack.name + suffix)
1233
1790
 
1234
1791
    def pack_distribution(self, total_revisions):
1235
1792
        """Generate a list of the number of revisions to put in each pack.
1261
1818
        self._remove_pack_indices(pack)
1262
1819
        self.packs.remove(pack)
1263
1820
 
1264
 
    def _remove_pack_indices(self, pack, ignore_missing=False):
1265
 
        """Remove the indices for pack from the aggregated indices.
1266
 
        
1267
 
        :param ignore_missing: Suppress KeyErrors from calling remove_index.
1268
 
        """
1269
 
        for index_type in Pack.index_definitions.keys():
1270
 
            attr_name = index_type + '_index'
1271
 
            aggregate_index = getattr(self, attr_name)
1272
 
            if aggregate_index is not None:
1273
 
                pack_index = getattr(pack, attr_name)
1274
 
                try:
1275
 
                    aggregate_index.remove_index(pack_index)
1276
 
                except KeyError:
1277
 
                    if ignore_missing:
1278
 
                        continue
1279
 
                    raise
 
1821
    def _remove_pack_indices(self, pack):
 
1822
        """Remove the indices for pack from the aggregated indices."""
 
1823
        self.revision_index.remove_index(pack.revision_index, pack)
 
1824
        self.inventory_index.remove_index(pack.inventory_index, pack)
 
1825
        self.text_index.remove_index(pack.text_index, pack)
 
1826
        self.signature_index.remove_index(pack.signature_index, pack)
 
1827
        if self.chk_index is not None:
 
1828
            self.chk_index.remove_index(pack.chk_index, pack)
1280
1829
 
1281
1830
    def reset(self):
1282
1831
        """Clear all cached data."""
1315
1864
        disk_nodes = set()
1316
1865
        for index, key, value in self._iter_disk_pack_index():
1317
1866
            disk_nodes.add((key, value))
1318
 
        orig_disk_nodes = set(disk_nodes)
1319
1867
 
1320
1868
        # do a two-way diff against our original content
1321
1869
        current_nodes = set()
1334
1882
        disk_nodes.difference_update(deleted_nodes)
1335
1883
        disk_nodes.update(new_nodes)
1336
1884
 
1337
 
        return disk_nodes, deleted_nodes, new_nodes, orig_disk_nodes
 
1885
        return disk_nodes, deleted_nodes, new_nodes
1338
1886
 
1339
1887
    def _syncronize_pack_names_from_disk_nodes(self, disk_nodes):
1340
1888
        """Given the correct set of pack files, update our saved info.
1368
1916
                    # disk index because the set values are the same, unless
1369
1917
                    # the only index shows up as deleted by the set difference
1370
1918
                    # - which it may. Until there is a specific test for this,
1371
 
                    # assume it's broken. RBC 20071017.
 
1919
                    # assume its broken. RBC 20071017.
1372
1920
                    self._remove_pack_from_memory(self.get_pack_by_name(name))
1373
1921
                    self._names[name] = sizes
1374
1922
                    self.get_pack_by_name(name)
1380
1928
                added.append(name)
1381
1929
        return removed, added, modified
1382
1930
 
1383
 
    def _save_pack_names(self, clear_obsolete_packs=False, obsolete_packs=None):
 
1931
    def _save_pack_names(self, clear_obsolete_packs=False):
1384
1932
        """Save the list of packs.
1385
1933
 
1386
1934
        This will take out the mutex around the pack names list for the
1390
1938
 
1391
1939
        :param clear_obsolete_packs: If True, clear out the contents of the
1392
1940
            obsolete_packs directory.
1393
 
        :param obsolete_packs: Packs that are obsolete once the new pack-names
1394
 
            file has been written.
1395
1941
        :return: A list of the names saved that were not previously on disk.
1396
1942
        """
1397
 
        already_obsolete = []
1398
1943
        self.lock_names()
1399
1944
        try:
1400
1945
            builder = self._index_builder_class()
1401
 
            (disk_nodes, deleted_nodes, new_nodes,
1402
 
             orig_disk_nodes) = self._diff_pack_names()
 
1946
            disk_nodes, deleted_nodes, new_nodes = self._diff_pack_names()
1403
1947
            # TODO: handle same-name, index-size-changes here -
1404
1948
            # e.g. use the value from disk, not ours, *unless* we're the one
1405
1949
            # changing it.
1407
1951
                builder.add_node(key, value)
1408
1952
            self.transport.put_file('pack-names', builder.finish(),
1409
1953
                mode=self.repo.bzrdir._get_file_mode())
 
1954
            # move the baseline forward
1410
1955
            self._packs_at_load = disk_nodes
1411
1956
            if clear_obsolete_packs:
1412
 
                to_preserve = None
1413
 
                if obsolete_packs:
1414
 
                    to_preserve = set([o.name for o in obsolete_packs])
1415
 
                already_obsolete = self._clear_obsolete_packs(to_preserve)
 
1957
                self._clear_obsolete_packs()
1416
1958
        finally:
1417
1959
            self._unlock_names()
1418
1960
        # synchronise the memory packs list with what we just wrote:
1419
1961
        self._syncronize_pack_names_from_disk_nodes(disk_nodes)
1420
 
        if obsolete_packs:
1421
 
            # TODO: We could add one more condition here. "if o.name not in
1422
 
            #       orig_disk_nodes and o != the new_pack we haven't written to
1423
 
            #       disk yet. However, the new pack object is not easily
1424
 
            #       accessible here (it would have to be passed through the
1425
 
            #       autopacking code, etc.)
1426
 
            obsolete_packs = [o for o in obsolete_packs
1427
 
                              if o.name not in already_obsolete]
1428
 
            self._obsolete_packs(obsolete_packs)
1429
1962
        return [new_node[0][0] for new_node in new_nodes]
1430
1963
 
1431
1964
    def reload_pack_names(self):
1439
1972
        """
1440
1973
        # The ensure_loaded call is to handle the case where the first call
1441
1974
        # made involving the collection was to reload_pack_names, where we 
1442
 
        # don't have a view of disk contents. It's a bit of a bandaid, and
1443
 
        # causes two reads of pack-names, but it's a rare corner case not
1444
 
        # struck with regular push/pull etc.
 
1975
        # don't have a view of disk contents. Its a bit of a bandaid, and
 
1976
        # causes two reads of pack-names, but its a rare corner case not struck
 
1977
        # with regular push/pull etc.
1445
1978
        first_read = self.ensure_loaded()
1446
1979
        if first_read:
1447
1980
            return True
1448
1981
        # out the new value.
1449
 
        (disk_nodes, deleted_nodes, new_nodes,
1450
 
         orig_disk_nodes) = self._diff_pack_names()
1451
 
        # _packs_at_load is meant to be the explicit list of names in
1452
 
        # 'pack-names' at then start. As such, it should not contain any
1453
 
        # pending names that haven't been written out yet.
1454
 
        self._packs_at_load = orig_disk_nodes
 
1982
        disk_nodes, _, _ = self._diff_pack_names()
 
1983
        self._packs_at_load = disk_nodes
1455
1984
        (removed, added,
1456
1985
         modified) = self._syncronize_pack_names_from_disk_nodes(disk_nodes)
1457
1986
        if removed or added or modified:
1466
1995
            raise
1467
1996
        raise errors.RetryAutopack(self.repo, False, sys.exc_info())
1468
1997
 
1469
 
    def _restart_pack_operations(self):
1470
 
        """Reload the pack names list, and restart the autopack code."""
1471
 
        if not self.reload_pack_names():
1472
 
            # Re-raise the original exception, because something went missing
1473
 
            # and a restart didn't find it
1474
 
            raise
1475
 
        raise RetryPackOperations(self.repo, False, sys.exc_info())
1476
 
 
1477
 
    def _clear_obsolete_packs(self, preserve=None):
 
1998
    def _clear_obsolete_packs(self):
1478
1999
        """Delete everything from the obsolete-packs directory.
1479
 
 
1480
 
        :return: A list of pack identifiers (the filename without '.pack') that
1481
 
            were found in obsolete_packs.
1482
2000
        """
1483
 
        found = []
1484
2001
        obsolete_pack_transport = self.transport.clone('obsolete_packs')
1485
 
        if preserve is None:
1486
 
            preserve = set()
1487
2002
        for filename in obsolete_pack_transport.list_dir('.'):
1488
 
            name, ext = osutils.splitext(filename)
1489
 
            if ext == '.pack':
1490
 
                found.append(name)
1491
 
            if name in preserve:
1492
 
                continue
1493
2003
            try:
1494
2004
                obsolete_pack_transport.delete(filename)
1495
2005
            except (errors.PathError, errors.TransportError), e:
1496
 
                warning("couldn't delete obsolete pack, skipping it:\n%s"
1497
 
                        % (e,))
1498
 
        return found
 
2006
                warning("couldn't delete obsolete pack, skipping it:\n%s" % (e,))
1499
2007
 
1500
2008
    def _start_write_group(self):
1501
2009
        # Do not permit preparation for writing if we're not in a 'write lock'.
1528
2036
        # FIXME: just drop the transient index.
1529
2037
        # forget what names there are
1530
2038
        if self._new_pack is not None:
1531
 
            operation = cleanup.OperationWithCleanups(self._new_pack.abort)
1532
 
            operation.add_cleanup(setattr, self, '_new_pack', None)
1533
 
            # If we aborted while in the middle of finishing the write
1534
 
            # group, _remove_pack_indices could fail because the indexes are
1535
 
            # already gone.  But they're not there we shouldn't fail in this
1536
 
            # case, so we pass ignore_missing=True.
1537
 
            operation.add_cleanup(self._remove_pack_indices, self._new_pack,
1538
 
                ignore_missing=True)
1539
 
            operation.run_simple()
 
2039
            try:
 
2040
                self._new_pack.abort()
 
2041
            finally:
 
2042
                # XXX: If we aborted while in the middle of finishing the write
 
2043
                # group, _remove_pack_indices can fail because the indexes are
 
2044
                # already gone.  If they're not there we shouldn't fail in this
 
2045
                # case.  -- mbp 20081113
 
2046
                self._remove_pack_indices(self._new_pack)
 
2047
                self._new_pack = None
1540
2048
        for resumed_pack in self._resumed_packs:
1541
 
            operation = cleanup.OperationWithCleanups(resumed_pack.abort)
1542
 
            # See comment in previous finally block.
1543
 
            operation.add_cleanup(self._remove_pack_indices, resumed_pack,
1544
 
                ignore_missing=True)
1545
 
            operation.run_simple()
 
2049
            try:
 
2050
                resumed_pack.abort()
 
2051
            finally:
 
2052
                # See comment in previous finally block.
 
2053
                try:
 
2054
                    self._remove_pack_indices(resumed_pack)
 
2055
                except KeyError:
 
2056
                    pass
1546
2057
        del self._resumed_packs[:]
1547
2058
 
1548
2059
    def _remove_resumed_pack_indices(self):
1550
2061
            self._remove_pack_indices(resumed_pack)
1551
2062
        del self._resumed_packs[:]
1552
2063
 
1553
 
    def _check_new_inventories(self):
1554
 
        """Detect missing inventories in this write group.
1555
 
 
1556
 
        :returns: list of strs, summarising any problems found.  If the list is
1557
 
            empty no problems were found.
1558
 
        """
1559
 
        # The base implementation does no checks.  GCRepositoryPackCollection
1560
 
        # overrides this.
1561
 
        return []
1562
 
        
1563
2064
    def _commit_write_group(self):
1564
2065
        all_missing = set()
1565
2066
        for prefix, versioned_file in (
1574
2075
            raise errors.BzrCheckError(
1575
2076
                "Repository %s has missing compression parent(s) %r "
1576
2077
                 % (self.repo, sorted(all_missing)))
1577
 
        problems = self._check_new_inventories()
1578
 
        if problems:
1579
 
            problems_summary = '\n'.join(problems)
1580
 
            raise errors.BzrCheckError(
1581
 
                "Cannot add revision(s) to repository: " + problems_summary)
1582
2078
        self._remove_pack_indices(self._new_pack)
1583
 
        any_new_content = False
 
2079
        should_autopack = False
1584
2080
        if self._new_pack.data_inserted():
1585
2081
            # get all the data to disk and read to use
1586
2082
            self._new_pack.finish()
1587
2083
            self.allocate(self._new_pack)
1588
2084
            self._new_pack = None
1589
 
            any_new_content = True
 
2085
            should_autopack = True
1590
2086
        else:
1591
2087
            self._new_pack.abort()
1592
2088
            self._new_pack = None
1597
2093
            self._remove_pack_from_memory(resumed_pack)
1598
2094
            resumed_pack.finish()
1599
2095
            self.allocate(resumed_pack)
1600
 
            any_new_content = True
 
2096
            should_autopack = True
1601
2097
        del self._resumed_packs[:]
1602
 
        if any_new_content:
1603
 
            result = self.autopack()
1604
 
            if not result:
 
2098
        if should_autopack:
 
2099
            if not self.autopack():
1605
2100
                # when autopack takes no steps, the names list is still
1606
2101
                # unsaved.
1607
2102
                return self._save_pack_names()
1608
 
            return result
1609
2103
        return []
1610
2104
 
1611
2105
    def _suspend_write_group(self):
1627
2121
            self._resume_pack(token)
1628
2122
 
1629
2123
 
1630
 
class PackRepository(MetaDirVersionedFileRepository):
 
2124
class KnitPackRepository(KnitRepository):
1631
2125
    """Repository with knit objects stored inside pack containers.
1632
2126
 
1633
2127
    The layering for a KnitPackRepository is:
1636
2130
    ===================================================
1637
2131
    Tuple based apis below, string based, and key based apis above
1638
2132
    ---------------------------------------------------
1639
 
    VersionedFiles
 
2133
    KnitVersionedFiles
1640
2134
      Provides .texts, .revisions etc
1641
2135
      This adapts the N-tuple keys to physical knit records which only have a
1642
2136
      single string identifier (for historical reasons), which in older formats
1652
2146
 
1653
2147
    """
1654
2148
 
1655
 
    # These attributes are inherited from the Repository base class. Setting
1656
 
    # them to None ensures that if the constructor is changed to not initialize
1657
 
    # them, or a subclass fails to call the constructor, that an error will
1658
 
    # occur rather than the system working but generating incorrect data.
1659
 
    _commit_builder_class = None
1660
 
    _serializer = None
1661
 
 
1662
2149
    def __init__(self, _format, a_bzrdir, control_files, _commit_builder_class,
1663
2150
        _serializer):
1664
 
        MetaDirRepository.__init__(self, _format, a_bzrdir, control_files)
1665
 
        self._commit_builder_class = _commit_builder_class
1666
 
        self._serializer = _serializer
 
2151
        KnitRepository.__init__(self, _format, a_bzrdir, control_files,
 
2152
            _commit_builder_class, _serializer)
 
2153
        index_transport = self._transport.clone('indices')
 
2154
        self._pack_collection = RepositoryPackCollection(self, self._transport,
 
2155
            index_transport,
 
2156
            self._transport.clone('upload'),
 
2157
            self._transport.clone('packs'),
 
2158
            _format.index_builder_class,
 
2159
            _format.index_class,
 
2160
            use_chk_index=self._format.supports_chks,
 
2161
            )
 
2162
        self.inventories = KnitVersionedFiles(
 
2163
            _KnitGraphIndex(self._pack_collection.inventory_index.combined_index,
 
2164
                add_callback=self._pack_collection.inventory_index.add_callback,
 
2165
                deltas=True, parents=True, is_locked=self.is_locked),
 
2166
            data_access=self._pack_collection.inventory_index.data_access,
 
2167
            max_delta_chain=200)
 
2168
        self.revisions = KnitVersionedFiles(
 
2169
            _KnitGraphIndex(self._pack_collection.revision_index.combined_index,
 
2170
                add_callback=self._pack_collection.revision_index.add_callback,
 
2171
                deltas=False, parents=True, is_locked=self.is_locked,
 
2172
                track_external_parent_refs=True),
 
2173
            data_access=self._pack_collection.revision_index.data_access,
 
2174
            max_delta_chain=0)
 
2175
        self.signatures = KnitVersionedFiles(
 
2176
            _KnitGraphIndex(self._pack_collection.signature_index.combined_index,
 
2177
                add_callback=self._pack_collection.signature_index.add_callback,
 
2178
                deltas=False, parents=False, is_locked=self.is_locked),
 
2179
            data_access=self._pack_collection.signature_index.data_access,
 
2180
            max_delta_chain=0)
 
2181
        self.texts = KnitVersionedFiles(
 
2182
            _KnitGraphIndex(self._pack_collection.text_index.combined_index,
 
2183
                add_callback=self._pack_collection.text_index.add_callback,
 
2184
                deltas=True, parents=True, is_locked=self.is_locked),
 
2185
            data_access=self._pack_collection.text_index.data_access,
 
2186
            max_delta_chain=200)
 
2187
        if _format.supports_chks:
 
2188
            # No graph, no compression:- references from chks are between
 
2189
            # different objects not temporal versions of the same; and without
 
2190
            # some sort of temporal structure knit compression will just fail.
 
2191
            self.chk_bytes = KnitVersionedFiles(
 
2192
                _KnitGraphIndex(self._pack_collection.chk_index.combined_index,
 
2193
                    add_callback=self._pack_collection.chk_index.add_callback,
 
2194
                    deltas=False, parents=False, is_locked=self.is_locked),
 
2195
                data_access=self._pack_collection.chk_index.data_access,
 
2196
                max_delta_chain=0)
 
2197
        else:
 
2198
            self.chk_bytes = None
 
2199
        # True when the repository object is 'write locked' (as opposed to the
 
2200
        # physical lock only taken out around changes to the pack-names list.)
 
2201
        # Another way to represent this would be a decorator around the control
 
2202
        # files object that presents logical locks as physical ones - if this
 
2203
        # gets ugly consider that alternative design. RBC 20071011
 
2204
        self._write_lock_count = 0
 
2205
        self._transaction = None
 
2206
        # for tests
 
2207
        self._reconcile_does_inventory_gc = True
1667
2208
        self._reconcile_fixes_text_parents = True
1668
 
        if self._format.supports_external_lookups:
1669
 
            self._unstacked_provider = graph.CachingParentsProvider(
1670
 
                self._make_parents_provider_unstacked())
1671
 
        else:
1672
 
            self._unstacked_provider = graph.CachingParentsProvider(self)
1673
 
        self._unstacked_provider.disable_cache()
 
2209
        self._reconcile_backsup_inventory = False
1674
2210
 
1675
 
    @needs_read_lock
1676
 
    def _all_revision_ids(self):
1677
 
        """See Repository.all_revision_ids()."""
1678
 
        return [key[0] for key in self.revisions.keys()]
 
2211
    def _warn_if_deprecated(self):
 
2212
        # This class isn't deprecated, but one sub-format is
 
2213
        if isinstance(self._format, RepositoryFormatKnitPack5RichRootBroken):
 
2214
            from bzrlib import repository
 
2215
            if repository._deprecation_warning_done:
 
2216
                return
 
2217
            repository._deprecation_warning_done = True
 
2218
            warning("Format %s for %s is deprecated - please use"
 
2219
                    " 'bzr upgrade --1.6.1-rich-root'"
 
2220
                    % (self._format, self.bzrdir.transport.base))
1679
2221
 
1680
2222
    def _abort_write_group(self):
1681
 
        self.revisions._index._key_dependencies.clear()
 
2223
        self.revisions._index._key_dependencies.refs.clear()
1682
2224
        self._pack_collection._abort_write_group()
1683
2225
 
 
2226
    def _find_inconsistent_revision_parents(self):
 
2227
        """Find revisions with incorrectly cached parents.
 
2228
 
 
2229
        :returns: an iterator yielding tuples of (revison-id, parents-in-index,
 
2230
            parents-in-revision).
 
2231
        """
 
2232
        if not self.is_locked():
 
2233
            raise errors.ObjectNotLocked(self)
 
2234
        pb = ui.ui_factory.nested_progress_bar()
 
2235
        result = []
 
2236
        try:
 
2237
            revision_nodes = self._pack_collection.revision_index \
 
2238
                .combined_index.iter_all_entries()
 
2239
            index_positions = []
 
2240
            # Get the cached index values for all revisions, and also the
 
2241
            # location in each index of the revision text so we can perform
 
2242
            # linear IO.
 
2243
            for index, key, value, refs in revision_nodes:
 
2244
                node = (index, key, value, refs)
 
2245
                index_memo = self.revisions._index._node_to_position(node)
 
2246
                if index_memo[0] != index:
 
2247
                    raise AssertionError('%r != %r' % (index_memo[0], index))
 
2248
                index_positions.append((index_memo, key[0],
 
2249
                                       tuple(parent[0] for parent in refs[0])))
 
2250
                pb.update("Reading revision index", 0, 0)
 
2251
            index_positions.sort()
 
2252
            batch_size = 1000
 
2253
            pb.update("Checking cached revision graph", 0,
 
2254
                      len(index_positions))
 
2255
            for offset in xrange(0, len(index_positions), 1000):
 
2256
                pb.update("Checking cached revision graph", offset)
 
2257
                to_query = index_positions[offset:offset + batch_size]
 
2258
                if not to_query:
 
2259
                    break
 
2260
                rev_ids = [item[1] for item in to_query]
 
2261
                revs = self.get_revisions(rev_ids)
 
2262
                for revision, item in zip(revs, to_query):
 
2263
                    index_parents = item[2]
 
2264
                    rev_parents = tuple(revision.parent_ids)
 
2265
                    if index_parents != rev_parents:
 
2266
                        result.append((revision.revision_id, index_parents,
 
2267
                                       rev_parents))
 
2268
        finally:
 
2269
            pb.finished()
 
2270
        return result
 
2271
 
 
2272
    def _get_source(self, to_format):
 
2273
        if to_format.network_name() == self._format.network_name():
 
2274
            return KnitPackStreamSource(self, to_format)
 
2275
        return super(KnitPackRepository, self)._get_source(to_format)
 
2276
 
1684
2277
    def _make_parents_provider(self):
1685
 
        if not self._format.supports_external_lookups:
1686
 
            return self._unstacked_provider
1687
 
        return graph.StackedParentsProvider(_LazyListJoin(
1688
 
            [self._unstacked_provider], self._fallback_repositories))
 
2278
        return graph.CachingParentsProvider(self)
1689
2279
 
1690
2280
    def _refresh_data(self):
1691
2281
        if not self.is_locked():
1692
2282
            return
1693
2283
        self._pack_collection.reload_pack_names()
1694
 
        self._unstacked_provider.disable_cache()
1695
 
        self._unstacked_provider.enable_cache()
1696
2284
 
1697
2285
    def _start_write_group(self):
1698
2286
        self._pack_collection._start_write_group()
1699
2287
 
1700
2288
    def _commit_write_group(self):
1701
 
        hint = self._pack_collection._commit_write_group()
1702
 
        self.revisions._index._key_dependencies.clear()
1703
 
        # The commit may have added keys that were previously cached as
1704
 
        # missing, so reset the cache.
1705
 
        self._unstacked_provider.disable_cache()
1706
 
        self._unstacked_provider.enable_cache()
1707
 
        return hint
 
2289
        self.revisions._index._key_dependencies.refs.clear()
 
2290
        return self._pack_collection._commit_write_group()
1708
2291
 
1709
2292
    def suspend_write_group(self):
1710
2293
        # XXX check self._write_group is self.get_transaction()?
1711
2294
        tokens = self._pack_collection._suspend_write_group()
1712
 
        self.revisions._index._key_dependencies.clear()
 
2295
        self.revisions._index._key_dependencies.refs.clear()
1713
2296
        self._write_group = None
1714
2297
        return tokens
1715
2298
 
1736
2319
        return self._write_lock_count
1737
2320
 
1738
2321
    def lock_write(self, token=None):
1739
 
        """Lock the repository for writes.
1740
 
 
1741
 
        :return: A bzrlib.repository.RepositoryWriteLockResult.
1742
 
        """
1743
2322
        locked = self.is_locked()
1744
2323
        if not self._write_lock_count and locked:
1745
2324
            raise errors.ReadOnlyError(self)
1747
2326
        if self._write_lock_count == 1:
1748
2327
            self._transaction = transactions.WriteTransaction()
1749
2328
        if not locked:
1750
 
            if 'relock' in debug.debug_flags and self._prev_lock == 'w':
1751
 
                note('%r was write locked again', self)
1752
 
            self._prev_lock = 'w'
1753
 
            self._unstacked_provider.enable_cache()
1754
2329
            for repo in self._fallback_repositories:
1755
2330
                # Writes don't affect fallback repos
1756
2331
                repo.lock_read()
1757
2332
            self._refresh_data()
1758
 
        return RepositoryWriteLockResult(self.unlock, None)
1759
2333
 
1760
2334
    def lock_read(self):
1761
 
        """Lock the repository for reads.
1762
 
 
1763
 
        :return: A bzrlib.lock.LogicalLockResult.
1764
 
        """
1765
2335
        locked = self.is_locked()
1766
2336
        if self._write_lock_count:
1767
2337
            self._write_lock_count += 1
1768
2338
        else:
1769
2339
            self.control_files.lock_read()
1770
2340
        if not locked:
1771
 
            if 'relock' in debug.debug_flags and self._prev_lock == 'r':
1772
 
                note('%r was read locked again', self)
1773
 
            self._prev_lock = 'r'
1774
 
            self._unstacked_provider.enable_cache()
1775
2341
            for repo in self._fallback_repositories:
1776
2342
                repo.lock_read()
1777
2343
            self._refresh_data()
1778
 
        return LogicalLockResult(self.unlock)
1779
2344
 
1780
2345
    def leave_lock_in_place(self):
1781
2346
        # not supported - raise an error
1786
2351
        raise NotImplementedError(self.dont_leave_lock_in_place)
1787
2352
 
1788
2353
    @needs_write_lock
1789
 
    def pack(self, hint=None, clean_obsolete_packs=False):
 
2354
    def pack(self, hint=None):
1790
2355
        """Compress the data within the repository.
1791
2356
 
1792
2357
        This will pack all the data to a single pack. In future it may
1793
2358
        recompress deltas or do other such expensive operations.
1794
2359
        """
1795
 
        self._pack_collection.pack(hint=hint, clean_obsolete_packs=clean_obsolete_packs)
 
2360
        self._pack_collection.pack(hint=hint)
1796
2361
 
1797
2362
    @needs_write_lock
1798
2363
    def reconcile(self, other=None, thorough=False):
1803
2368
        return reconciler
1804
2369
 
1805
2370
    def _reconcile_pack(self, collection, packs, extension, revs, pb):
1806
 
        raise NotImplementedError(self._reconcile_pack)
 
2371
        packer = ReconcilePacker(collection, packs, extension, revs)
 
2372
        return packer.pack(pb)
1807
2373
 
1808
 
    @only_raises(errors.LockNotHeld, errors.LockBroken)
1809
2374
    def unlock(self):
1810
2375
        if self._write_lock_count == 1 and self._write_group is not None:
1811
2376
            self.abort_write_group()
1812
 
            self._unstacked_provider.disable_cache()
1813
2377
            self._transaction = None
1814
2378
            self._write_lock_count = 0
1815
2379
            raise errors.BzrError(
1825
2389
            self.control_files.unlock()
1826
2390
 
1827
2391
        if not self.is_locked():
1828
 
            self._unstacked_provider.disable_cache()
1829
2392
            for repo in self._fallback_repositories:
1830
2393
                repo.unlock()
1831
2394
 
1832
2395
 
1833
 
class RepositoryFormatPack(MetaDirVersionedFileRepositoryFormat):
 
2396
class KnitPackStreamSource(StreamSource):
 
2397
    """A StreamSource used to transfer data between same-format KnitPack repos.
 
2398
 
 
2399
    This source assumes:
 
2400
        1) Same serialization format for all objects
 
2401
        2) Same root information
 
2402
        3) XML format inventories
 
2403
        4) Atomic inserts (so we can stream inventory texts before text
 
2404
           content)
 
2405
        5) No chk_bytes
 
2406
    """
 
2407
 
 
2408
    def __init__(self, from_repository, to_format):
 
2409
        super(KnitPackStreamSource, self).__init__(from_repository, to_format)
 
2410
        self._text_keys = None
 
2411
        self._text_fetch_order = 'unordered'
 
2412
 
 
2413
    def _get_filtered_inv_stream(self, revision_ids):
 
2414
        from_repo = self.from_repository
 
2415
        parent_ids = from_repo._find_parent_ids_of_revisions(revision_ids)
 
2416
        parent_keys = [(p,) for p in parent_ids]
 
2417
        find_text_keys = from_repo._find_text_key_references_from_xml_inventory_lines
 
2418
        parent_text_keys = set(find_text_keys(
 
2419
            from_repo._inventory_xml_lines_for_keys(parent_keys)))
 
2420
        content_text_keys = set()
 
2421
        knit = KnitVersionedFiles(None, None)
 
2422
        factory = KnitPlainFactory()
 
2423
        def find_text_keys_from_content(record):
 
2424
            if record.storage_kind not in ('knit-delta-gz', 'knit-ft-gz'):
 
2425
                raise ValueError("Unknown content storage kind for"
 
2426
                    " inventory text: %s" % (record.storage_kind,))
 
2427
            # It's a knit record, it has a _raw_record field (even if it was
 
2428
            # reconstituted from a network stream).
 
2429
            raw_data = record._raw_record
 
2430
            # read the entire thing
 
2431
            revision_id = record.key[-1]
 
2432
            content, _ = knit._parse_record(revision_id, raw_data)
 
2433
            if record.storage_kind == 'knit-delta-gz':
 
2434
                line_iterator = factory.get_linedelta_content(content)
 
2435
            elif record.storage_kind == 'knit-ft-gz':
 
2436
                line_iterator = factory.get_fulltext_content(content)
 
2437
            content_text_keys.update(find_text_keys(
 
2438
                [(line, revision_id) for line in line_iterator]))
 
2439
        revision_keys = [(r,) for r in revision_ids]
 
2440
        def _filtered_inv_stream():
 
2441
            source_vf = from_repo.inventories
 
2442
            stream = source_vf.get_record_stream(revision_keys,
 
2443
                                                 'unordered', False)
 
2444
            for record in stream:
 
2445
                if record.storage_kind == 'absent':
 
2446
                    raise errors.NoSuchRevision(from_repo, record.key)
 
2447
                find_text_keys_from_content(record)
 
2448
                yield record
 
2449
            self._text_keys = content_text_keys - parent_text_keys
 
2450
        return ('inventories', _filtered_inv_stream())
 
2451
 
 
2452
    def _get_text_stream(self):
 
2453
        # Note: We know we don't have to handle adding root keys, because both
 
2454
        # the source and target are the identical network name.
 
2455
        text_stream = self.from_repository.texts.get_record_stream(
 
2456
                        self._text_keys, self._text_fetch_order, False)
 
2457
        return ('texts', text_stream)
 
2458
 
 
2459
    def get_stream(self, search):
 
2460
        revision_ids = search.get_keys()
 
2461
        for stream_info in self._fetch_revision_texts(revision_ids):
 
2462
            yield stream_info
 
2463
        self._revision_keys = [(rev_id,) for rev_id in revision_ids]
 
2464
        yield self._get_filtered_inv_stream(revision_ids)
 
2465
        yield self._get_text_stream()
 
2466
 
 
2467
 
 
2468
 
 
2469
class RepositoryFormatPack(MetaDirRepositoryFormat):
1834
2470
    """Format logic for pack structured repositories.
1835
2471
 
1836
2472
    This repository format has:
1866
2502
    index_class = None
1867
2503
    _fetch_uses_deltas = True
1868
2504
    fast_deltas = False
1869
 
    supports_funky_characters = True
1870
 
    revision_graph_can_have_wrong_parents = True
1871
2505
 
1872
2506
    def initialize(self, a_bzrdir, shared=False):
1873
2507
        """Create a pack based repository.
1884
2518
        utf8_files = [('format', self.get_format_string())]
1885
2519
 
1886
2520
        self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1887
 
        repository = self.open(a_bzrdir=a_bzrdir, _found=True)
1888
 
        self._run_post_repo_init_hooks(repository, a_bzrdir, shared)
1889
 
        return repository
 
2521
        return self.open(a_bzrdir=a_bzrdir, _found=True)
1890
2522
 
1891
2523
    def open(self, a_bzrdir, _found=False, _override_transport=None):
1892
2524
        """See RepositoryFormat.open().
1910
2542
                              _serializer=self._serializer)
1911
2543
 
1912
2544
 
1913
 
class RetryPackOperations(errors.RetryWithNewPacks):
1914
 
    """Raised when we are packing and we find a missing file.
1915
 
 
1916
 
    Meant as a signaling exception, to tell the RepositoryPackCollection.pack
1917
 
    code it should try again.
1918
 
    """
1919
 
 
1920
 
    internal_error = True
1921
 
 
1922
 
    _fmt = ("Pack files have changed, reload and try pack again."
1923
 
            " context: %(context)s %(orig_error)s")
1924
 
 
1925
 
 
1926
 
class _DirectPackAccess(object):
1927
 
    """Access to data in one or more packs with less translation."""
1928
 
 
1929
 
    def __init__(self, index_to_packs, reload_func=None, flush_func=None):
1930
 
        """Create a _DirectPackAccess object.
1931
 
 
1932
 
        :param index_to_packs: A dict mapping index objects to the transport
1933
 
            and file names for obtaining data.
1934
 
        :param reload_func: A function to call if we determine that the pack
1935
 
            files have moved and we need to reload our caches. See
1936
 
            bzrlib.repo_fmt.pack_repo.AggregateIndex for more details.
1937
 
        """
1938
 
        self._container_writer = None
1939
 
        self._write_index = None
1940
 
        self._indices = index_to_packs
1941
 
        self._reload_func = reload_func
1942
 
        self._flush_func = flush_func
1943
 
 
1944
 
    def add_raw_records(self, key_sizes, raw_data):
1945
 
        """Add raw knit bytes to a storage area.
1946
 
 
1947
 
        The data is spooled to the container writer in one bytes-record per
1948
 
        raw data item.
1949
 
 
1950
 
        :param sizes: An iterable of tuples containing the key and size of each
1951
 
            raw data segment.
1952
 
        :param raw_data: A bytestring containing the data.
1953
 
        :return: A list of memos to retrieve the record later. Each memo is an
1954
 
            opaque index memo. For _DirectPackAccess the memo is (index, pos,
1955
 
            length), where the index field is the write_index object supplied
1956
 
            to the PackAccess object.
1957
 
        """
1958
 
        if type(raw_data) is not str:
1959
 
            raise AssertionError(
1960
 
                'data must be plain bytes was %s' % type(raw_data))
1961
 
        result = []
1962
 
        offset = 0
1963
 
        for key, size in key_sizes:
1964
 
            p_offset, p_length = self._container_writer.add_bytes_record(
1965
 
                raw_data[offset:offset+size], [])
1966
 
            offset += size
1967
 
            result.append((self._write_index, p_offset, p_length))
1968
 
        return result
1969
 
 
1970
 
    def flush(self):
1971
 
        """Flush pending writes on this access object.
1972
 
 
1973
 
        This will flush any buffered writes to a NewPack.
1974
 
        """
1975
 
        if self._flush_func is not None:
1976
 
            self._flush_func()
1977
 
 
1978
 
    def get_raw_records(self, memos_for_retrieval):
1979
 
        """Get the raw bytes for a records.
1980
 
 
1981
 
        :param memos_for_retrieval: An iterable containing the (index, pos,
1982
 
            length) memo for retrieving the bytes. The Pack access method
1983
 
            looks up the pack to use for a given record in its index_to_pack
1984
 
            map.
1985
 
        :return: An iterator over the bytes of the records.
1986
 
        """
1987
 
        # first pass, group into same-index requests
1988
 
        request_lists = []
1989
 
        current_index = None
1990
 
        for (index, offset, length) in memos_for_retrieval:
1991
 
            if current_index == index:
1992
 
                current_list.append((offset, length))
1993
 
            else:
1994
 
                if current_index is not None:
1995
 
                    request_lists.append((current_index, current_list))
1996
 
                current_index = index
1997
 
                current_list = [(offset, length)]
1998
 
        # handle the last entry
1999
 
        if current_index is not None:
2000
 
            request_lists.append((current_index, current_list))
2001
 
        for index, offsets in request_lists:
2002
 
            try:
2003
 
                transport, path = self._indices[index]
2004
 
            except KeyError:
2005
 
                # A KeyError here indicates that someone has triggered an index
2006
 
                # reload, and this index has gone missing, we need to start
2007
 
                # over.
2008
 
                if self._reload_func is None:
2009
 
                    # If we don't have a _reload_func there is nothing that can
2010
 
                    # be done
2011
 
                    raise
2012
 
                raise errors.RetryWithNewPacks(index,
2013
 
                                               reload_occurred=True,
2014
 
                                               exc_info=sys.exc_info())
2015
 
            try:
2016
 
                reader = pack.make_readv_reader(transport, path, offsets)
2017
 
                for names, read_func in reader.iter_records():
2018
 
                    yield read_func(None)
2019
 
            except errors.NoSuchFile:
2020
 
                # A NoSuchFile error indicates that a pack file has gone
2021
 
                # missing on disk, we need to trigger a reload, and start over.
2022
 
                if self._reload_func is None:
2023
 
                    raise
2024
 
                raise errors.RetryWithNewPacks(transport.abspath(path),
2025
 
                                               reload_occurred=False,
2026
 
                                               exc_info=sys.exc_info())
2027
 
 
2028
 
    def set_writer(self, writer, index, transport_packname):
2029
 
        """Set a writer to use for adding data."""
2030
 
        if index is not None:
2031
 
            self._indices[index] = transport_packname
2032
 
        self._container_writer = writer
2033
 
        self._write_index = index
2034
 
 
2035
 
    def reload_or_raise(self, retry_exc):
2036
 
        """Try calling the reload function, or re-raise the original exception.
2037
 
 
2038
 
        This should be called after _DirectPackAccess raises a
2039
 
        RetryWithNewPacks exception. This function will handle the common logic
2040
 
        of determining when the error is fatal versus being temporary.
2041
 
        It will also make sure that the original exception is raised, rather
2042
 
        than the RetryWithNewPacks exception.
2043
 
 
2044
 
        If this function returns, then the calling function should retry
2045
 
        whatever operation was being performed. Otherwise an exception will
2046
 
        be raised.
2047
 
 
2048
 
        :param retry_exc: A RetryWithNewPacks exception.
2049
 
        """
2050
 
        is_error = False
2051
 
        if self._reload_func is None:
2052
 
            is_error = True
2053
 
        elif not self._reload_func():
2054
 
            # The reload claimed that nothing changed
2055
 
            if not retry_exc.reload_occurred:
2056
 
                # If there wasn't an earlier reload, then we really were
2057
 
                # expecting to find changes. We didn't find them, so this is a
2058
 
                # hard error
2059
 
                is_error = True
2060
 
        if is_error:
2061
 
            exc_class, exc_value, exc_traceback = retry_exc.exc_info
2062
 
            raise exc_class, exc_value, exc_traceback
2063
 
 
2064
 
 
 
2545
class RepositoryFormatKnitPack1(RepositoryFormatPack):
 
2546
    """A no-subtrees parameterized Pack repository.
 
2547
 
 
2548
    This format was introduced in 0.92.
 
2549
    """
 
2550
 
 
2551
    repository_class = KnitPackRepository
 
2552
    _commit_builder_class = PackCommitBuilder
 
2553
    @property
 
2554
    def _serializer(self):
 
2555
        return xml5.serializer_v5
 
2556
    # What index classes to use
 
2557
    index_builder_class = InMemoryGraphIndex
 
2558
    index_class = GraphIndex
 
2559
 
 
2560
    def _get_matching_bzrdir(self):
 
2561
        return bzrdir.format_registry.make_bzrdir('pack-0.92')
 
2562
 
 
2563
    def _ignore_setting_bzrdir(self, format):
 
2564
        pass
 
2565
 
 
2566
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2567
 
 
2568
    def get_format_string(self):
 
2569
        """See RepositoryFormat.get_format_string()."""
 
2570
        return "Bazaar pack repository format 1 (needs bzr 0.92)\n"
 
2571
 
 
2572
    def get_format_description(self):
 
2573
        """See RepositoryFormat.get_format_description()."""
 
2574
        return "Packs containing knits without subtree support"
 
2575
 
 
2576
    def check_conversion_target(self, target_format):
 
2577
        pass
 
2578
 
 
2579
 
 
2580
class RepositoryFormatKnitPack3(RepositoryFormatPack):
 
2581
    """A subtrees parameterized Pack repository.
 
2582
 
 
2583
    This repository format uses the xml7 serializer to get:
 
2584
     - support for recording full info about the tree root
 
2585
     - support for recording tree-references
 
2586
 
 
2587
    This format was introduced in 0.92.
 
2588
    """
 
2589
 
 
2590
    repository_class = KnitPackRepository
 
2591
    _commit_builder_class = PackRootCommitBuilder
 
2592
    rich_root_data = True
 
2593
    supports_tree_reference = True
 
2594
    @property
 
2595
    def _serializer(self):
 
2596
        return xml7.serializer_v7
 
2597
    # What index classes to use
 
2598
    index_builder_class = InMemoryGraphIndex
 
2599
    index_class = GraphIndex
 
2600
 
 
2601
    def _get_matching_bzrdir(self):
 
2602
        return bzrdir.format_registry.make_bzrdir(
 
2603
            'pack-0.92-subtree')
 
2604
 
 
2605
    def _ignore_setting_bzrdir(self, format):
 
2606
        pass
 
2607
 
 
2608
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2609
 
 
2610
    def check_conversion_target(self, target_format):
 
2611
        if not target_format.rich_root_data:
 
2612
            raise errors.BadConversionTarget(
 
2613
                'Does not support rich root data.', target_format)
 
2614
        if not getattr(target_format, 'supports_tree_reference', False):
 
2615
            raise errors.BadConversionTarget(
 
2616
                'Does not support nested trees', target_format)
 
2617
 
 
2618
    def get_format_string(self):
 
2619
        """See RepositoryFormat.get_format_string()."""
 
2620
        return "Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n"
 
2621
 
 
2622
    def get_format_description(self):
 
2623
        """See RepositoryFormat.get_format_description()."""
 
2624
        return "Packs containing knits with subtree support\n"
 
2625
 
 
2626
 
 
2627
class RepositoryFormatKnitPack4(RepositoryFormatPack):
 
2628
    """A rich-root, no subtrees parameterized Pack repository.
 
2629
 
 
2630
    This repository format uses the xml6 serializer to get:
 
2631
     - support for recording full info about the tree root
 
2632
 
 
2633
    This format was introduced in 1.0.
 
2634
    """
 
2635
 
 
2636
    repository_class = KnitPackRepository
 
2637
    _commit_builder_class = PackRootCommitBuilder
 
2638
    rich_root_data = True
 
2639
    supports_tree_reference = False
 
2640
    @property
 
2641
    def _serializer(self):
 
2642
        return xml6.serializer_v6
 
2643
    # What index classes to use
 
2644
    index_builder_class = InMemoryGraphIndex
 
2645
    index_class = GraphIndex
 
2646
 
 
2647
    def _get_matching_bzrdir(self):
 
2648
        return bzrdir.format_registry.make_bzrdir(
 
2649
            'rich-root-pack')
 
2650
 
 
2651
    def _ignore_setting_bzrdir(self, format):
 
2652
        pass
 
2653
 
 
2654
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2655
 
 
2656
    def check_conversion_target(self, target_format):
 
2657
        if not target_format.rich_root_data:
 
2658
            raise errors.BadConversionTarget(
 
2659
                'Does not support rich root data.', target_format)
 
2660
 
 
2661
    def get_format_string(self):
 
2662
        """See RepositoryFormat.get_format_string()."""
 
2663
        return ("Bazaar pack repository format 1 with rich root"
 
2664
                " (needs bzr 1.0)\n")
 
2665
 
 
2666
    def get_format_description(self):
 
2667
        """See RepositoryFormat.get_format_description()."""
 
2668
        return "Packs containing knits with rich root support\n"
 
2669
 
 
2670
 
 
2671
class RepositoryFormatKnitPack5(RepositoryFormatPack):
 
2672
    """Repository that supports external references to allow stacking.
 
2673
 
 
2674
    New in release 1.6.
 
2675
 
 
2676
    Supports external lookups, which results in non-truncated ghosts after
 
2677
    reconcile compared to pack-0.92 formats.
 
2678
    """
 
2679
 
 
2680
    repository_class = KnitPackRepository
 
2681
    _commit_builder_class = PackCommitBuilder
 
2682
    supports_external_lookups = True
 
2683
    # What index classes to use
 
2684
    index_builder_class = InMemoryGraphIndex
 
2685
    index_class = GraphIndex
 
2686
 
 
2687
    @property
 
2688
    def _serializer(self):
 
2689
        return xml5.serializer_v5
 
2690
 
 
2691
    def _get_matching_bzrdir(self):
 
2692
        return bzrdir.format_registry.make_bzrdir('1.6')
 
2693
 
 
2694
    def _ignore_setting_bzrdir(self, format):
 
2695
        pass
 
2696
 
 
2697
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2698
 
 
2699
    def get_format_string(self):
 
2700
        """See RepositoryFormat.get_format_string()."""
 
2701
        return "Bazaar RepositoryFormatKnitPack5 (bzr 1.6)\n"
 
2702
 
 
2703
    def get_format_description(self):
 
2704
        """See RepositoryFormat.get_format_description()."""
 
2705
        return "Packs 5 (adds stacking support, requires bzr 1.6)"
 
2706
 
 
2707
    def check_conversion_target(self, target_format):
 
2708
        pass
 
2709
 
 
2710
 
 
2711
class RepositoryFormatKnitPack5RichRoot(RepositoryFormatPack):
 
2712
    """A repository with rich roots and stacking.
 
2713
 
 
2714
    New in release 1.6.1.
 
2715
 
 
2716
    Supports stacking on other repositories, allowing data to be accessed
 
2717
    without being stored locally.
 
2718
    """
 
2719
 
 
2720
    repository_class = KnitPackRepository
 
2721
    _commit_builder_class = PackRootCommitBuilder
 
2722
    rich_root_data = True
 
2723
    supports_tree_reference = False # no subtrees
 
2724
    supports_external_lookups = True
 
2725
    # What index classes to use
 
2726
    index_builder_class = InMemoryGraphIndex
 
2727
    index_class = GraphIndex
 
2728
 
 
2729
    @property
 
2730
    def _serializer(self):
 
2731
        return xml6.serializer_v6
 
2732
 
 
2733
    def _get_matching_bzrdir(self):
 
2734
        return bzrdir.format_registry.make_bzrdir(
 
2735
            '1.6.1-rich-root')
 
2736
 
 
2737
    def _ignore_setting_bzrdir(self, format):
 
2738
        pass
 
2739
 
 
2740
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2741
 
 
2742
    def check_conversion_target(self, target_format):
 
2743
        if not target_format.rich_root_data:
 
2744
            raise errors.BadConversionTarget(
 
2745
                'Does not support rich root data.', target_format)
 
2746
 
 
2747
    def get_format_string(self):
 
2748
        """See RepositoryFormat.get_format_string()."""
 
2749
        return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6.1)\n"
 
2750
 
 
2751
    def get_format_description(self):
 
2752
        return "Packs 5 rich-root (adds stacking support, requires bzr 1.6.1)"
 
2753
 
 
2754
 
 
2755
class RepositoryFormatKnitPack5RichRootBroken(RepositoryFormatPack):
 
2756
    """A repository with rich roots and external references.
 
2757
 
 
2758
    New in release 1.6.
 
2759
 
 
2760
    Supports external lookups, which results in non-truncated ghosts after
 
2761
    reconcile compared to pack-0.92 formats.
 
2762
 
 
2763
    This format was deprecated because the serializer it uses accidentally
 
2764
    supported subtrees, when the format was not intended to. This meant that
 
2765
    someone could accidentally fetch from an incorrect repository.
 
2766
    """
 
2767
 
 
2768
    repository_class = KnitPackRepository
 
2769
    _commit_builder_class = PackRootCommitBuilder
 
2770
    rich_root_data = True
 
2771
    supports_tree_reference = False # no subtrees
 
2772
 
 
2773
    supports_external_lookups = True
 
2774
    # What index classes to use
 
2775
    index_builder_class = InMemoryGraphIndex
 
2776
    index_class = GraphIndex
 
2777
 
 
2778
    @property
 
2779
    def _serializer(self):
 
2780
        return xml7.serializer_v7
 
2781
 
 
2782
    def _get_matching_bzrdir(self):
 
2783
        matching = bzrdir.format_registry.make_bzrdir(
 
2784
            '1.6.1-rich-root')
 
2785
        matching.repository_format = self
 
2786
        return matching
 
2787
 
 
2788
    def _ignore_setting_bzrdir(self, format):
 
2789
        pass
 
2790
 
 
2791
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2792
 
 
2793
    def check_conversion_target(self, target_format):
 
2794
        if not target_format.rich_root_data:
 
2795
            raise errors.BadConversionTarget(
 
2796
                'Does not support rich root data.', target_format)
 
2797
 
 
2798
    def get_format_string(self):
 
2799
        """See RepositoryFormat.get_format_string()."""
 
2800
        return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6)\n"
 
2801
 
 
2802
    def get_format_description(self):
 
2803
        return ("Packs 5 rich-root (adds stacking support, requires bzr 1.6)"
 
2804
                " (deprecated)")
 
2805
 
 
2806
 
 
2807
class RepositoryFormatKnitPack6(RepositoryFormatPack):
 
2808
    """A repository with stacking and btree indexes,
 
2809
    without rich roots or subtrees.
 
2810
 
 
2811
    This is equivalent to pack-1.6 with B+Tree indices.
 
2812
    """
 
2813
 
 
2814
    repository_class = KnitPackRepository
 
2815
    _commit_builder_class = PackCommitBuilder
 
2816
    supports_external_lookups = True
 
2817
    # What index classes to use
 
2818
    index_builder_class = BTreeBuilder
 
2819
    index_class = BTreeGraphIndex
 
2820
 
 
2821
    @property
 
2822
    def _serializer(self):
 
2823
        return xml5.serializer_v5
 
2824
 
 
2825
    def _get_matching_bzrdir(self):
 
2826
        return bzrdir.format_registry.make_bzrdir('1.9')
 
2827
 
 
2828
    def _ignore_setting_bzrdir(self, format):
 
2829
        pass
 
2830
 
 
2831
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2832
 
 
2833
    def get_format_string(self):
 
2834
        """See RepositoryFormat.get_format_string()."""
 
2835
        return "Bazaar RepositoryFormatKnitPack6 (bzr 1.9)\n"
 
2836
 
 
2837
    def get_format_description(self):
 
2838
        """See RepositoryFormat.get_format_description()."""
 
2839
        return "Packs 6 (uses btree indexes, requires bzr 1.9)"
 
2840
 
 
2841
    def check_conversion_target(self, target_format):
 
2842
        pass
 
2843
 
 
2844
 
 
2845
class RepositoryFormatKnitPack6RichRoot(RepositoryFormatPack):
 
2846
    """A repository with rich roots, no subtrees, stacking and btree indexes.
 
2847
 
 
2848
    1.6-rich-root with B+Tree indices.
 
2849
    """
 
2850
 
 
2851
    repository_class = KnitPackRepository
 
2852
    _commit_builder_class = PackRootCommitBuilder
 
2853
    rich_root_data = True
 
2854
    supports_tree_reference = False # no subtrees
 
2855
    supports_external_lookups = True
 
2856
    # What index classes to use
 
2857
    index_builder_class = BTreeBuilder
 
2858
    index_class = BTreeGraphIndex
 
2859
 
 
2860
    @property
 
2861
    def _serializer(self):
 
2862
        return xml6.serializer_v6
 
2863
 
 
2864
    def _get_matching_bzrdir(self):
 
2865
        return bzrdir.format_registry.make_bzrdir(
 
2866
            '1.9-rich-root')
 
2867
 
 
2868
    def _ignore_setting_bzrdir(self, format):
 
2869
        pass
 
2870
 
 
2871
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2872
 
 
2873
    def check_conversion_target(self, target_format):
 
2874
        if not target_format.rich_root_data:
 
2875
            raise errors.BadConversionTarget(
 
2876
                'Does not support rich root data.', target_format)
 
2877
 
 
2878
    def get_format_string(self):
 
2879
        """See RepositoryFormat.get_format_string()."""
 
2880
        return "Bazaar RepositoryFormatKnitPack6RichRoot (bzr 1.9)\n"
 
2881
 
 
2882
    def get_format_description(self):
 
2883
        return "Packs 6 rich-root (uses btree indexes, requires bzr 1.9)"
 
2884
 
 
2885
 
 
2886
class RepositoryFormatPackDevelopment2Subtree(RepositoryFormatPack):
 
2887
    """A subtrees development repository.
 
2888
 
 
2889
    This format should be retained until the second release after bzr 1.7.
 
2890
 
 
2891
    1.6.1-subtree[as it might have been] with B+Tree indices.
 
2892
 
 
2893
    This is [now] retained until we have a CHK based subtree format in
 
2894
    development.
 
2895
    """
 
2896
 
 
2897
    repository_class = KnitPackRepository
 
2898
    _commit_builder_class = PackRootCommitBuilder
 
2899
    rich_root_data = True
 
2900
    supports_tree_reference = True
 
2901
    supports_external_lookups = True
 
2902
    # What index classes to use
 
2903
    index_builder_class = BTreeBuilder
 
2904
    index_class = BTreeGraphIndex
 
2905
 
 
2906
    @property
 
2907
    def _serializer(self):
 
2908
        return xml7.serializer_v7
 
2909
 
 
2910
    def _get_matching_bzrdir(self):
 
2911
        return bzrdir.format_registry.make_bzrdir(
 
2912
            'development-subtree')
 
2913
 
 
2914
    def _ignore_setting_bzrdir(self, format):
 
2915
        pass
 
2916
 
 
2917
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2918
 
 
2919
    def check_conversion_target(self, target_format):
 
2920
        if not target_format.rich_root_data:
 
2921
            raise errors.BadConversionTarget(
 
2922
                'Does not support rich root data.', target_format)
 
2923
        if not getattr(target_format, 'supports_tree_reference', False):
 
2924
            raise errors.BadConversionTarget(
 
2925
                'Does not support nested trees', target_format)
 
2926
 
 
2927
    def get_format_string(self):
 
2928
        """See RepositoryFormat.get_format_string()."""
 
2929
        return ("Bazaar development format 2 with subtree support "
 
2930
            "(needs bzr.dev from before 1.8)\n")
 
2931
 
 
2932
    def get_format_description(self):
 
2933
        """See RepositoryFormat.get_format_description()."""
 
2934
        return ("Development repository format, currently the same as "
 
2935
            "1.6.1-subtree with B+Tree indices.\n")
2065
2936