~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/repofmt/pack_repo.py

  • Committer: Jelmer Vernooij
  • Date: 2009-06-09 00:59:51 UTC
  • mto: (4443.1.1 bzr.dev)
  • mto: This revision was merged to the branch mainline in revision 4444.
  • Revision ID: jelmer@samba.org-20090609005951-apv900cdk35o2ygh
Move squashing of XML-invalid characters to XMLSerializer.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2007-2011 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
24
24
 
25
25
from bzrlib import (
26
26
    chk_map,
27
 
    cleanup,
28
 
    config,
29
27
    debug,
30
28
    graph,
31
29
    osutils,
32
30
    pack,
33
31
    transactions,
34
 
    tsort,
35
32
    ui,
 
33
    xml5,
 
34
    xml6,
 
35
    xml7,
36
36
    )
37
37
from bzrlib.index import (
38
38
    CombinedGraphIndex,
 
39
    GraphIndex,
 
40
    GraphIndexBuilder,
39
41
    GraphIndexPrefixAdapter,
40
 
    )
 
42
    InMemoryGraphIndex,
 
43
    )
 
44
from bzrlib.knit import (
 
45
    KnitPlainFactory,
 
46
    KnitVersionedFiles,
 
47
    _KnitGraphIndex,
 
48
    _DirectPackAccess,
 
49
    )
 
50
from bzrlib import tsort
41
51
""")
42
52
from bzrlib import (
43
 
    btree_index,
 
53
    bzrdir,
44
54
    errors,
45
55
    lockable_files,
46
56
    lockdir,
 
57
    revision as _mod_revision,
 
58
    symbol_versioning,
47
59
    )
48
60
 
49
 
from bzrlib.decorators import (
50
 
    needs_read_lock,
51
 
    needs_write_lock,
52
 
    only_raises,
53
 
    )
54
 
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
55
71
from bzrlib.repository import (
56
 
    _LazyListJoin,
57
 
    MetaDirRepository,
 
72
    CommitBuilder,
 
73
    MetaDirRepositoryFormat,
58
74
    RepositoryFormat,
59
 
    RepositoryWriteLockResult,
60
 
    )
61
 
from bzrlib.vf_repository import (
62
 
    MetaDirVersionedFileRepository,
63
 
    MetaDirVersionedFileRepositoryFormat,
64
 
    VersionedFileCommitBuilder,
65
 
    VersionedFileRootCommitBuilder,
66
 
    )
 
75
    RootCommitBuilder,
 
76
    )
 
77
import bzrlib.revision as _mod_revision
67
78
from bzrlib.trace import (
68
79
    mutter,
69
 
    note,
70
80
    warning,
71
81
    )
72
82
 
73
83
 
74
 
class PackCommitBuilder(VersionedFileCommitBuilder):
75
 
    """Subclass of VersionedFileCommitBuilder to add texts with pack semantics.
 
84
class PackCommitBuilder(CommitBuilder):
 
85
    """A subclass of CommitBuilder to add texts with pack semantics.
76
86
 
77
87
    Specifically this uses one knit object rather than one knit object per
78
88
    added text, reducing memory and object pressure.
80
90
 
81
91
    def __init__(self, repository, parents, config, timestamp=None,
82
92
                 timezone=None, committer=None, revprops=None,
83
 
                 revision_id=None, lossy=False):
84
 
        VersionedFileCommitBuilder.__init__(self, repository, parents, config,
 
93
                 revision_id=None):
 
94
        CommitBuilder.__init__(self, repository, parents, config,
85
95
            timestamp=timestamp, timezone=timezone, committer=committer,
86
 
            revprops=revprops, revision_id=revision_id, lossy=lossy)
 
96
            revprops=revprops, revision_id=revision_id)
87
97
        self._file_graph = graph.Graph(
88
98
            repository._pack_collection.text_index.combined_index)
89
99
 
92
102
        return set([key[1] for key in self._file_graph.heads(keys)])
93
103
 
94
104
 
95
 
class PackRootCommitBuilder(VersionedFileRootCommitBuilder):
 
105
class PackRootCommitBuilder(RootCommitBuilder):
96
106
    """A subclass of RootCommitBuilder to add texts with pack semantics.
97
107
 
98
108
    Specifically this uses one knit object rather than one knit object per
101
111
 
102
112
    def __init__(self, repository, parents, config, timestamp=None,
103
113
                 timezone=None, committer=None, revprops=None,
104
 
                 revision_id=None, lossy=False):
105
 
        super(PackRootCommitBuilder, self).__init__(repository, parents,
106
 
            config, timestamp=timestamp, timezone=timezone,
107
 
            committer=committer, revprops=revprops, revision_id=revision_id,
108
 
            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)
109
118
        self._file_graph = graph.Graph(
110
119
            repository._pack_collection.text_index.combined_index)
111
120
 
219
228
        return self.index_name('text', name)
220
229
 
221
230
    def _replace_index_with_readonly(self, index_type):
222
 
        unlimited_cache = False
223
 
        if index_type == 'chk':
224
 
            unlimited_cache = True
225
 
        index = self.index_class(self.index_transport,
226
 
                    self.index_name(index_type, self.name),
227
 
                    self.index_sizes[self.index_offset(index_type)],
228
 
                    unlimited_cache=unlimited_cache)
229
 
        if index_type == 'chk':
230
 
            index._leaf_factory = btree_index._gcchk_factory
231
 
        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)]))
232
235
 
233
236
 
234
237
class ExistingPack(Pack):
309
312
 
310
313
    def finish(self):
311
314
        self._check_references()
 
315
        new_name = '../packs/' + self.file_name()
 
316
        self.upload_transport.rename(self.file_name(), new_name)
312
317
        index_types = ['revision', 'inventory', 'text', 'signature']
313
318
        if self.chk_index is not None:
314
319
            index_types.append('chk')
315
320
        for index_type in index_types:
316
321
            old_name = self.index_name(index_type, self.name)
317
322
            new_name = '../indices/' + old_name
318
 
            self.upload_transport.move(old_name, new_name)
 
323
            self.upload_transport.rename(old_name, new_name)
319
324
            self._replace_index_with_readonly(index_type)
320
 
        new_name = '../packs/' + self.file_name()
321
 
        self.upload_transport.move(self.file_name(), new_name)
322
325
        self._state = 'finished'
323
326
 
324
327
    def _get_external_refs(self, index):
423
426
        self._writer.begin()
424
427
        # what state is the pack in? (open, finished, aborted)
425
428
        self._state = 'open'
426
 
        # no name until we finish writing the content
427
 
        self.name = None
428
429
 
429
430
    def abort(self):
430
431
        """Cancel creating this pack."""
451
452
            self.signature_index.key_count() or
452
453
            (self.chk_index is not None and self.chk_index.key_count()))
453
454
 
454
 
    def finish_content(self):
455
 
        if self.name is not None:
456
 
            return
457
 
        self._writer.end()
458
 
        if self._buffer[1]:
459
 
            self._write_data('', flush=True)
460
 
        self.name = self._hash.hexdigest()
461
 
 
462
455
    def finish(self, suspend=False):
463
456
        """Finish the new pack.
464
457
 
470
463
         - stores the index size tuple for the pack in the index_sizes
471
464
           attribute.
472
465
        """
473
 
        self.finish_content()
 
466
        self._writer.end()
 
467
        if self._buffer[1]:
 
468
            self._write_data('', flush=True)
 
469
        self.name = self._hash.hexdigest()
474
470
        if not suspend:
475
471
            self._check_references()
476
472
        # write indices
479
475
        # visible is smaller.  On the other hand none will be seen until
480
476
        # they're in the names list.
481
477
        self.index_sizes = [None, None, None, None]
482
 
        self._write_index('revision', self.revision_index, 'revision',
483
 
            suspend)
 
478
        self._write_index('revision', self.revision_index, 'revision', suspend)
484
479
        self._write_index('inventory', self.inventory_index, 'inventory',
485
480
            suspend)
486
481
        self._write_index('text', self.text_index, 'file texts', suspend)
490
485
            self.index_sizes.append(None)
491
486
            self._write_index('chk', self.chk_index,
492
487
                'content hash bytes', suspend)
493
 
        self.write_stream.close(
494
 
            want_fdatasync=self._pack_collection.config_stack.get('repository.fdatasync'))
 
488
        self.write_stream.close()
495
489
        # Note that this will clobber an existing pack with the same name,
496
490
        # without checking for hash collisions. While this is undesirable this
497
491
        # is something that can be rectified in a subsequent release. One way
506
500
        new_name = self.name + '.pack'
507
501
        if not suspend:
508
502
            new_name = '../packs/' + new_name
509
 
        self.upload_transport.move(self.random_name, new_name)
 
503
        self.upload_transport.rename(self.random_name, new_name)
510
504
        self._state = 'finished'
511
505
        if 'pack' in debug.debug_flags:
512
506
            # XXX: size might be interesting?
540
534
            transport = self.upload_transport
541
535
        else:
542
536
            transport = self.index_transport
543
 
        index_tempfile = index.finish()
544
 
        index_bytes = index_tempfile.read()
545
 
        write_stream = transport.open_write_stream(index_name,
546
 
            mode=self._file_mode)
547
 
        write_stream.write(index_bytes)
548
 
        write_stream.close(
549
 
            want_fdatasync=self._pack_collection.config_stack.get('repository.fdatasync'))
550
 
        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)
551
539
        if 'pack' in debug.debug_flags:
552
540
            # XXX: size might be interesting?
553
541
            mutter('%s: create_pack: wrote %s index: %s%s t+%6.3fs',
590
578
                                             flush_func=flush_func)
591
579
        self.add_callback = None
592
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
 
593
601
    def add_index(self, index, pack):
594
602
        """Add index to the aggregate, which is an index for Pack pack.
595
603
 
602
610
        # expose it to the index map
603
611
        self.index_to_pack[index] = pack.access_tuple()
604
612
        # put it at the front of the linear index list
605
 
        self.combined_index.insert_index(0, index, pack.name)
 
613
        self.combined_index.insert_index(0, index)
606
614
 
607
615
    def add_writable_index(self, index, pack):
608
616
        """Add an index which is able to have data added to it.
628
636
        self.data_access.set_writer(None, None, (None, None))
629
637
        self.index_to_pack.clear()
630
638
        del self.combined_index._indices[:]
631
 
        del self.combined_index._index_names[:]
632
639
        self.add_callback = None
633
640
 
634
 
    def remove_index(self, index):
 
641
    def remove_index(self, index, pack):
635
642
        """Remove index from the indices used to answer queries.
636
643
 
637
644
        :param index: An index from the pack parameter.
 
645
        :param pack: A Pack instance.
638
646
        """
639
647
        del self.index_to_pack[index]
640
 
        pos = self.combined_index._indices.index(index)
641
 
        del self.combined_index._indices[pos]
642
 
        del self.combined_index._index_names[pos]
 
648
        self.combined_index._indices.remove(index)
643
649
        if (self.add_callback is not None and
644
650
            getattr(index, 'add_nodes', None) == self.add_callback):
645
651
            self.add_callback = None
675
681
        # What text keys to copy. None for 'all texts'. This is set by
676
682
        # _copy_inventory_texts
677
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)
678
717
 
679
718
    def pack(self, pb=None):
680
719
        """Create a new pack by reading data from other packs.
691
730
        :return: A Pack object, or None if nothing was copied.
692
731
        """
693
732
        # open a pack - using the same name as the last temporary file
694
 
        # - which has already been flushed, so it's safe.
 
733
        # - which has already been flushed, so its safe.
695
734
        # XXX: - duplicate code warning with start_write_group; fix before
696
735
        #      considering 'done'.
697
736
        if self._pack_collection._new_pack is not None:
729
768
        new_pack.signature_index.set_optimize(combine_backing_indices=False)
730
769
        return new_pack
731
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
 
732
805
    def _copy_revision_texts(self):
733
806
        """Copy revision data to the new pack."""
734
 
        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
735
830
 
736
831
    def _copy_inventory_texts(self):
737
832
        """Copy the inventory texts to the new pack.
740
835
 
741
836
        Sets self._text_filter appropriately.
742
837
        """
743
 
        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)
744
868
 
745
869
    def _copy_text_texts(self):
746
 
        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()
747
895
 
748
896
    def _create_pack_from_packs(self):
749
 
        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
750
1139
 
751
1140
    def _log_copied_texts(self):
752
1141
        if 'pack' in debug.debug_flags:
756
1145
                self.new_pack.text_index.key_count(),
757
1146
                time.time() - self.new_pack.start_time)
758
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
 
759
1167
    def _use_pack(self, new_pack):
760
1168
        """Return True if new_pack should be used.
761
1169
 
765
1173
        return new_pack.data_inserted()
766
1174
 
767
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.get(key[0][1], 0))
 
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
 
768
1362
class RepositoryPackCollection(object):
769
1363
    """Management of packs within a repository.
770
1364
 
771
1365
    :ivar _names: map of {pack_name: (index_size,)}
772
1366
    """
773
1367
 
774
 
    pack_factory = None
775
 
    resumed_pack_factory = None
776
 
    normal_packer_class = None
777
 
    optimising_packer_class = None
 
1368
    pack_factory = NewPack
 
1369
    resumed_pack_factory = ResumedPack
778
1370
 
779
1371
    def __init__(self, repo, transport, index_transport, upload_transport,
780
1372
                 pack_transport, index_builder_class, index_class,
815
1407
        self.inventory_index = AggregateIndex(self.reload_pack_names, flush)
816
1408
        self.text_index = AggregateIndex(self.reload_pack_names, flush)
817
1409
        self.signature_index = AggregateIndex(self.reload_pack_names, flush)
818
 
        all_indices = [self.revision_index, self.inventory_index,
819
 
                self.text_index, self.signature_index]
820
1410
        if use_chk_index:
821
1411
            self.chk_index = AggregateIndex(self.reload_pack_names, flush)
822
 
            all_indices.append(self.chk_index)
823
1412
        else:
824
1413
            # used to determine if we're using a chk_index elsewhere.
825
1414
            self.chk_index = None
826
 
        # Tell all the CombinedGraphIndex objects about each other, so they can
827
 
        # share hints about which pack names to search first.
828
 
        all_combined = [agg_idx.combined_index for agg_idx in all_indices]
829
 
        for combined_idx in all_combined:
830
 
            combined_idx.set_sibling_indices(
831
 
                set(all_combined).difference([combined_idx]))
832
1415
        # resumed packs
833
1416
        self._resumed_packs = []
834
 
        self.config_stack = config.LocationStack(self.transport.base)
835
 
 
836
 
    def __repr__(self):
837
 
        return '%s(%r)' % (self.__class__.__name__, self.repo)
838
1417
 
839
1418
    def add_pack_to_memory(self, pack):
840
1419
        """Make a Pack object available to the repository to satisfy queries.
879
1458
        in synchronisation with certain steps. Otherwise the names collection
880
1459
        is not flushed.
881
1460
 
882
 
        :return: Something evaluating true if packing took place.
 
1461
        :return: True if packing took place.
883
1462
        """
884
1463
        while True:
885
1464
            try:
886
1465
                return self._do_autopack()
887
 
            except errors.RetryAutopack:
 
1466
            except errors.RetryAutopack, e:
888
1467
                # If we get a RetryAutopack exception, we should abort the
889
1468
                # current action, and retry.
890
1469
                pass
894
1473
        total_revisions = self.revision_index.combined_index.key_count()
895
1474
        total_packs = len(self._names)
896
1475
        if self._max_pack_count(total_revisions) >= total_packs:
897
 
            return None
 
1476
            return False
898
1477
        # determine which packs need changing
899
1478
        pack_distribution = self.pack_distribution(total_revisions)
900
1479
        existing_packs = []
922
1501
            'containing %d revisions. Packing %d files into %d affecting %d'
923
1502
            ' revisions', self, total_packs, total_revisions, num_old_packs,
924
1503
            num_new_packs, num_revs_affected)
925
 
        result = self._execute_pack_operations(pack_operations, packer_class=self.normal_packer_class,
 
1504
        self._execute_pack_operations(pack_operations,
926
1505
                                      reload_func=self._restart_autopack)
927
1506
        mutter('Auto-packing repository %s completed', self)
928
 
        return result
 
1507
        return True
929
1508
 
930
 
    def _execute_pack_operations(self, pack_operations, packer_class,
931
 
            reload_func=None):
 
1509
    def _execute_pack_operations(self, pack_operations, _packer_class=Packer,
 
1510
                                 reload_func=None):
932
1511
        """Execute a series of pack operations.
933
1512
 
934
1513
        :param pack_operations: A list of [revision_count, packs_to_combine].
935
 
        :param packer_class: The class of packer to use
936
 
        :return: The new pack names.
 
1514
        :param _packer_class: The class of packer to use (default: Packer).
 
1515
        :return: None.
937
1516
        """
938
1517
        for revision_count, packs in pack_operations:
939
1518
            # we may have no-ops from the setup logic
940
1519
            if len(packs) == 0:
941
1520
                continue
942
 
            packer = packer_class(self, packs, '.autopack',
 
1521
            packer = _packer_class(self, packs, '.autopack',
943
1522
                                   reload_func=reload_func)
944
1523
            try:
945
 
                result = packer.pack()
 
1524
                packer.pack()
946
1525
            except errors.RetryWithNewPacks:
947
1526
                # An exception is propagating out of this context, make sure
948
1527
                # this packer has cleaned up. Packer() doesn't set its new_pack
951
1530
                if packer.new_pack is not None:
952
1531
                    packer.new_pack.abort()
953
1532
                raise
954
 
            if result is None:
955
 
                return
956
1533
            for pack in packs:
957
1534
                self._remove_pack_from_memory(pack)
958
1535
        # record the newly available packs and stop advertising the old
959
1536
        # packs
960
 
        to_be_obsoleted = []
961
 
        for _, packs in pack_operations:
962
 
            to_be_obsoleted.extend(packs)
963
 
        result = self._save_pack_names(clear_obsolete_packs=True,
964
 
                                       obsolete_packs=to_be_obsoleted)
965
 
        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)
966
1541
 
967
1542
    def _flush_new_pack(self):
968
1543
        if self._new_pack is not None:
978
1553
 
979
1554
    def _already_packed(self):
980
1555
        """Is the collection already packed?"""
981
 
        return not (self.repo._format.pack_compresses or (len(self._names) > 1))
 
1556
        return len(self._names) < 2
982
1557
 
983
 
    def pack(self, hint=None, clean_obsolete_packs=False):
 
1558
    def pack(self):
984
1559
        """Pack the pack collection totally."""
985
1560
        self.ensure_loaded()
986
1561
        total_packs = len(self._names)
987
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.
988
1566
            return
989
1567
        total_revisions = self.revision_index.combined_index.key_count()
990
1568
        # XXX: the following may want to be a class, to pack with a given
991
1569
        # policy.
992
1570
        mutter('Packing repository %s, which has %d pack files, '
993
 
            'containing %d revisions with hint %r.', self, total_packs,
994
 
            total_revisions, hint)
995
 
        while True:
996
 
            try:
997
 
                self._try_pack_operations(hint)
998
 
            except RetryPackOperations:
999
 
                continue
1000
 
            break
1001
 
 
1002
 
        if clean_obsolete_packs:
1003
 
            self._clear_obsolete_packs()
1004
 
 
1005
 
    def _try_pack_operations(self, hint):
1006
 
        """Calculate the pack operations based on the hint (if any), and
1007
 
        execute them.
1008
 
        """
 
1571
            'containing %d revisions into 1 packs.', self, total_packs,
 
1572
            total_revisions)
1009
1573
        # determine which packs need changing
 
1574
        pack_distribution = [1]
1010
1575
        pack_operations = [[0, []]]
1011
1576
        for pack in self.all_packs():
1012
 
            if hint is None or pack.name in hint:
1013
 
                # Either no hint was provided (so we are packing everything),
1014
 
                # or this pack was included in the hint.
1015
 
                pack_operations[-1][0] += pack.get_revision_count()
1016
 
                pack_operations[-1][1].append(pack)
1017
 
        self._execute_pack_operations(pack_operations,
1018
 
            packer_class=self.optimising_packer_class,
1019
 
            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)
1020
1580
 
1021
1581
    def plan_autopack_combinations(self, existing_packs, pack_distribution):
1022
1582
        """Plan a pack operation.
1032
1592
        pack_operations = [[0, []]]
1033
1593
        # plan out what packs to keep, and what to reorganise
1034
1594
        while len(existing_packs):
1035
 
            # 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
1036
1596
            # distribution chart we will include its contents in the new pack
1037
 
            # 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
1038
1598
            # distribution chart
1039
1599
            next_pack_rev_count, next_pack = existing_packs.pop(0)
1040
1600
            if next_pack_rev_count >= pack_distribution[0]:
1075
1635
 
1076
1636
        :return: True if the disk names had not been previously read.
1077
1637
        """
1078
 
        # 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
1079
1639
        # an unlocked repo. Naughty.
1080
1640
        if not self.repo.is_locked():
1081
1641
            raise errors.ObjectNotLocked(self.repo)
1111
1671
            txt_index = self._make_index(name, '.tix')
1112
1672
            sig_index = self._make_index(name, '.six')
1113
1673
            if self.chk_index is not None:
1114
 
                chk_index = self._make_index(name, '.cix', is_chk=True)
 
1674
                chk_index = self._make_index(name, '.cix')
1115
1675
            else:
1116
1676
                chk_index = None
1117
1677
            result = ExistingPack(self._pack_transport, name, rev_index,
1136
1696
            txt_index = self._make_index(name, '.tix', resume=True)
1137
1697
            sig_index = self._make_index(name, '.six', resume=True)
1138
1698
            if self.chk_index is not None:
1139
 
                chk_index = self._make_index(name, '.cix', resume=True,
1140
 
                                             is_chk=True)
 
1699
                chk_index = self._make_index(name, '.cix', resume=True)
1141
1700
            else:
1142
1701
                chk_index = None
1143
1702
            result = self.resumed_pack_factory(name, rev_index, inv_index,
1173
1732
        return self._index_class(self.transport, 'pack-names', None
1174
1733
                ).iter_all_entries()
1175
1734
 
1176
 
    def _make_index(self, name, suffix, resume=False, is_chk=False):
 
1735
    def _make_index(self, name, suffix, resume=False):
1177
1736
        size_offset = self._suffix_offsets[suffix]
1178
1737
        index_name = name + suffix
1179
1738
        if resume:
1182
1741
        else:
1183
1742
            transport = self._index_transport
1184
1743
            index_size = self._names[name][size_offset]
1185
 
        index = self._index_class(transport, index_name, index_size,
1186
 
                                  unlimited_cache=is_chk)
1187
 
        if is_chk and self._index_class is btree_index.BTreeGraphIndex: 
1188
 
            index._leaf_factory = btree_index._gcchk_factory
1189
 
        return index
 
1744
        return self._index_class(transport, index_name, index_size)
1190
1745
 
1191
1746
    def _max_pack_count(self, total_revisions):
1192
1747
        """Return the maximum number of packs to use for total revisions.
1220
1775
        :param return: None.
1221
1776
        """
1222
1777
        for pack in packs:
1223
 
            try:
1224
 
                pack.pack_transport.move(pack.file_name(),
1225
 
                    '../obsolete_packs/' + pack.file_name())
1226
 
            except (errors.PathError, errors.TransportError), e:
1227
 
                # TODO: Should these be warnings or mutters?
1228
 
                mutter("couldn't rename obsolete pack, skipping it:\n%s"
1229
 
                       % (e,))
 
1778
            pack.pack_transport.rename(pack.file_name(),
 
1779
                '../obsolete_packs/' + pack.file_name())
1230
1780
            # TODO: Probably needs to know all possible indices for this pack
1231
1781
            # - or maybe list the directory and move all indices matching this
1232
1782
            # name whether we recognize it or not?
1234
1784
            if self.chk_index is not None:
1235
1785
                suffixes.append('.cix')
1236
1786
            for suffix in suffixes:
1237
 
                try:
1238
 
                    self._index_transport.move(pack.name + suffix,
1239
 
                        '../obsolete_packs/' + pack.name + suffix)
1240
 
                except (errors.PathError, errors.TransportError), e:
1241
 
                    mutter("couldn't rename obsolete index, skipping it:\n%s"
1242
 
                           % (e,))
 
1787
                self._index_transport.rename(pack.name + suffix,
 
1788
                    '../obsolete_packs/' + pack.name + suffix)
1243
1789
 
1244
1790
    def pack_distribution(self, total_revisions):
1245
1791
        """Generate a list of the number of revisions to put in each pack.
1271
1817
        self._remove_pack_indices(pack)
1272
1818
        self.packs.remove(pack)
1273
1819
 
1274
 
    def _remove_pack_indices(self, pack, ignore_missing=False):
1275
 
        """Remove the indices for pack from the aggregated indices.
1276
 
        
1277
 
        :param ignore_missing: Suppress KeyErrors from calling remove_index.
1278
 
        """
1279
 
        for index_type in Pack.index_definitions.keys():
1280
 
            attr_name = index_type + '_index'
1281
 
            aggregate_index = getattr(self, attr_name)
1282
 
            if aggregate_index is not None:
1283
 
                pack_index = getattr(pack, attr_name)
1284
 
                try:
1285
 
                    aggregate_index.remove_index(pack_index)
1286
 
                except KeyError:
1287
 
                    if ignore_missing:
1288
 
                        continue
1289
 
                    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)
1290
1828
 
1291
1829
    def reset(self):
1292
1830
        """Clear all cached data."""
1325
1863
        disk_nodes = set()
1326
1864
        for index, key, value in self._iter_disk_pack_index():
1327
1865
            disk_nodes.add((key, value))
1328
 
        orig_disk_nodes = set(disk_nodes)
1329
1866
 
1330
1867
        # do a two-way diff against our original content
1331
1868
        current_nodes = set()
1344
1881
        disk_nodes.difference_update(deleted_nodes)
1345
1882
        disk_nodes.update(new_nodes)
1346
1883
 
1347
 
        return disk_nodes, deleted_nodes, new_nodes, orig_disk_nodes
 
1884
        return disk_nodes, deleted_nodes, new_nodes
1348
1885
 
1349
1886
    def _syncronize_pack_names_from_disk_nodes(self, disk_nodes):
1350
1887
        """Given the correct set of pack files, update our saved info.
1378
1915
                    # disk index because the set values are the same, unless
1379
1916
                    # the only index shows up as deleted by the set difference
1380
1917
                    # - which it may. Until there is a specific test for this,
1381
 
                    # assume it's broken. RBC 20071017.
 
1918
                    # assume its broken. RBC 20071017.
1382
1919
                    self._remove_pack_from_memory(self.get_pack_by_name(name))
1383
1920
                    self._names[name] = sizes
1384
1921
                    self.get_pack_by_name(name)
1390
1927
                added.append(name)
1391
1928
        return removed, added, modified
1392
1929
 
1393
 
    def _save_pack_names(self, clear_obsolete_packs=False, obsolete_packs=None):
 
1930
    def _save_pack_names(self, clear_obsolete_packs=False):
1394
1931
        """Save the list of packs.
1395
1932
 
1396
1933
        This will take out the mutex around the pack names list for the
1400
1937
 
1401
1938
        :param clear_obsolete_packs: If True, clear out the contents of the
1402
1939
            obsolete_packs directory.
1403
 
        :param obsolete_packs: Packs that are obsolete once the new pack-names
1404
 
            file has been written.
1405
 
        :return: A list of the names saved that were not previously on disk.
1406
1940
        """
1407
 
        already_obsolete = []
1408
1941
        self.lock_names()
1409
1942
        try:
1410
1943
            builder = self._index_builder_class()
1411
 
            (disk_nodes, deleted_nodes, new_nodes,
1412
 
             orig_disk_nodes) = self._diff_pack_names()
 
1944
            disk_nodes, deleted_nodes, new_nodes = self._diff_pack_names()
1413
1945
            # TODO: handle same-name, index-size-changes here -
1414
1946
            # e.g. use the value from disk, not ours, *unless* we're the one
1415
1947
            # changing it.
1417
1949
                builder.add_node(key, value)
1418
1950
            self.transport.put_file('pack-names', builder.finish(),
1419
1951
                mode=self.repo.bzrdir._get_file_mode())
 
1952
            # move the baseline forward
1420
1953
            self._packs_at_load = disk_nodes
1421
1954
            if clear_obsolete_packs:
1422
 
                to_preserve = None
1423
 
                if obsolete_packs:
1424
 
                    to_preserve = set([o.name for o in obsolete_packs])
1425
 
                already_obsolete = self._clear_obsolete_packs(to_preserve)
 
1955
                self._clear_obsolete_packs()
1426
1956
        finally:
1427
1957
            self._unlock_names()
1428
1958
        # synchronise the memory packs list with what we just wrote:
1429
1959
        self._syncronize_pack_names_from_disk_nodes(disk_nodes)
1430
 
        if obsolete_packs:
1431
 
            # TODO: We could add one more condition here. "if o.name not in
1432
 
            #       orig_disk_nodes and o != the new_pack we haven't written to
1433
 
            #       disk yet. However, the new pack object is not easily
1434
 
            #       accessible here (it would have to be passed through the
1435
 
            #       autopacking code, etc.)
1436
 
            obsolete_packs = [o for o in obsolete_packs
1437
 
                              if o.name not in already_obsolete]
1438
 
            self._obsolete_packs(obsolete_packs)
1439
 
        return [new_node[0][0] for new_node in new_nodes]
1440
1960
 
1441
1961
    def reload_pack_names(self):
1442
1962
        """Sync our pack listing with what is present in the repository.
1449
1969
        """
1450
1970
        # The ensure_loaded call is to handle the case where the first call
1451
1971
        # made involving the collection was to reload_pack_names, where we 
1452
 
        # don't have a view of disk contents. It's a bit of a bandaid, and
1453
 
        # causes two reads of pack-names, but it's a rare corner case not
1454
 
        # 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.
1455
1975
        first_read = self.ensure_loaded()
1456
1976
        if first_read:
1457
1977
            return True
1458
1978
        # out the new value.
1459
 
        (disk_nodes, deleted_nodes, new_nodes,
1460
 
         orig_disk_nodes) = self._diff_pack_names()
1461
 
        # _packs_at_load is meant to be the explicit list of names in
1462
 
        # 'pack-names' at then start. As such, it should not contain any
1463
 
        # pending names that haven't been written out yet.
1464
 
        self._packs_at_load = orig_disk_nodes
 
1979
        disk_nodes, _, _ = self._diff_pack_names()
 
1980
        self._packs_at_load = disk_nodes
1465
1981
        (removed, added,
1466
1982
         modified) = self._syncronize_pack_names_from_disk_nodes(disk_nodes)
1467
1983
        if removed or added or modified:
1476
1992
            raise
1477
1993
        raise errors.RetryAutopack(self.repo, False, sys.exc_info())
1478
1994
 
1479
 
    def _restart_pack_operations(self):
1480
 
        """Reload the pack names list, and restart the autopack code."""
1481
 
        if not self.reload_pack_names():
1482
 
            # Re-raise the original exception, because something went missing
1483
 
            # and a restart didn't find it
1484
 
            raise
1485
 
        raise RetryPackOperations(self.repo, False, sys.exc_info())
1486
 
 
1487
 
    def _clear_obsolete_packs(self, preserve=None):
 
1995
    def _clear_obsolete_packs(self):
1488
1996
        """Delete everything from the obsolete-packs directory.
1489
 
 
1490
 
        :return: A list of pack identifiers (the filename without '.pack') that
1491
 
            were found in obsolete_packs.
1492
1997
        """
1493
 
        found = []
1494
1998
        obsolete_pack_transport = self.transport.clone('obsolete_packs')
1495
 
        if preserve is None:
1496
 
            preserve = set()
1497
1999
        for filename in obsolete_pack_transport.list_dir('.'):
1498
 
            name, ext = osutils.splitext(filename)
1499
 
            if ext == '.pack':
1500
 
                found.append(name)
1501
 
            if name in preserve:
1502
 
                continue
1503
2000
            try:
1504
2001
                obsolete_pack_transport.delete(filename)
1505
2002
            except (errors.PathError, errors.TransportError), e:
1506
 
                warning("couldn't delete obsolete pack, skipping it:\n%s"
1507
 
                        % (e,))
1508
 
        return found
 
2003
                warning("couldn't delete obsolete pack, skipping it:\n%s" % (e,))
1509
2004
 
1510
2005
    def _start_write_group(self):
1511
2006
        # Do not permit preparation for writing if we're not in a 'write lock'.
1538
2033
        # FIXME: just drop the transient index.
1539
2034
        # forget what names there are
1540
2035
        if self._new_pack is not None:
1541
 
            operation = cleanup.OperationWithCleanups(self._new_pack.abort)
1542
 
            operation.add_cleanup(setattr, self, '_new_pack', None)
1543
 
            # If we aborted while in the middle of finishing the write
1544
 
            # group, _remove_pack_indices could fail because the indexes are
1545
 
            # already gone.  But they're not there we shouldn't fail in this
1546
 
            # case, so we pass ignore_missing=True.
1547
 
            operation.add_cleanup(self._remove_pack_indices, self._new_pack,
1548
 
                ignore_missing=True)
1549
 
            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
1550
2045
        for resumed_pack in self._resumed_packs:
1551
 
            operation = cleanup.OperationWithCleanups(resumed_pack.abort)
1552
 
            # See comment in previous finally block.
1553
 
            operation.add_cleanup(self._remove_pack_indices, resumed_pack,
1554
 
                ignore_missing=True)
1555
 
            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
1556
2054
        del self._resumed_packs[:]
1557
2055
 
1558
2056
    def _remove_resumed_pack_indices(self):
1560
2058
            self._remove_pack_indices(resumed_pack)
1561
2059
        del self._resumed_packs[:]
1562
2060
 
1563
 
    def _check_new_inventories(self):
1564
 
        """Detect missing inventories in this write group.
1565
 
 
1566
 
        :returns: list of strs, summarising any problems found.  If the list is
1567
 
            empty no problems were found.
1568
 
        """
1569
 
        # The base implementation does no checks.  GCRepositoryPackCollection
1570
 
        # overrides this.
1571
 
        return []
1572
 
        
1573
2061
    def _commit_write_group(self):
1574
2062
        all_missing = set()
1575
2063
        for prefix, versioned_file in (
1584
2072
            raise errors.BzrCheckError(
1585
2073
                "Repository %s has missing compression parent(s) %r "
1586
2074
                 % (self.repo, sorted(all_missing)))
1587
 
        problems = self._check_new_inventories()
1588
 
        if problems:
1589
 
            problems_summary = '\n'.join(problems)
1590
 
            raise errors.BzrCheckError(
1591
 
                "Cannot add revision(s) to repository: " + problems_summary)
1592
2075
        self._remove_pack_indices(self._new_pack)
1593
 
        any_new_content = False
 
2076
        should_autopack = False
1594
2077
        if self._new_pack.data_inserted():
1595
2078
            # get all the data to disk and read to use
1596
2079
            self._new_pack.finish()
1597
2080
            self.allocate(self._new_pack)
1598
2081
            self._new_pack = None
1599
 
            any_new_content = True
 
2082
            should_autopack = True
1600
2083
        else:
1601
2084
            self._new_pack.abort()
1602
2085
            self._new_pack = None
1607
2090
            self._remove_pack_from_memory(resumed_pack)
1608
2091
            resumed_pack.finish()
1609
2092
            self.allocate(resumed_pack)
1610
 
            any_new_content = True
 
2093
            should_autopack = True
1611
2094
        del self._resumed_packs[:]
1612
 
        if any_new_content:
1613
 
            result = self.autopack()
1614
 
            if not result:
 
2095
        if should_autopack:
 
2096
            if not self.autopack():
1615
2097
                # when autopack takes no steps, the names list is still
1616
2098
                # unsaved.
1617
 
                return self._save_pack_names()
1618
 
            return result
1619
 
        return []
 
2099
                self._save_pack_names()
1620
2100
 
1621
2101
    def _suspend_write_group(self):
1622
2102
        tokens = [pack.name for pack in self._resumed_packs]
1637
2117
            self._resume_pack(token)
1638
2118
 
1639
2119
 
1640
 
class PackRepository(MetaDirVersionedFileRepository):
 
2120
class KnitPackRepository(KnitRepository):
1641
2121
    """Repository with knit objects stored inside pack containers.
1642
2122
 
1643
2123
    The layering for a KnitPackRepository is:
1646
2126
    ===================================================
1647
2127
    Tuple based apis below, string based, and key based apis above
1648
2128
    ---------------------------------------------------
1649
 
    VersionedFiles
 
2129
    KnitVersionedFiles
1650
2130
      Provides .texts, .revisions etc
1651
2131
      This adapts the N-tuple keys to physical knit records which only have a
1652
2132
      single string identifier (for historical reasons), which in older formats
1662
2142
 
1663
2143
    """
1664
2144
 
1665
 
    # These attributes are inherited from the Repository base class. Setting
1666
 
    # them to None ensures that if the constructor is changed to not initialize
1667
 
    # them, or a subclass fails to call the constructor, that an error will
1668
 
    # occur rather than the system working but generating incorrect data.
1669
 
    _commit_builder_class = None
1670
 
    _serializer = None
1671
 
 
1672
2145
    def __init__(self, _format, a_bzrdir, control_files, _commit_builder_class,
1673
2146
        _serializer):
1674
 
        MetaDirRepository.__init__(self, _format, a_bzrdir, control_files)
1675
 
        self._commit_builder_class = _commit_builder_class
1676
 
        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
1677
2204
        self._reconcile_fixes_text_parents = True
1678
 
        if self._format.supports_external_lookups:
1679
 
            self._unstacked_provider = graph.CachingParentsProvider(
1680
 
                self._make_parents_provider_unstacked())
1681
 
        else:
1682
 
            self._unstacked_provider = graph.CachingParentsProvider(self)
1683
 
        self._unstacked_provider.disable_cache()
 
2205
        self._reconcile_backsup_inventory = False
1684
2206
 
1685
 
    @needs_read_lock
1686
 
    def _all_revision_ids(self):
1687
 
        """See Repository.all_revision_ids()."""
1688
 
        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))
1689
2217
 
1690
2218
    def _abort_write_group(self):
1691
 
        self.revisions._index._key_dependencies.clear()
 
2219
        self.revisions._index._key_dependencies.refs.clear()
1692
2220
        self._pack_collection._abort_write_group()
1693
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
 
1694
2268
    def _make_parents_provider(self):
1695
 
        if not self._format.supports_external_lookups:
1696
 
            return self._unstacked_provider
1697
 
        return graph.StackedParentsProvider(_LazyListJoin(
1698
 
            [self._unstacked_provider], self._fallback_repositories))
 
2269
        return graph.CachingParentsProvider(self)
1699
2270
 
1700
2271
    def _refresh_data(self):
1701
2272
        if not self.is_locked():
1702
2273
            return
1703
2274
        self._pack_collection.reload_pack_names()
1704
 
        self._unstacked_provider.disable_cache()
1705
 
        self._unstacked_provider.enable_cache()
1706
2275
 
1707
2276
    def _start_write_group(self):
1708
2277
        self._pack_collection._start_write_group()
1709
2278
 
1710
2279
    def _commit_write_group(self):
1711
 
        hint = self._pack_collection._commit_write_group()
1712
 
        self.revisions._index._key_dependencies.clear()
1713
 
        # The commit may have added keys that were previously cached as
1714
 
        # missing, so reset the cache.
1715
 
        self._unstacked_provider.disable_cache()
1716
 
        self._unstacked_provider.enable_cache()
1717
 
        return hint
 
2280
        self.revisions._index._key_dependencies.refs.clear()
 
2281
        return self._pack_collection._commit_write_group()
1718
2282
 
1719
2283
    def suspend_write_group(self):
1720
2284
        # XXX check self._write_group is self.get_transaction()?
1721
2285
        tokens = self._pack_collection._suspend_write_group()
1722
 
        self.revisions._index._key_dependencies.clear()
 
2286
        self.revisions._index._key_dependencies.refs.clear()
1723
2287
        self._write_group = None
1724
2288
        return tokens
1725
2289
 
1746
2310
        return self._write_lock_count
1747
2311
 
1748
2312
    def lock_write(self, token=None):
1749
 
        """Lock the repository for writes.
1750
 
 
1751
 
        :return: A bzrlib.repository.RepositoryWriteLockResult.
1752
 
        """
1753
2313
        locked = self.is_locked()
1754
2314
        if not self._write_lock_count and locked:
1755
2315
            raise errors.ReadOnlyError(self)
1757
2317
        if self._write_lock_count == 1:
1758
2318
            self._transaction = transactions.WriteTransaction()
1759
2319
        if not locked:
1760
 
            if 'relock' in debug.debug_flags and self._prev_lock == 'w':
1761
 
                note('%r was write locked again', self)
1762
 
            self._prev_lock = 'w'
1763
 
            self._unstacked_provider.enable_cache()
1764
2320
            for repo in self._fallback_repositories:
1765
2321
                # Writes don't affect fallback repos
1766
2322
                repo.lock_read()
1767
2323
            self._refresh_data()
1768
 
        return RepositoryWriteLockResult(self.unlock, None)
1769
2324
 
1770
2325
    def lock_read(self):
1771
 
        """Lock the repository for reads.
1772
 
 
1773
 
        :return: A bzrlib.lock.LogicalLockResult.
1774
 
        """
1775
2326
        locked = self.is_locked()
1776
2327
        if self._write_lock_count:
1777
2328
            self._write_lock_count += 1
1778
2329
        else:
1779
2330
            self.control_files.lock_read()
1780
2331
        if not locked:
1781
 
            if 'relock' in debug.debug_flags and self._prev_lock == 'r':
1782
 
                note('%r was read locked again', self)
1783
 
            self._prev_lock = 'r'
1784
 
            self._unstacked_provider.enable_cache()
1785
2332
            for repo in self._fallback_repositories:
1786
2333
                repo.lock_read()
1787
2334
            self._refresh_data()
1788
 
        return LogicalLockResult(self.unlock)
1789
2335
 
1790
2336
    def leave_lock_in_place(self):
1791
2337
        # not supported - raise an error
1796
2342
        raise NotImplementedError(self.dont_leave_lock_in_place)
1797
2343
 
1798
2344
    @needs_write_lock
1799
 
    def pack(self, hint=None, clean_obsolete_packs=False):
 
2345
    def pack(self):
1800
2346
        """Compress the data within the repository.
1801
2347
 
1802
2348
        This will pack all the data to a single pack. In future it may
1803
2349
        recompress deltas or do other such expensive operations.
1804
2350
        """
1805
 
        self._pack_collection.pack(hint=hint, clean_obsolete_packs=clean_obsolete_packs)
 
2351
        self._pack_collection.pack()
1806
2352
 
1807
2353
    @needs_write_lock
1808
2354
    def reconcile(self, other=None, thorough=False):
1813
2359
        return reconciler
1814
2360
 
1815
2361
    def _reconcile_pack(self, collection, packs, extension, revs, pb):
1816
 
        raise NotImplementedError(self._reconcile_pack)
 
2362
        packer = ReconcilePacker(collection, packs, extension, revs)
 
2363
        return packer.pack(pb)
1817
2364
 
1818
 
    @only_raises(errors.LockNotHeld, errors.LockBroken)
1819
2365
    def unlock(self):
1820
2366
        if self._write_lock_count == 1 and self._write_group is not None:
1821
2367
            self.abort_write_group()
1822
 
            self._unstacked_provider.disable_cache()
1823
2368
            self._transaction = None
1824
2369
            self._write_lock_count = 0
1825
2370
            raise errors.BzrError(
1835
2380
            self.control_files.unlock()
1836
2381
 
1837
2382
        if not self.is_locked():
1838
 
            self._unstacked_provider.disable_cache()
1839
2383
            for repo in self._fallback_repositories:
1840
2384
                repo.unlock()
1841
2385
 
1842
2386
 
1843
 
class RepositoryFormatPack(MetaDirVersionedFileRepositoryFormat):
 
2387
class RepositoryFormatPack(MetaDirRepositoryFormat):
1844
2388
    """Format logic for pack structured repositories.
1845
2389
 
1846
2390
    This repository format has:
1876
2420
    index_class = None
1877
2421
    _fetch_uses_deltas = True
1878
2422
    fast_deltas = False
1879
 
    supports_funky_characters = True
1880
 
    revision_graph_can_have_wrong_parents = True
1881
2423
 
1882
2424
    def initialize(self, a_bzrdir, shared=False):
1883
2425
        """Create a pack based repository.
1894
2436
        utf8_files = [('format', self.get_format_string())]
1895
2437
 
1896
2438
        self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1897
 
        repository = self.open(a_bzrdir=a_bzrdir, _found=True)
1898
 
        self._run_post_repo_init_hooks(repository, a_bzrdir, shared)
1899
 
        return repository
 
2439
        return self.open(a_bzrdir=a_bzrdir, _found=True)
1900
2440
 
1901
2441
    def open(self, a_bzrdir, _found=False, _override_transport=None):
1902
2442
        """See RepositoryFormat.open().
1920
2460
                              _serializer=self._serializer)
1921
2461
 
1922
2462
 
1923
 
class RetryPackOperations(errors.RetryWithNewPacks):
1924
 
    """Raised when we are packing and we find a missing file.
1925
 
 
1926
 
    Meant as a signaling exception, to tell the RepositoryPackCollection.pack
1927
 
    code it should try again.
1928
 
    """
1929
 
 
1930
 
    internal_error = True
1931
 
 
1932
 
    _fmt = ("Pack files have changed, reload and try pack again."
1933
 
            " context: %(context)s %(orig_error)s")
1934
 
 
1935
 
 
1936
 
class _DirectPackAccess(object):
1937
 
    """Access to data in one or more packs with less translation."""
1938
 
 
1939
 
    def __init__(self, index_to_packs, reload_func=None, flush_func=None):
1940
 
        """Create a _DirectPackAccess object.
1941
 
 
1942
 
        :param index_to_packs: A dict mapping index objects to the transport
1943
 
            and file names for obtaining data.
1944
 
        :param reload_func: A function to call if we determine that the pack
1945
 
            files have moved and we need to reload our caches. See
1946
 
            bzrlib.repo_fmt.pack_repo.AggregateIndex for more details.
1947
 
        """
1948
 
        self._container_writer = None
1949
 
        self._write_index = None
1950
 
        self._indices = index_to_packs
1951
 
        self._reload_func = reload_func
1952
 
        self._flush_func = flush_func
1953
 
 
1954
 
    def add_raw_records(self, key_sizes, raw_data):
1955
 
        """Add raw knit bytes to a storage area.
1956
 
 
1957
 
        The data is spooled to the container writer in one bytes-record per
1958
 
        raw data item.
1959
 
 
1960
 
        :param sizes: An iterable of tuples containing the key and size of each
1961
 
            raw data segment.
1962
 
        :param raw_data: A bytestring containing the data.
1963
 
        :return: A list of memos to retrieve the record later. Each memo is an
1964
 
            opaque index memo. For _DirectPackAccess the memo is (index, pos,
1965
 
            length), where the index field is the write_index object supplied
1966
 
            to the PackAccess object.
1967
 
        """
1968
 
        if type(raw_data) is not str:
1969
 
            raise AssertionError(
1970
 
                'data must be plain bytes was %s' % type(raw_data))
1971
 
        result = []
1972
 
        offset = 0
1973
 
        for key, size in key_sizes:
1974
 
            p_offset, p_length = self._container_writer.add_bytes_record(
1975
 
                raw_data[offset:offset+size], [])
1976
 
            offset += size
1977
 
            result.append((self._write_index, p_offset, p_length))
1978
 
        return result
1979
 
 
1980
 
    def flush(self):
1981
 
        """Flush pending writes on this access object.
1982
 
 
1983
 
        This will flush any buffered writes to a NewPack.
1984
 
        """
1985
 
        if self._flush_func is not None:
1986
 
            self._flush_func()
1987
 
 
1988
 
    def get_raw_records(self, memos_for_retrieval):
1989
 
        """Get the raw bytes for a records.
1990
 
 
1991
 
        :param memos_for_retrieval: An iterable containing the (index, pos,
1992
 
            length) memo for retrieving the bytes. The Pack access method
1993
 
            looks up the pack to use for a given record in its index_to_pack
1994
 
            map.
1995
 
        :return: An iterator over the bytes of the records.
1996
 
        """
1997
 
        # first pass, group into same-index requests
1998
 
        request_lists = []
1999
 
        current_index = None
2000
 
        for (index, offset, length) in memos_for_retrieval:
2001
 
            if current_index == index:
2002
 
                current_list.append((offset, length))
2003
 
            else:
2004
 
                if current_index is not None:
2005
 
                    request_lists.append((current_index, current_list))
2006
 
                current_index = index
2007
 
                current_list = [(offset, length)]
2008
 
        # handle the last entry
2009
 
        if current_index is not None:
2010
 
            request_lists.append((current_index, current_list))
2011
 
        for index, offsets in request_lists:
2012
 
            try:
2013
 
                transport, path = self._indices[index]
2014
 
            except KeyError:
2015
 
                # A KeyError here indicates that someone has triggered an index
2016
 
                # reload, and this index has gone missing, we need to start
2017
 
                # over.
2018
 
                if self._reload_func is None:
2019
 
                    # If we don't have a _reload_func there is nothing that can
2020
 
                    # be done
2021
 
                    raise
2022
 
                raise errors.RetryWithNewPacks(index,
2023
 
                                               reload_occurred=True,
2024
 
                                               exc_info=sys.exc_info())
2025
 
            try:
2026
 
                reader = pack.make_readv_reader(transport, path, offsets)
2027
 
                for names, read_func in reader.iter_records():
2028
 
                    yield read_func(None)
2029
 
            except errors.NoSuchFile:
2030
 
                # A NoSuchFile error indicates that a pack file has gone
2031
 
                # missing on disk, we need to trigger a reload, and start over.
2032
 
                if self._reload_func is None:
2033
 
                    raise
2034
 
                raise errors.RetryWithNewPacks(transport.abspath(path),
2035
 
                                               reload_occurred=False,
2036
 
                                               exc_info=sys.exc_info())
2037
 
 
2038
 
    def set_writer(self, writer, index, transport_packname):
2039
 
        """Set a writer to use for adding data."""
2040
 
        if index is not None:
2041
 
            self._indices[index] = transport_packname
2042
 
        self._container_writer = writer
2043
 
        self._write_index = index
2044
 
 
2045
 
    def reload_or_raise(self, retry_exc):
2046
 
        """Try calling the reload function, or re-raise the original exception.
2047
 
 
2048
 
        This should be called after _DirectPackAccess raises a
2049
 
        RetryWithNewPacks exception. This function will handle the common logic
2050
 
        of determining when the error is fatal versus being temporary.
2051
 
        It will also make sure that the original exception is raised, rather
2052
 
        than the RetryWithNewPacks exception.
2053
 
 
2054
 
        If this function returns, then the calling function should retry
2055
 
        whatever operation was being performed. Otherwise an exception will
2056
 
        be raised.
2057
 
 
2058
 
        :param retry_exc: A RetryWithNewPacks exception.
2059
 
        """
2060
 
        is_error = False
2061
 
        if self._reload_func is None:
2062
 
            is_error = True
2063
 
        elif not self._reload_func():
2064
 
            # The reload claimed that nothing changed
2065
 
            if not retry_exc.reload_occurred:
2066
 
                # If there wasn't an earlier reload, then we really were
2067
 
                # expecting to find changes. We didn't find them, so this is a
2068
 
                # hard error
2069
 
                is_error = True
2070
 
        if is_error:
2071
 
            exc_class, exc_value, exc_traceback = retry_exc.exc_info
2072
 
            raise exc_class, exc_value, exc_traceback
2073
 
 
2074
 
 
 
2463
class RepositoryFormatKnitPack1(RepositoryFormatPack):
 
2464
    """A no-subtrees parameterized Pack repository.
 
2465
 
 
2466
    This format was introduced in 0.92.
 
2467
    """
 
2468
 
 
2469
    repository_class = KnitPackRepository
 
2470
    _commit_builder_class = PackCommitBuilder
 
2471
    @property
 
2472
    def _serializer(self):
 
2473
        return xml5.serializer_v5
 
2474
    # What index classes to use
 
2475
    index_builder_class = InMemoryGraphIndex
 
2476
    index_class = GraphIndex
 
2477
 
 
2478
    def _get_matching_bzrdir(self):
 
2479
        return bzrdir.format_registry.make_bzrdir('pack-0.92')
 
2480
 
 
2481
    def _ignore_setting_bzrdir(self, format):
 
2482
        pass
 
2483
 
 
2484
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2485
 
 
2486
    def get_format_string(self):
 
2487
        """See RepositoryFormat.get_format_string()."""
 
2488
        return "Bazaar pack repository format 1 (needs bzr 0.92)\n"
 
2489
 
 
2490
    def get_format_description(self):
 
2491
        """See RepositoryFormat.get_format_description()."""
 
2492
        return "Packs containing knits without subtree support"
 
2493
 
 
2494
    def check_conversion_target(self, target_format):
 
2495
        pass
 
2496
 
 
2497
 
 
2498
class RepositoryFormatKnitPack3(RepositoryFormatPack):
 
2499
    """A subtrees parameterized Pack repository.
 
2500
 
 
2501
    This repository format uses the xml7 serializer to get:
 
2502
     - support for recording full info about the tree root
 
2503
     - support for recording tree-references
 
2504
 
 
2505
    This format was introduced in 0.92.
 
2506
    """
 
2507
 
 
2508
    repository_class = KnitPackRepository
 
2509
    _commit_builder_class = PackRootCommitBuilder
 
2510
    rich_root_data = True
 
2511
    supports_tree_reference = True
 
2512
    @property
 
2513
    def _serializer(self):
 
2514
        return xml7.serializer_v7
 
2515
    # What index classes to use
 
2516
    index_builder_class = InMemoryGraphIndex
 
2517
    index_class = GraphIndex
 
2518
 
 
2519
    def _get_matching_bzrdir(self):
 
2520
        return bzrdir.format_registry.make_bzrdir(
 
2521
            'pack-0.92-subtree')
 
2522
 
 
2523
    def _ignore_setting_bzrdir(self, format):
 
2524
        pass
 
2525
 
 
2526
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2527
 
 
2528
    def check_conversion_target(self, target_format):
 
2529
        if not target_format.rich_root_data:
 
2530
            raise errors.BadConversionTarget(
 
2531
                'Does not support rich root data.', target_format)
 
2532
        if not getattr(target_format, 'supports_tree_reference', False):
 
2533
            raise errors.BadConversionTarget(
 
2534
                'Does not support nested trees', target_format)
 
2535
 
 
2536
    def get_format_string(self):
 
2537
        """See RepositoryFormat.get_format_string()."""
 
2538
        return "Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n"
 
2539
 
 
2540
    def get_format_description(self):
 
2541
        """See RepositoryFormat.get_format_description()."""
 
2542
        return "Packs containing knits with subtree support\n"
 
2543
 
 
2544
 
 
2545
class RepositoryFormatKnitPack4(RepositoryFormatPack):
 
2546
    """A rich-root, no subtrees parameterized Pack repository.
 
2547
 
 
2548
    This repository format uses the xml6 serializer to get:
 
2549
     - support for recording full info about the tree root
 
2550
 
 
2551
    This format was introduced in 1.0.
 
2552
    """
 
2553
 
 
2554
    repository_class = KnitPackRepository
 
2555
    _commit_builder_class = PackRootCommitBuilder
 
2556
    rich_root_data = True
 
2557
    supports_tree_reference = False
 
2558
    @property
 
2559
    def _serializer(self):
 
2560
        return xml6.serializer_v6
 
2561
    # What index classes to use
 
2562
    index_builder_class = InMemoryGraphIndex
 
2563
    index_class = GraphIndex
 
2564
 
 
2565
    def _get_matching_bzrdir(self):
 
2566
        return bzrdir.format_registry.make_bzrdir(
 
2567
            'rich-root-pack')
 
2568
 
 
2569
    def _ignore_setting_bzrdir(self, format):
 
2570
        pass
 
2571
 
 
2572
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2573
 
 
2574
    def check_conversion_target(self, target_format):
 
2575
        if not target_format.rich_root_data:
 
2576
            raise errors.BadConversionTarget(
 
2577
                'Does not support rich root data.', target_format)
 
2578
 
 
2579
    def get_format_string(self):
 
2580
        """See RepositoryFormat.get_format_string()."""
 
2581
        return ("Bazaar pack repository format 1 with rich root"
 
2582
                " (needs bzr 1.0)\n")
 
2583
 
 
2584
    def get_format_description(self):
 
2585
        """See RepositoryFormat.get_format_description()."""
 
2586
        return "Packs containing knits with rich root support\n"
 
2587
 
 
2588
 
 
2589
class RepositoryFormatKnitPack5(RepositoryFormatPack):
 
2590
    """Repository that supports external references to allow stacking.
 
2591
 
 
2592
    New in release 1.6.
 
2593
 
 
2594
    Supports external lookups, which results in non-truncated ghosts after
 
2595
    reconcile compared to pack-0.92 formats.
 
2596
    """
 
2597
 
 
2598
    repository_class = KnitPackRepository
 
2599
    _commit_builder_class = PackCommitBuilder
 
2600
    supports_external_lookups = True
 
2601
    # What index classes to use
 
2602
    index_builder_class = InMemoryGraphIndex
 
2603
    index_class = GraphIndex
 
2604
 
 
2605
    @property
 
2606
    def _serializer(self):
 
2607
        return xml5.serializer_v5
 
2608
 
 
2609
    def _get_matching_bzrdir(self):
 
2610
        return bzrdir.format_registry.make_bzrdir('1.6')
 
2611
 
 
2612
    def _ignore_setting_bzrdir(self, format):
 
2613
        pass
 
2614
 
 
2615
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2616
 
 
2617
    def get_format_string(self):
 
2618
        """See RepositoryFormat.get_format_string()."""
 
2619
        return "Bazaar RepositoryFormatKnitPack5 (bzr 1.6)\n"
 
2620
 
 
2621
    def get_format_description(self):
 
2622
        """See RepositoryFormat.get_format_description()."""
 
2623
        return "Packs 5 (adds stacking support, requires bzr 1.6)"
 
2624
 
 
2625
    def check_conversion_target(self, target_format):
 
2626
        pass
 
2627
 
 
2628
 
 
2629
class RepositoryFormatKnitPack5RichRoot(RepositoryFormatPack):
 
2630
    """A repository with rich roots and stacking.
 
2631
 
 
2632
    New in release 1.6.1.
 
2633
 
 
2634
    Supports stacking on other repositories, allowing data to be accessed
 
2635
    without being stored locally.
 
2636
    """
 
2637
 
 
2638
    repository_class = KnitPackRepository
 
2639
    _commit_builder_class = PackRootCommitBuilder
 
2640
    rich_root_data = True
 
2641
    supports_tree_reference = False # no subtrees
 
2642
    supports_external_lookups = True
 
2643
    # What index classes to use
 
2644
    index_builder_class = InMemoryGraphIndex
 
2645
    index_class = GraphIndex
 
2646
 
 
2647
    @property
 
2648
    def _serializer(self):
 
2649
        return xml6.serializer_v6
 
2650
 
 
2651
    def _get_matching_bzrdir(self):
 
2652
        return bzrdir.format_registry.make_bzrdir(
 
2653
            '1.6.1-rich-root')
 
2654
 
 
2655
    def _ignore_setting_bzrdir(self, format):
 
2656
        pass
 
2657
 
 
2658
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2659
 
 
2660
    def check_conversion_target(self, target_format):
 
2661
        if not target_format.rich_root_data:
 
2662
            raise errors.BadConversionTarget(
 
2663
                'Does not support rich root data.', target_format)
 
2664
 
 
2665
    def get_format_string(self):
 
2666
        """See RepositoryFormat.get_format_string()."""
 
2667
        return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6.1)\n"
 
2668
 
 
2669
    def get_format_description(self):
 
2670
        return "Packs 5 rich-root (adds stacking support, requires bzr 1.6.1)"
 
2671
 
 
2672
 
 
2673
class RepositoryFormatKnitPack5RichRootBroken(RepositoryFormatPack):
 
2674
    """A repository with rich roots and external references.
 
2675
 
 
2676
    New in release 1.6.
 
2677
 
 
2678
    Supports external lookups, which results in non-truncated ghosts after
 
2679
    reconcile compared to pack-0.92 formats.
 
2680
 
 
2681
    This format was deprecated because the serializer it uses accidentally
 
2682
    supported subtrees, when the format was not intended to. This meant that
 
2683
    someone could accidentally fetch from an incorrect repository.
 
2684
    """
 
2685
 
 
2686
    repository_class = KnitPackRepository
 
2687
    _commit_builder_class = PackRootCommitBuilder
 
2688
    rich_root_data = True
 
2689
    supports_tree_reference = False # no subtrees
 
2690
 
 
2691
    supports_external_lookups = True
 
2692
    # What index classes to use
 
2693
    index_builder_class = InMemoryGraphIndex
 
2694
    index_class = GraphIndex
 
2695
 
 
2696
    @property
 
2697
    def _serializer(self):
 
2698
        return xml7.serializer_v7
 
2699
 
 
2700
    def _get_matching_bzrdir(self):
 
2701
        matching = bzrdir.format_registry.make_bzrdir(
 
2702
            '1.6.1-rich-root')
 
2703
        matching.repository_format = self
 
2704
        return matching
 
2705
 
 
2706
    def _ignore_setting_bzrdir(self, format):
 
2707
        pass
 
2708
 
 
2709
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2710
 
 
2711
    def check_conversion_target(self, target_format):
 
2712
        if not target_format.rich_root_data:
 
2713
            raise errors.BadConversionTarget(
 
2714
                'Does not support rich root data.', target_format)
 
2715
 
 
2716
    def get_format_string(self):
 
2717
        """See RepositoryFormat.get_format_string()."""
 
2718
        return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6)\n"
 
2719
 
 
2720
    def get_format_description(self):
 
2721
        return ("Packs 5 rich-root (adds stacking support, requires bzr 1.6)"
 
2722
                " (deprecated)")
 
2723
 
 
2724
 
 
2725
class RepositoryFormatKnitPack6(RepositoryFormatPack):
 
2726
    """A repository with stacking and btree indexes,
 
2727
    without rich roots or subtrees.
 
2728
 
 
2729
    This is equivalent to pack-1.6 with B+Tree indices.
 
2730
    """
 
2731
 
 
2732
    repository_class = KnitPackRepository
 
2733
    _commit_builder_class = PackCommitBuilder
 
2734
    supports_external_lookups = True
 
2735
    # What index classes to use
 
2736
    index_builder_class = BTreeBuilder
 
2737
    index_class = BTreeGraphIndex
 
2738
 
 
2739
    @property
 
2740
    def _serializer(self):
 
2741
        return xml5.serializer_v5
 
2742
 
 
2743
    def _get_matching_bzrdir(self):
 
2744
        return bzrdir.format_registry.make_bzrdir('1.9')
 
2745
 
 
2746
    def _ignore_setting_bzrdir(self, format):
 
2747
        pass
 
2748
 
 
2749
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2750
 
 
2751
    def get_format_string(self):
 
2752
        """See RepositoryFormat.get_format_string()."""
 
2753
        return "Bazaar RepositoryFormatKnitPack6 (bzr 1.9)\n"
 
2754
 
 
2755
    def get_format_description(self):
 
2756
        """See RepositoryFormat.get_format_description()."""
 
2757
        return "Packs 6 (uses btree indexes, requires bzr 1.9)"
 
2758
 
 
2759
    def check_conversion_target(self, target_format):
 
2760
        pass
 
2761
 
 
2762
 
 
2763
class RepositoryFormatKnitPack6RichRoot(RepositoryFormatPack):
 
2764
    """A repository with rich roots, no subtrees, stacking and btree indexes.
 
2765
 
 
2766
    1.6-rich-root with B+Tree indices.
 
2767
    """
 
2768
 
 
2769
    repository_class = KnitPackRepository
 
2770
    _commit_builder_class = PackRootCommitBuilder
 
2771
    rich_root_data = True
 
2772
    supports_tree_reference = False # no subtrees
 
2773
    supports_external_lookups = True
 
2774
    # What index classes to use
 
2775
    index_builder_class = BTreeBuilder
 
2776
    index_class = BTreeGraphIndex
 
2777
 
 
2778
    @property
 
2779
    def _serializer(self):
 
2780
        return xml6.serializer_v6
 
2781
 
 
2782
    def _get_matching_bzrdir(self):
 
2783
        return bzrdir.format_registry.make_bzrdir(
 
2784
            '1.9-rich-root')
 
2785
 
 
2786
    def _ignore_setting_bzrdir(self, format):
 
2787
        pass
 
2788
 
 
2789
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2790
 
 
2791
    def check_conversion_target(self, target_format):
 
2792
        if not target_format.rich_root_data:
 
2793
            raise errors.BadConversionTarget(
 
2794
                'Does not support rich root data.', target_format)
 
2795
 
 
2796
    def get_format_string(self):
 
2797
        """See RepositoryFormat.get_format_string()."""
 
2798
        return "Bazaar RepositoryFormatKnitPack6RichRoot (bzr 1.9)\n"
 
2799
 
 
2800
    def get_format_description(self):
 
2801
        return "Packs 6 rich-root (uses btree indexes, requires bzr 1.9)"
 
2802
 
 
2803
 
 
2804
class RepositoryFormatPackDevelopment2Subtree(RepositoryFormatPack):
 
2805
    """A subtrees development repository.
 
2806
 
 
2807
    This format should be retained until the second release after bzr 1.7.
 
2808
 
 
2809
    1.6.1-subtree[as it might have been] with B+Tree indices.
 
2810
 
 
2811
    This is [now] retained until we have a CHK based subtree format in
 
2812
    development.
 
2813
    """
 
2814
 
 
2815
    repository_class = KnitPackRepository
 
2816
    _commit_builder_class = PackRootCommitBuilder
 
2817
    rich_root_data = True
 
2818
    supports_tree_reference = True
 
2819
    supports_external_lookups = True
 
2820
    # What index classes to use
 
2821
    index_builder_class = BTreeBuilder
 
2822
    index_class = BTreeGraphIndex
 
2823
 
 
2824
    @property
 
2825
    def _serializer(self):
 
2826
        return xml7.serializer_v7
 
2827
 
 
2828
    def _get_matching_bzrdir(self):
 
2829
        return bzrdir.format_registry.make_bzrdir(
 
2830
            'development-subtree')
 
2831
 
 
2832
    def _ignore_setting_bzrdir(self, format):
 
2833
        pass
 
2834
 
 
2835
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2836
 
 
2837
    def check_conversion_target(self, target_format):
 
2838
        if not target_format.rich_root_data:
 
2839
            raise errors.BadConversionTarget(
 
2840
                'Does not support rich root data.', target_format)
 
2841
        if not getattr(target_format, 'supports_tree_reference', False):
 
2842
            raise errors.BadConversionTarget(
 
2843
                'Does not support nested trees', target_format)
 
2844
 
 
2845
    def get_format_string(self):
 
2846
        """See RepositoryFormat.get_format_string()."""
 
2847
        return ("Bazaar development format 2 with subtree support "
 
2848
            "(needs bzr.dev from before 1.8)\n")
 
2849
 
 
2850
    def get_format_description(self):
 
2851
        """See RepositoryFormat.get_format_description()."""
 
2852
        return ("Development repository format, currently the same as "
 
2853
            "1.6.1-subtree with B+Tree indices.\n")
2075
2854