~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/repofmt/pack_repo.py

  • Committer: John Arbash Meinel
  • Date: 2009-06-04 16:50:33 UTC
  • mto: This revision was merged to the branch mainline in revision 4410.
  • Revision ID: john@arbash-meinel.com-20090604165033-bfdo0lyf4yt4vjcz
We don't need a base Coder class, because Decoder._update_tail is different than Encoder._update_tail.
(one adds, one subtracts from self.size).
So we now have 2 versions of the macro, and the test suite stops crashing... :)

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