/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/repofmt/groupcompress_repo.py

  • Committer: Marius Kruger
  • Date: 2010-07-10 21:28:56 UTC
  • mto: (5384.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 5385.
  • Revision ID: marius.kruger@enerweb.co.za-20100710212856-uq4ji3go0u5se7hx
* Update documentation
* add NEWS

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2008-2011 Canonical Ltd
 
1
# Copyright (C) 2008, 2009, 2010 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
16
16
 
17
17
"""Repository formats using CHK inventories and groupcompress compression."""
18
18
 
19
 
from __future__ import absolute_import
20
 
 
21
19
import time
22
20
 
23
 
from .. import (
24
 
    controldir,
 
21
from bzrlib import (
 
22
    bzrdir,
 
23
    chk_map,
 
24
    chk_serializer,
25
25
    debug,
26
26
    errors,
 
27
    index as _mod_index,
 
28
    inventory,
 
29
    knit,
27
30
    osutils,
 
31
    pack,
28
32
    revision as _mod_revision,
29
33
    trace,
30
34
    ui,
31
35
    )
32
 
from ..bzr import (
33
 
    chk_map,
34
 
    chk_serializer,
35
 
    index as _mod_index,
36
 
    inventory,
37
 
    pack,
38
 
    versionedfile,
39
 
    )
40
 
from ..bzr.btree_index import (
 
36
from bzrlib.btree_index import (
41
37
    BTreeGraphIndex,
42
38
    BTreeBuilder,
43
39
    )
44
 
from ..bzr.groupcompress import (
 
40
from bzrlib.groupcompress import (
45
41
    _GCGraphIndex,
46
42
    GroupCompressVersionedFiles,
47
43
    )
48
 
from .pack_repo import (
49
 
    _DirectPackAccess,
 
44
from bzrlib.repofmt.pack_repo import (
50
45
    Pack,
51
46
    NewPack,
52
 
    PackRepository,
53
 
    PackCommitBuilder,
 
47
    KnitPackRepository,
 
48
    KnitPackStreamSource,
 
49
    PackRootCommitBuilder,
54
50
    RepositoryPackCollection,
55
51
    RepositoryFormatPack,
56
52
    ResumedPack,
57
53
    Packer,
58
54
    )
59
 
from ..bzr.vf_repository import (
60
 
    StreamSource,
61
 
    )
62
 
from ..sixish import (
63
 
    viewitems,
64
 
    viewvalues,
65
 
    )
66
 
from ..static_tuple import StaticTuple
 
55
from bzrlib.static_tuple import StaticTuple
67
56
 
68
57
 
69
58
class GCPack(NewPack):
91
80
        else:
92
81
            chk_index = None
93
82
        Pack.__init__(self,
94
 
                      # Revisions: parents list, no text compression.
95
 
                      index_builder_class(reference_lists=1),
96
 
                      # Inventory: We want to map compression only, but currently the
97
 
                      # knit code hasn't been updated enough to understand that, so we
98
 
                      # have a regular 2-list index giving parents and compression
99
 
                      # source.
100
 
                      index_builder_class(reference_lists=1),
101
 
                      # Texts: per file graph, for all fileids - so one reference list
102
 
                      # and two elements in the key tuple.
103
 
                      index_builder_class(reference_lists=1, key_elements=2),
104
 
                      # Signatures: Just blobs to store, no compression, no parents
105
 
                      # listing.
106
 
                      index_builder_class(reference_lists=0),
107
 
                      # CHK based storage - just blobs, no compression or parents.
108
 
                      chk_index=chk_index
109
 
                      )
 
83
            # Revisions: parents list, no text compression.
 
84
            index_builder_class(reference_lists=1),
 
85
            # Inventory: We want to map compression only, but currently the
 
86
            # knit code hasn't been updated enough to understand that, so we
 
87
            # have a regular 2-list index giving parents and compression
 
88
            # source.
 
89
            index_builder_class(reference_lists=1),
 
90
            # Texts: per file graph, for all fileids - so one reference list
 
91
            # and two elements in the key tuple.
 
92
            index_builder_class(reference_lists=1, key_elements=2),
 
93
            # Signatures: Just blobs to store, no compression, no parents
 
94
            # listing.
 
95
            index_builder_class(reference_lists=0),
 
96
            # CHK based storage - just blobs, no compression or parents.
 
97
            chk_index=chk_index
 
98
            )
110
99
        self._pack_collection = pack_collection
111
100
        # When we make readonly indices, we need this.
112
101
        self.index_class = pack_collection._index_class
137
126
            self.random_name, mode=self._file_mode)
138
127
        if 'pack' in debug.debug_flags:
139
128
            trace.mutter('%s: create_pack: pack stream open: %s%s t+%6.3fs',
140
 
                         time.ctime(), self.upload_transport.base, self.random_name,
141
 
                         time.time() - self.start_time)
 
129
                time.ctime(), self.upload_transport.base, self.random_name,
 
130
                time.time() - self.start_time)
142
131
        # A list of byte sequences to be written to the new pack, and the
143
132
        # aggregate size of them.  Stored as a list rather than separate
144
133
        # variables so that the _write_data closure below can update them.
148
137
        # robertc says- this is a closure rather than a method on the object
149
138
        # so that the variables are locals, and faster than accessing object
150
139
        # members.
151
 
 
152
 
        def _write_data(data, flush=False, _buffer=self._buffer,
153
 
                        _write=self.write_stream.write, _update=self._hash.update):
154
 
            _buffer[0].append(data)
155
 
            _buffer[1] += len(data)
 
140
        def _write_data(bytes, flush=False, _buffer=self._buffer,
 
141
            _write=self.write_stream.write, _update=self._hash.update):
 
142
            _buffer[0].append(bytes)
 
143
            _buffer[1] += len(bytes)
156
144
            # buffer cap
157
145
            if _buffer[1] > self._cache_limit or flush:
158
 
                data = b''.join(_buffer[0])
159
 
                _write(data)
160
 
                _update(data)
 
146
                bytes = ''.join(_buffer[0])
 
147
                _write(bytes)
 
148
                _update(bytes)
161
149
                _buffer[:] = [[], 0]
162
150
        # expose this on self, for the occasion when clients want to add data.
163
151
        self._write_data = _write_data
205
193
        self._pack_collection = pack_collection
206
194
        # ATM, We only support this for GCCHK repositories
207
195
        if pack_collection.chk_index is None:
208
 
            raise AssertionError(
209
 
                'pack_collection.chk_index should not be None')
 
196
            raise AssertionError('pack_collection.chk_index should not be None')
210
197
        self._gather_text_refs = False
211
198
        self._chk_id_roots = []
212
199
        self._chk_p_id_roots = []
216
203
 
217
204
    def _get_progress_stream(self, source_vf, keys, message, pb):
218
205
        def pb_stream():
219
 
            substream = source_vf.get_record_stream(
220
 
                keys, 'groupcompress', True)
 
206
            substream = source_vf.get_record_stream(keys, 'groupcompress', True)
221
207
            for idx, record in enumerate(substream):
222
208
                if pb is not None:
223
209
                    pb.update(message, idx + 1, len(keys))
227
213
    def _get_filtered_inv_stream(self, source_vf, keys, message, pb=None):
228
214
        """Filter the texts of inventories, to find the chk pages."""
229
215
        total_keys = len(keys)
230
 
 
231
216
        def _filtered_inv_stream():
232
217
            id_roots_set = set()
233
218
            p_id_roots_set = set()
234
219
            stream = source_vf.get_record_stream(keys, 'groupcompress', True)
235
220
            for idx, record in enumerate(stream):
236
221
                # Inventories should always be with revisions; assume success.
237
 
                lines = record.get_bytes_as('lines')
238
 
                chk_inv = inventory.CHKInventory.deserialise(
239
 
                    None, lines, record.key)
 
222
                bytes = record.get_bytes_as('fulltext')
 
223
                chk_inv = inventory.CHKInventory.deserialise(None, bytes,
 
224
                                                             record.key)
240
225
                if pb is not None:
241
226
                    pb.update('inv', idx, total_keys)
242
227
                key = chk_inv.id_to_entry.key()
278
263
        counter = [0]
279
264
        if self._gather_text_refs:
280
265
            self._text_refs = set()
281
 
 
282
266
        def _get_referenced_stream(root_keys, parse_leaf_nodes=False):
283
267
            cur_keys = root_keys
284
268
            while cur_keys:
285
269
                keys_by_search_prefix = {}
286
270
                remaining_keys.difference_update(cur_keys)
287
271
                next_keys = set()
288
 
 
289
272
                def handle_internal_node(node):
290
 
                    for prefix, value in viewitems(node._items):
 
273
                    for prefix, value in node._items.iteritems():
291
274
                        # We don't want to request the same key twice, and we
292
275
                        # want to order it by the first time it is seen.
293
276
                        # Even further, we don't want to request a key which is
299
282
                        #       always fill them in for stacked branches
300
283
                        if value not in next_keys and value in remaining_keys:
301
284
                            keys_by_search_prefix.setdefault(prefix,
302
 
                                                             []).append(value)
 
285
                                []).append(value)
303
286
                            next_keys.add(value)
304
 
 
305
287
                def handle_leaf_node(node):
306
288
                    # Store is None, because we know we have a LeafNode, and we
307
289
                    # just want its entries
308
290
                    for file_id, bytes in node.iteritems(None):
309
291
                        self._text_refs.add(chk_map._bytes_to_text_key(bytes))
310
 
 
311
292
                def next_stream():
312
293
                    stream = source_vf.get_record_stream(cur_keys,
313
294
                                                         'as-requested', True)
369
350
        """Build a VersionedFiles instance on top of this group of packs."""
370
351
        index_name = index_name + '_index'
371
352
        index_to_pack = {}
372
 
        access = _DirectPackAccess(index_to_pack,
373
 
                                   reload_func=self._reload_func)
 
353
        access = knit._DirectPackAccess(index_to_pack,
 
354
                                        reload_func=self._reload_func)
374
355
        if for_write:
375
356
            # Use new_pack
376
357
            if self.new_pack is None:
410
391
                     pb_offset):
411
392
        trace.mutter('repacking %d %s', len(keys), message)
412
393
        self.pb.update('repacking %s' % (message,), pb_offset)
413
 
        with ui.ui_factory.nested_progress_bar() as child_pb:
 
394
        child_pb = ui.ui_factory.nested_progress_bar()
 
395
        try:
414
396
            stream = vf_to_stream(source_vf, keys, message, child_pb)
415
 
            for _, _ in target_vf._insert_record_stream(
416
 
                    stream, random_id=True, reuse_blocks=False):
 
397
            for _ in target_vf._insert_record_stream(stream,
 
398
                                                     random_id=True,
 
399
                                                     reuse_blocks=False):
417
400
                pass
 
401
        finally:
 
402
            child_pb.finished()
418
403
 
419
404
    def _copy_revision_texts(self):
420
405
        source_vf, target_vf = self._build_vfs('revision', True, False)
432
417
        # get_parent_map(self.revision_keys), but that shouldn't be any faster
433
418
        # than this.
434
419
        inventory_keys = source_vf.keys()
435
 
        missing_inventories = set(
436
 
            self.revision_keys).difference(inventory_keys)
 
420
        missing_inventories = set(self.revision_keys).difference(inventory_keys)
437
421
        if missing_inventories:
438
 
            # Go back to the original repo, to see if these are really missing
439
 
            # https://bugs.launchpad.net/bzr/+bug/437003
440
 
            # If we are packing a subset of the repo, it is fine to just have
441
 
            # the data in another Pack file, which is not included in this pack
442
 
            # operation.
443
 
            inv_index = self._pack_collection.repo.inventories._index
444
 
            pmap = inv_index.get_parent_map(missing_inventories)
445
 
            really_missing = missing_inventories.difference(pmap)
446
 
            if really_missing:
447
 
                missing_inventories = sorted(really_missing)
448
 
                raise ValueError('We are missing inventories for revisions: %s'
449
 
                                 % (missing_inventories,))
 
422
            missing_inventories = sorted(missing_inventories)
 
423
            raise ValueError('We are missing inventories for revisions: %s'
 
424
                % (missing_inventories,))
450
425
        self._copy_stream(source_vf, target_vf, inventory_keys,
451
426
                          'inventories', self._get_filtered_inv_stream, 2)
452
427
 
453
 
    def _get_chk_vfs_for_copy(self):
454
 
        return self._build_vfs('chk', False, False)
455
 
 
456
428
    def _copy_chk_texts(self):
457
 
        source_vf, target_vf = self._get_chk_vfs_for_copy()
 
429
        source_vf, target_vf = self._build_vfs('chk', False, False)
458
430
        # TODO: This is technically spurious... if it is a performance issue,
459
431
        #       remove it
460
432
        total_keys = source_vf.keys()
463
435
                     len(self._chk_id_roots), len(self._chk_p_id_roots),
464
436
                     len(total_keys))
465
437
        self.pb.update('repacking chk', 3)
466
 
        with ui.ui_factory.nested_progress_bar() as child_pb:
 
438
        child_pb = ui.ui_factory.nested_progress_bar()
 
439
        try:
467
440
            for stream in self._get_chk_streams(source_vf, total_keys,
468
441
                                                pb=child_pb):
469
 
                for _, _ in target_vf._insert_record_stream(
470
 
                        stream, random_id=True, reuse_blocks=False):
 
442
                for _ in target_vf._insert_record_stream(stream,
 
443
                                                         random_id=True,
 
444
                                                         reuse_blocks=False):
471
445
                    pass
 
446
        finally:
 
447
            child_pb.finished()
472
448
 
473
449
    def _copy_text_texts(self):
474
450
        source_vf, target_vf = self._build_vfs('text', True, True)
492
468
        self.pb.update('repacking', 0, 7)
493
469
        self.new_pack = self.open_pack()
494
470
        # Is this necessary for GC ?
495
 
        self.new_pack.set_write_cache_size(1024 * 1024)
 
471
        self.new_pack.set_write_cache_size(1024*1024)
496
472
        self._copy_revision_texts()
497
473
        self._copy_inventory_texts()
498
474
        self._copy_chk_texts()
508
484
            if old_pack.name == self.new_pack._hash.hexdigest():
509
485
                # The single old pack was already optimally packed.
510
486
                trace.mutter('single pack %s was already optimally packed',
511
 
                             old_pack.name)
 
487
                    old_pack.name)
512
488
                self.new_pack.abort()
513
489
                return None
514
490
        self.pb.update('finishing repack', 6, 7)
520
496
class GCCHKReconcilePacker(GCCHKPacker):
521
497
    """A packer which regenerates indices etc as it copies.
522
498
 
523
 
    This is used by ``brz reconcile`` to cause parent text pointers to be
 
499
    This is used by ``bzr reconcile`` to cause parent text pointers to be
524
500
    regenerated.
525
501
    """
526
502
 
549
525
        ancestor_keys = revision_vf.get_parent_map(revision_vf.keys())
550
526
        # Strip keys back into revision_ids.
551
527
        ancestors = dict((k[0], tuple([p[0] for p in parents]))
552
 
                         for k, parents in viewitems(ancestor_keys))
 
528
                         for k, parents in ancestor_keys.iteritems())
553
529
        del ancestor_keys
554
530
        # TODO: _generate_text_key_index should be much cheaper to generate from
555
531
        #       a chk repository, rather than the current implementation
558
534
        # 2) generate a keys list that contains all the entries that can
559
535
        #    be used as-is, with corrected parents.
560
536
        ok_keys = []
561
 
        new_parent_keys = {}  # (key, parent_keys)
 
537
        new_parent_keys = {} # (key, parent_keys)
562
538
        discarded_keys = []
563
539
        NULL_REVISION = _mod_revision.NULL_REVISION
564
540
        for key in self._text_refs:
588
564
        del ideal_index
589
565
        del file_id_parent_map
590
566
        # 3) bulk copy the data, updating records than need it
591
 
 
592
567
        def _update_parents_for_texts():
593
568
            stream = source_vf.get_record_stream(self._text_refs,
594
 
                                                 'groupcompress', False)
 
569
                'groupcompress', False)
595
570
            for record in stream:
596
571
                if record.key in new_parent_keys:
597
572
                    record.parents = new_parent_keys[record.key]
603
578
        return new_pack.data_inserted() and self._data_changed
604
579
 
605
580
 
606
 
class GCCHKCanonicalizingPacker(GCCHKPacker):
607
 
    """A packer that ensures inventories have canonical-form CHK maps.
608
 
 
609
 
    Ideally this would be part of reconcile, but it's very slow and rarely
610
 
    needed.  (It repairs repositories affected by
611
 
    https://bugs.launchpad.net/bzr/+bug/522637).
612
 
    """
613
 
 
614
 
    def __init__(self, *args, **kwargs):
615
 
        super(GCCHKCanonicalizingPacker, self).__init__(*args, **kwargs)
616
 
        self._data_changed = False
617
 
 
618
 
    def _exhaust_stream(self, source_vf, keys, message, vf_to_stream, pb_offset):
619
 
        """Create and exhaust a stream, but don't insert it.
620
 
 
621
 
        This is useful to get the side-effects of generating a stream.
622
 
        """
623
 
        self.pb.update('scanning %s' % (message,), pb_offset)
624
 
        with ui.ui_factory.nested_progress_bar() as child_pb:
625
 
            list(vf_to_stream(source_vf, keys, message, child_pb))
626
 
 
627
 
    def _copy_inventory_texts(self):
628
 
        source_vf, target_vf = self._build_vfs('inventory', True, True)
629
 
        source_chk_vf, target_chk_vf = self._get_chk_vfs_for_copy()
630
 
        inventory_keys = source_vf.keys()
631
 
        # First, copy the existing CHKs on the assumption that most of them
632
 
        # will be correct.  This will save us from having to reinsert (and
633
 
        # recompress) these records later at the cost of perhaps preserving a
634
 
        # few unused CHKs.
635
 
        # (Iterate but don't insert _get_filtered_inv_stream to populate the
636
 
        # variables needed by GCCHKPacker._copy_chk_texts.)
637
 
        self._exhaust_stream(source_vf, inventory_keys, 'inventories',
638
 
                             self._get_filtered_inv_stream, 2)
639
 
        GCCHKPacker._copy_chk_texts(self)
640
 
        # Now copy and fix the inventories, and any regenerated CHKs.
641
 
 
642
 
        def chk_canonicalizing_inv_stream(source_vf, keys, message, pb=None):
643
 
            return self._get_filtered_canonicalizing_inv_stream(
644
 
                source_vf, keys, message, pb, source_chk_vf, target_chk_vf)
645
 
        self._copy_stream(source_vf, target_vf, inventory_keys,
646
 
                          'inventories', chk_canonicalizing_inv_stream, 4)
647
 
 
648
 
    def _copy_chk_texts(self):
649
 
        # No-op; in this class this happens during _copy_inventory_texts.
650
 
        pass
651
 
 
652
 
    def _get_filtered_canonicalizing_inv_stream(self, source_vf, keys, message,
653
 
                                                pb=None, source_chk_vf=None, target_chk_vf=None):
654
 
        """Filter the texts of inventories, regenerating CHKs to make sure they
655
 
        are canonical.
656
 
        """
657
 
        total_keys = len(keys)
658
 
        target_chk_vf = versionedfile.NoDupeAddLinesDecorator(target_chk_vf)
659
 
 
660
 
        def _filtered_inv_stream():
661
 
            stream = source_vf.get_record_stream(keys, 'groupcompress', True)
662
 
            search_key_name = None
663
 
            for idx, record in enumerate(stream):
664
 
                # Inventories should always be with revisions; assume success.
665
 
                lines = record.get_bytes_as('lines')
666
 
                chk_inv = inventory.CHKInventory.deserialise(
667
 
                    source_chk_vf, lines, record.key)
668
 
                if pb is not None:
669
 
                    pb.update('inv', idx, total_keys)
670
 
                chk_inv.id_to_entry._ensure_root()
671
 
                if search_key_name is None:
672
 
                    # Find the name corresponding to the search_key_func
673
 
                    search_key_reg = chk_map.search_key_registry
674
 
                    for search_key_name, func in viewitems(search_key_reg):
675
 
                        if func == chk_inv.id_to_entry._search_key_func:
676
 
                            break
677
 
                canonical_inv = inventory.CHKInventory.from_inventory(
678
 
                    target_chk_vf, chk_inv,
679
 
                    maximum_size=chk_inv.id_to_entry._root_node._maximum_size,
680
 
                    search_key_name=search_key_name)
681
 
                if chk_inv.id_to_entry.key() != canonical_inv.id_to_entry.key():
682
 
                    trace.mutter(
683
 
                        'Non-canonical CHK map for id_to_entry of inv: %s '
684
 
                        '(root is %s, should be %s)' % (chk_inv.revision_id,
685
 
                                                        chk_inv.id_to_entry.key()[
686
 
                                                            0],
687
 
                                                        canonical_inv.id_to_entry.key()[0]))
688
 
                    self._data_changed = True
689
 
                p_id_map = chk_inv.parent_id_basename_to_file_id
690
 
                p_id_map._ensure_root()
691
 
                canon_p_id_map = canonical_inv.parent_id_basename_to_file_id
692
 
                if p_id_map.key() != canon_p_id_map.key():
693
 
                    trace.mutter(
694
 
                        'Non-canonical CHK map for parent_id_to_basename of '
695
 
                        'inv: %s (root is %s, should be %s)'
696
 
                        % (chk_inv.revision_id, p_id_map.key()[0],
697
 
                           canon_p_id_map.key()[0]))
698
 
                    self._data_changed = True
699
 
                yield versionedfile.ChunkedContentFactory(
700
 
                    record.key, record.parents, record.sha1, canonical_inv.to_lines(),
701
 
                    chunks_are_lines=True)
702
 
            # We have finished processing all of the inventory records, we
703
 
            # don't need these sets anymore
704
 
        return _filtered_inv_stream()
705
 
 
706
 
    def _use_pack(self, new_pack):
707
 
        """Override _use_pack to check for reconcile having changed content."""
708
 
        return new_pack.data_inserted() and self._data_changed
709
 
 
710
 
 
711
581
class GCRepositoryPackCollection(RepositoryPackCollection):
712
582
 
713
583
    pack_factory = GCPack
714
584
    resumed_pack_factory = ResumedGCPack
715
 
    normal_packer_class = GCCHKPacker
716
 
    optimising_packer_class = GCCHKPacker
717
585
 
718
586
    def _check_new_inventories(self):
719
587
        """Detect missing inventories or chk root entries for the new revisions
742
610
        missing_corresponding.difference_update(corresponding_invs)
743
611
        if missing_corresponding:
744
612
            problems.append("inventories missing for revisions %s" %
745
 
                            (sorted(missing_corresponding),))
 
613
                (sorted(missing_corresponding),))
746
614
            return problems
747
615
        # Are any chk root entries missing for any inventories?  This includes
748
616
        # any present parent inventories, which may be used when calculating
749
617
        # deltas for streaming.
750
618
        all_inv_keys = set(corresponding_invs)
751
 
        for parent_inv_keys in viewvalues(inv_parent_map):
 
619
        for parent_inv_keys in inv_parent_map.itervalues():
752
620
            all_inv_keys.update(parent_inv_keys)
753
621
        # Filter out ghost parents.
754
622
        all_inv_keys.intersection_update(
765
633
            expected_chk_roots)
766
634
        missing_chk_roots = expected_chk_roots.difference(present_chk_roots)
767
635
        if missing_chk_roots:
768
 
            problems.append(
769
 
                "missing referenced chk root keys: %s."
770
 
                "Run 'brz reconcile --canonicalize-chks' on the affected "
771
 
                "repository."
 
636
            problems.append("missing referenced chk root keys: %s"
772
637
                % (sorted(missing_chk_roots),))
773
638
            # Don't bother checking any further.
774
639
            return problems
785
650
            for record in _filter_text_keys(chk_diff, text_keys,
786
651
                                            chk_map._bytes_to_text_key):
787
652
                pass
788
 
        except errors.NoSuchRevision as e:
 
653
        except errors.NoSuchRevision, e:
789
654
            # XXX: It would be nice if we could give a more precise error here.
790
655
            problems.append("missing chk node(s) for id_to_entry maps")
791
656
        chk_diff = chk_map.iter_interesting_nodes(
794
659
        try:
795
660
            for interesting_rec, interesting_map in chk_diff:
796
661
                pass
797
 
        except errors.NoSuchRevision as e:
 
662
        except errors.NoSuchRevision, e:
798
663
            problems.append(
799
664
                "missing chk node(s) for parent_id_basename_to_file_id maps")
800
665
        present_text_keys = no_fallback_texts_index.get_parent_map(text_keys)
801
666
        missing_text_keys = text_keys.difference(present_text_keys)
802
667
        if missing_text_keys:
803
668
            problems.append("missing text keys: %r"
804
 
                            % (sorted(missing_text_keys),))
 
669
                % (sorted(missing_text_keys),))
805
670
        return problems
806
671
 
807
 
 
808
 
class CHKInventoryRepository(PackRepository):
809
 
    """subclass of PackRepository that uses CHK based inventories."""
810
 
 
811
 
    def __init__(self, _format, a_controldir, control_files, _commit_builder_class,
812
 
                 _serializer):
 
672
    def _execute_pack_operations(self, pack_operations,
 
673
                                 _packer_class=GCCHKPacker,
 
674
                                 reload_func=None):
 
675
        """Execute a series of pack operations.
 
676
 
 
677
        :param pack_operations: A list of [revision_count, packs_to_combine].
 
678
        :param _packer_class: The class of packer to use (default: Packer).
 
679
        :return: None.
 
680
        """
 
681
        # XXX: Copied across from RepositoryPackCollection simply because we
 
682
        #      want to override the _packer_class ... :(
 
683
        for revision_count, packs in pack_operations:
 
684
            # we may have no-ops from the setup logic
 
685
            if len(packs) == 0:
 
686
                continue
 
687
            packer = GCCHKPacker(self, packs, '.autopack',
 
688
                                 reload_func=reload_func)
 
689
            try:
 
690
                result = packer.pack()
 
691
            except errors.RetryWithNewPacks:
 
692
                # An exception is propagating out of this context, make sure
 
693
                # this packer has cleaned up. Packer() doesn't set its new_pack
 
694
                # state into the RepositoryPackCollection object, so we only
 
695
                # have access to it directly here.
 
696
                if packer.new_pack is not None:
 
697
                    packer.new_pack.abort()
 
698
                raise
 
699
            if result is None:
 
700
                return
 
701
            for pack in packs:
 
702
                self._remove_pack_from_memory(pack)
 
703
        # record the newly available packs and stop advertising the old
 
704
        # packs
 
705
        to_be_obsoleted = []
 
706
        for _, packs in pack_operations:
 
707
            to_be_obsoleted.extend(packs)
 
708
        result = self._save_pack_names(clear_obsolete_packs=True,
 
709
                                       obsolete_packs=to_be_obsoleted)
 
710
        return result
 
711
 
 
712
 
 
713
class CHKInventoryRepository(KnitPackRepository):
 
714
    """subclass of KnitPackRepository that uses CHK based inventories."""
 
715
 
 
716
    def __init__(self, _format, a_bzrdir, control_files, _commit_builder_class,
 
717
        _serializer):
813
718
        """Overridden to change pack collection class."""
814
 
        super(CHKInventoryRepository, self).__init__(_format, a_controldir,
815
 
                                                     control_files, _commit_builder_class, _serializer)
 
719
        KnitPackRepository.__init__(self, _format, a_bzrdir, control_files,
 
720
            _commit_builder_class, _serializer)
 
721
        # and now replace everything it did :)
816
722
        index_transport = self._transport.clone('indices')
817
723
        self._pack_collection = GCRepositoryPackCollection(self,
818
 
                                                           self._transport, index_transport,
819
 
                                                           self._transport.clone(
820
 
                                                               'upload'),
821
 
                                                           self._transport.clone(
822
 
                                                               'packs'),
823
 
                                                           _format.index_builder_class,
824
 
                                                           _format.index_class,
825
 
                                                           use_chk_index=self._format.supports_chks,
826
 
                                                           )
 
724
            self._transport, index_transport,
 
725
            self._transport.clone('upload'),
 
726
            self._transport.clone('packs'),
 
727
            _format.index_builder_class,
 
728
            _format.index_class,
 
729
            use_chk_index=self._format.supports_chks,
 
730
            )
827
731
        self.inventories = GroupCompressVersionedFiles(
828
732
            _GCGraphIndex(self._pack_collection.inventory_index.combined_index,
829
 
                          add_callback=self._pack_collection.inventory_index.add_callback,
830
 
                          parents=True, is_locked=self.is_locked,
831
 
                          inconsistency_fatal=False),
 
733
                add_callback=self._pack_collection.inventory_index.add_callback,
 
734
                parents=True, is_locked=self.is_locked,
 
735
                inconsistency_fatal=False),
832
736
            access=self._pack_collection.inventory_index.data_access)
833
737
        self.revisions = GroupCompressVersionedFiles(
834
738
            _GCGraphIndex(self._pack_collection.revision_index.combined_index,
835
 
                          add_callback=self._pack_collection.revision_index.add_callback,
836
 
                          parents=True, is_locked=self.is_locked,
837
 
                          track_external_parent_refs=True, track_new_keys=True),
 
739
                add_callback=self._pack_collection.revision_index.add_callback,
 
740
                parents=True, is_locked=self.is_locked,
 
741
                track_external_parent_refs=True, track_new_keys=True),
838
742
            access=self._pack_collection.revision_index.data_access,
839
743
            delta=False)
840
744
        self.signatures = GroupCompressVersionedFiles(
841
745
            _GCGraphIndex(self._pack_collection.signature_index.combined_index,
842
 
                          add_callback=self._pack_collection.signature_index.add_callback,
843
 
                          parents=False, is_locked=self.is_locked,
844
 
                          inconsistency_fatal=False),
 
746
                add_callback=self._pack_collection.signature_index.add_callback,
 
747
                parents=False, is_locked=self.is_locked,
 
748
                inconsistency_fatal=False),
845
749
            access=self._pack_collection.signature_index.data_access,
846
750
            delta=False)
847
751
        self.texts = GroupCompressVersionedFiles(
848
752
            _GCGraphIndex(self._pack_collection.text_index.combined_index,
849
 
                          add_callback=self._pack_collection.text_index.add_callback,
850
 
                          parents=True, is_locked=self.is_locked,
851
 
                          inconsistency_fatal=False),
 
753
                add_callback=self._pack_collection.text_index.add_callback,
 
754
                parents=True, is_locked=self.is_locked,
 
755
                inconsistency_fatal=False),
852
756
            access=self._pack_collection.text_index.data_access)
853
757
        # No parents, individual CHK pages don't have specific ancestry
854
758
        self.chk_bytes = GroupCompressVersionedFiles(
855
759
            _GCGraphIndex(self._pack_collection.chk_index.combined_index,
856
 
                          add_callback=self._pack_collection.chk_index.add_callback,
857
 
                          parents=False, is_locked=self.is_locked,
858
 
                          inconsistency_fatal=False),
 
760
                add_callback=self._pack_collection.chk_index.add_callback,
 
761
                parents=False, is_locked=self.is_locked,
 
762
                inconsistency_fatal=False),
859
763
            access=self._pack_collection.chk_index.data_access)
860
764
        search_key_name = self._format._serializer.search_key_name
861
765
        search_key_func = chk_map.search_key_registry.get(search_key_name)
882
786
        # make inventory
883
787
        serializer = self._format._serializer
884
788
        result = inventory.CHKInventory.from_inventory(self.chk_bytes, inv,
885
 
                                                       maximum_size=serializer.maximum_size,
886
 
                                                       search_key_name=serializer.search_key_name)
 
789
            maximum_size=serializer.maximum_size,
 
790
            search_key_name=serializer.search_key_name)
887
791
        inv_lines = result.to_lines()
888
792
        return self._inventory_add_lines(revision_id, parents,
889
 
                                         inv_lines, check_content=False)
 
793
            inv_lines, check_content=False)
890
794
 
891
795
    def _create_inv_from_null(self, delta, revision_id):
892
796
        """This will mutate new_inv directly.
910
814
                                 ' no new_path %r' % (file_id,))
911
815
            if new_path == '':
912
816
                new_inv.root_id = file_id
913
 
                parent_id_basename_key = StaticTuple(b'', b'').intern()
 
817
                parent_id_basename_key = StaticTuple('', '').intern()
914
818
            else:
915
819
                utf8_entry_name = entry.name.encode('utf-8')
916
820
                parent_id_basename_key = StaticTuple(entry.parent_id,
923
827
            parent_id_basename_dict[parent_id_basename_key] = file_id
924
828
 
925
829
        new_inv._populate_from_dicts(self.chk_bytes, id_to_entry_dict,
926
 
                                     parent_id_basename_dict, maximum_size=serializer.maximum_size)
 
830
            parent_id_basename_dict, maximum_size=serializer.maximum_size)
927
831
        return new_inv
928
832
 
929
833
    def add_inventory_by_delta(self, basis_revision_id, delta, new_revision_id,
955
859
            raise AssertionError("%r not in write group" % (self,))
956
860
        _mod_revision.check_not_reserved_id(new_revision_id)
957
861
        basis_tree = None
958
 
        if basis_inv is None or not isinstance(basis_inv, inventory.CHKInventory):
 
862
        if basis_inv is None:
959
863
            if basis_revision_id == _mod_revision.NULL_REVISION:
960
864
                new_inv = self._create_inv_from_null(delta, new_revision_id)
961
865
                if new_inv.root_id is None:
962
866
                    raise errors.RootMissing()
963
867
                inv_lines = new_inv.to_lines()
964
868
                return self._inventory_add_lines(new_revision_id, parents,
965
 
                                                 inv_lines, check_content=False), new_inv
 
869
                    inv_lines, check_content=False), new_inv
966
870
            else:
967
871
                basis_tree = self.revision_tree(basis_revision_id)
968
872
                basis_tree.lock_read()
969
 
                basis_inv = basis_tree.root_inventory
 
873
                basis_inv = basis_tree.inventory
970
874
        try:
971
875
            result = basis_inv.create_by_apply_delta(delta, new_revision_id,
972
 
                                                     propagate_caches=propagate_caches)
 
876
                propagate_caches=propagate_caches)
973
877
            inv_lines = result.to_lines()
974
878
            return self._inventory_add_lines(new_revision_id, parents,
975
 
                                             inv_lines, check_content=False), result
 
879
                inv_lines, check_content=False), result
976
880
        finally:
977
881
            if basis_tree is not None:
978
882
                basis_tree.unlock()
979
883
 
980
 
    def _deserialise_inventory(self, revision_id, lines):
981
 
        return inventory.CHKInventory.deserialise(self.chk_bytes, lines,
982
 
                                                  (revision_id,))
 
884
    def _deserialise_inventory(self, revision_id, bytes):
 
885
        return inventory.CHKInventory.deserialise(self.chk_bytes, bytes,
 
886
            (revision_id,))
983
887
 
984
888
    def _iter_inventories(self, revision_ids, ordering):
985
889
        """Iterate over many inventory objects."""
990
894
        texts = {}
991
895
        for record in stream:
992
896
            if record.storage_kind != 'absent':
993
 
                texts[record.key] = record.get_bytes_as('lines')
 
897
                texts[record.key] = record.get_bytes_as('fulltext')
994
898
            else:
995
 
                texts[record.key] = None
 
899
                raise errors.NoSuchRevision(self, record.key)
996
900
        for key in keys:
997
 
            lines = texts[key]
998
 
            if lines is None:
999
 
                yield (None, key[-1])
1000
 
            else:
1001
 
                yield (inventory.CHKInventory.deserialise(
1002
 
                    self.chk_bytes, lines, key), key[-1])
 
901
            yield inventory.CHKInventory.deserialise(self.chk_bytes, texts[key], key)
1003
902
 
1004
 
    def _get_inventory_xml(self, revision_id):
1005
 
        """Get serialized inventory as a string."""
 
903
    def _iter_inventory_xmls(self, revision_ids, ordering):
1006
904
        # Without a native 'xml' inventory, this method doesn't make sense.
1007
905
        # However older working trees, and older bundles want it - so we supply
1008
906
        # it allowing _get_inventory_xml to work. Bundles currently use the
1009
907
        # serializer directly; this also isn't ideal, but there isn't an xml
1010
 
        # iteration interface offered at all for repositories.
1011
 
        return self._serializer.write_inventory_to_lines(
1012
 
            self.get_inventory(revision_id))
 
908
        # iteration interface offered at all for repositories. We could make
 
909
        # _iter_inventory_xmls be part of the contract, even if kept private.
 
910
        inv_to_str = self._serializer.write_inventory_to_string
 
911
        for inv in self.iter_inventories(revision_ids, ordering=ordering):
 
912
            yield inv_to_str(inv), inv.revision_id
1013
913
 
1014
914
    def _find_present_inventory_keys(self, revision_keys):
1015
915
        parent_map = self.inventories.get_parent_map(revision_keys)
1029
929
        rich_root = self.supports_rich_root()
1030
930
        bytes_to_info = inventory.CHKInventory._bytes_to_utf8name_key
1031
931
        file_id_revisions = {}
1032
 
        with ui.ui_factory.nested_progress_bar() as pb:
 
932
        pb = ui.ui_factory.nested_progress_bar()
 
933
        try:
1033
934
            revision_keys = [(r,) for r in revision_ids]
1034
935
            parent_keys = self._find_parent_keys_of_revisions(revision_keys)
1035
936
            # TODO: instead of using _find_present_inventory_keys, change the
1037
938
            #       However, we only want to tolerate missing parent
1038
939
            #       inventories, not missing inventories for revision_ids
1039
940
            present_parent_inv_keys = self._find_present_inventory_keys(
1040
 
                parent_keys)
1041
 
            present_parent_inv_ids = {k[-1] for k in present_parent_inv_keys}
 
941
                                        parent_keys)
 
942
            present_parent_inv_ids = set(
 
943
                [k[-1] for k in present_parent_inv_keys])
1042
944
            inventories_to_read = set(revision_ids)
1043
945
            inventories_to_read.update(present_parent_inv_ids)
1044
946
            root_key_info = _build_interesting_key_sets(
1047
949
            uninteresting_root_keys = root_key_info.uninteresting_root_keys
1048
950
            chk_bytes = self.chk_bytes
1049
951
            for record, items in chk_map.iter_interesting_nodes(chk_bytes,
1050
 
                                                                interesting_root_keys, uninteresting_root_keys,
1051
 
                                                                pb=pb):
 
952
                        interesting_root_keys, uninteresting_root_keys,
 
953
                        pb=pb):
1052
954
                for name, bytes in items:
1053
955
                    (name_utf8, file_id, revision_id) = bytes_to_info(bytes)
1054
956
                    # TODO: consider interning file_id, revision_id here, or
1060
962
                    try:
1061
963
                        file_id_revisions[file_id].add(revision_id)
1062
964
                    except KeyError:
1063
 
                        file_id_revisions[file_id] = {revision_id}
 
965
                        file_id_revisions[file_id] = set([revision_id])
 
966
        finally:
 
967
            pb.finished()
1064
968
        return file_id_revisions
1065
969
 
1066
970
    def find_text_key_references(self):
1078
982
        revision_keys = self.revisions.keys()
1079
983
        result = {}
1080
984
        rich_roots = self.supports_rich_root()
1081
 
        with ui.ui_factory.nested_progress_bar() as pb:
 
985
        pb = ui.ui_factory.nested_progress_bar()
 
986
        try:
1082
987
            all_revs = self.all_revision_ids()
1083
988
            total = len(all_revs)
1084
989
            for pos, inv in enumerate(self.iter_inventories(all_revs)):
1091
996
                    if entry.revision == inv.revision_id:
1092
997
                        result[key] = True
1093
998
            return result
1094
 
 
1095
 
    def reconcile_canonicalize_chks(self):
1096
 
        """Reconcile this repository to make sure all CHKs are in canonical
1097
 
        form.
1098
 
        """
1099
 
        from .reconcile import PackReconciler
1100
 
        with self.lock_write():
1101
 
            reconciler = PackReconciler(
1102
 
                self, thorough=True, canonicalize_chks=True)
1103
 
            return reconciler.reconcile()
 
999
        finally:
 
1000
            pb.finished()
1104
1001
 
1105
1002
    def _reconcile_pack(self, collection, packs, extension, revs, pb):
1106
1003
        packer = GCCHKReconcilePacker(collection, packs, extension)
1107
1004
        return packer.pack(pb)
1108
1005
 
1109
 
    def _canonicalize_chks_pack(self, collection, packs, extension, revs, pb):
1110
 
        packer = GCCHKCanonicalizingPacker(collection, packs, extension, revs)
1111
 
        return packer.pack(pb)
1112
 
 
1113
1006
    def _get_source(self, to_format):
1114
1007
        """Return a source for streaming from this repository."""
1115
1008
        if self._format._serializer == to_format._serializer:
1120
1013
            return GroupCHKStreamSource(self, to_format)
1121
1014
        return super(CHKInventoryRepository, self)._get_source(to_format)
1122
1015
 
1123
 
    def _find_inconsistent_revision_parents(self, revisions_iterator=None):
1124
 
        """Find revisions with different parent lists in the revision object
1125
 
        and in the index graph.
1126
 
 
1127
 
        :param revisions_iterator: None, or an iterator of (revid,
1128
 
            Revision-or-None). This iterator controls the revisions checked.
1129
 
        :returns: an iterator yielding tuples of (revison-id, parents-in-index,
1130
 
            parents-in-revision).
1131
 
        """
1132
 
        if not self.is_locked():
1133
 
            raise AssertionError()
1134
 
        vf = self.revisions
1135
 
        if revisions_iterator is None:
1136
 
            revisions_iterator = self.iter_revisions(self.all_revision_ids())
1137
 
        for revid, revision in revisions_iterator:
1138
 
            if revision is None:
1139
 
                pass
1140
 
            parent_map = vf.get_parent_map([(revid,)])
1141
 
            parents_according_to_index = tuple(parent[-1] for parent in
1142
 
                                               parent_map[(revid,)])
1143
 
            parents_according_to_revision = tuple(revision.parent_ids)
1144
 
            if parents_according_to_index != parents_according_to_revision:
1145
 
                yield (revid, parents_according_to_index,
1146
 
                       parents_according_to_revision)
1147
 
 
1148
 
    def _check_for_inconsistent_revision_parents(self):
1149
 
        inconsistencies = list(self._find_inconsistent_revision_parents())
1150
 
        if inconsistencies:
1151
 
            raise errors.BzrCheckError(
1152
 
                "Revision index has inconsistent parents.")
1153
 
 
1154
 
 
1155
 
class GroupCHKStreamSource(StreamSource):
 
1016
 
 
1017
class GroupCHKStreamSource(KnitPackStreamSource):
1156
1018
    """Used when both the source and target repo are GroupCHK repos."""
1157
1019
 
1158
1020
    def __init__(self, from_repository, to_format):
1172
1034
        """
1173
1035
        self._chk_id_roots = []
1174
1036
        self._chk_p_id_roots = []
1175
 
 
1176
1037
        def _filtered_inv_stream():
1177
1038
            id_roots_set = set()
1178
1039
            p_id_roots_set = set()
1185
1046
                        continue
1186
1047
                    else:
1187
1048
                        raise errors.NoSuchRevision(self, record.key)
1188
 
                lines = record.get_bytes_as('lines')
1189
 
                chk_inv = inventory.CHKInventory.deserialise(None, lines,
 
1049
                bytes = record.get_bytes_as('fulltext')
 
1050
                chk_inv = inventory.CHKInventory.deserialise(None, bytes,
1190
1051
                                                             record.key)
1191
1052
                key = chk_inv.id_to_entry.key()
1192
1053
                if key not in id_roots_set:
1218
1079
            # TODO: Update Repository.iter_inventories() to add
1219
1080
            #       ignore_missing=True
1220
1081
            present_keys = self.from_repository._find_present_inventory_keys(
1221
 
                excluded_revision_keys)
 
1082
                            excluded_revision_keys)
1222
1083
            present_ids = [k[-1] for k in present_keys]
1223
1084
            uninteresting_root_keys = set()
1224
1085
            uninteresting_pid_root_keys = set()
1227
1088
                uninteresting_pid_root_keys.add(
1228
1089
                    inv.parent_id_basename_to_file_id.key())
1229
1090
        chk_bytes = self.from_repository.chk_bytes
1230
 
 
1231
1091
        def _filter_id_to_entry():
1232
1092
            interesting_nodes = chk_map.iter_interesting_nodes(chk_bytes,
1233
 
                                                               self._chk_id_roots, uninteresting_root_keys)
 
1093
                        self._chk_id_roots, uninteresting_root_keys)
1234
1094
            for record in _filter_text_keys(interesting_nodes, self._text_keys,
1235
 
                                            chk_map._bytes_to_text_key):
 
1095
                    chk_map._bytes_to_text_key):
1236
1096
                if record is not None:
1237
1097
                    yield record
1238
1098
            # Consumed
1239
1099
            self._chk_id_roots = None
1240
1100
        yield 'chk_bytes', _filter_id_to_entry()
1241
 
 
1242
1101
        def _get_parent_id_basename_to_file_id_pages():
1243
1102
            for record, items in chk_map.iter_interesting_nodes(chk_bytes,
1244
 
                                                                self._chk_p_id_roots, uninteresting_pid_root_keys):
 
1103
                        self._chk_p_id_roots, uninteresting_pid_root_keys):
1245
1104
                if record is not None:
1246
1105
                    yield record
1247
1106
            # Consumed
1248
1107
            self._chk_p_id_roots = None
1249
1108
        yield 'chk_bytes', _get_parent_id_basename_to_file_id_pages()
1250
1109
 
1251
 
    def _get_text_stream(self):
1252
 
        # Note: We know we don't have to handle adding root keys, because both
1253
 
        # the source and target are the identical network name.
1254
 
        text_stream = self.from_repository.texts.get_record_stream(
1255
 
            self._text_keys, self._text_fetch_order, False)
1256
 
        return ('texts', text_stream)
1257
 
 
1258
1110
    def get_stream(self, search):
1259
1111
        def wrap_and_count(pb, rc, stream):
1260
1112
            """Yield records from stream while showing progress."""
1268
1120
                yield record
1269
1121
 
1270
1122
        revision_ids = search.get_keys()
1271
 
        with ui.ui_factory.nested_progress_bar() as pb:
1272
 
            rc = self._record_counter
1273
 
            self._record_counter.setup(len(revision_ids))
1274
 
            for stream_info in self._fetch_revision_texts(revision_ids):
1275
 
                yield (stream_info[0],
1276
 
                       wrap_and_count(pb, rc, stream_info[1]))
1277
 
            self._revision_keys = [(rev_id,) for rev_id in revision_ids]
1278
 
            # TODO: The keys to exclude might be part of the search recipe
1279
 
            # For now, exclude all parents that are at the edge of ancestry, for
1280
 
            # which we have inventories
1281
 
            from_repo = self.from_repository
1282
 
            parent_keys = from_repo._find_parent_keys_of_revisions(
1283
 
                self._revision_keys)
1284
 
            self.from_repository.revisions.clear_cache()
1285
 
            self.from_repository.signatures.clear_cache()
1286
 
            # Clear the repo's get_parent_map cache too.
1287
 
            self.from_repository._unstacked_provider.disable_cache()
1288
 
            self.from_repository._unstacked_provider.enable_cache()
1289
 
            s = self._get_inventory_stream(self._revision_keys)
1290
 
            yield (s[0], wrap_and_count(pb, rc, s[1]))
1291
 
            self.from_repository.inventories.clear_cache()
1292
 
            for stream_info in self._get_filtered_chk_streams(parent_keys):
1293
 
                yield (stream_info[0], wrap_and_count(pb, rc, stream_info[1]))
1294
 
            self.from_repository.chk_bytes.clear_cache()
1295
 
            s = self._get_text_stream()
1296
 
            yield (s[0], wrap_and_count(pb, rc, s[1]))
1297
 
            self.from_repository.texts.clear_cache()
1298
 
            pb.update('Done', rc.max, rc.max)
 
1123
        pb = ui.ui_factory.nested_progress_bar()
 
1124
        rc = self._record_counter
 
1125
        self._record_counter.setup(len(revision_ids))
 
1126
        for stream_info in self._fetch_revision_texts(revision_ids):
 
1127
            yield (stream_info[0],
 
1128
                wrap_and_count(pb, rc, stream_info[1]))
 
1129
        self._revision_keys = [(rev_id,) for rev_id in revision_ids]
 
1130
        self.from_repository.revisions.clear_cache()
 
1131
        self.from_repository.signatures.clear_cache()
 
1132
        s = self._get_inventory_stream(self._revision_keys)
 
1133
        yield (s[0], wrap_and_count(pb, rc, s[1]))
 
1134
        self.from_repository.inventories.clear_cache()
 
1135
        # TODO: The keys to exclude might be part of the search recipe
 
1136
        # For now, exclude all parents that are at the edge of ancestry, for
 
1137
        # which we have inventories
 
1138
        from_repo = self.from_repository
 
1139
        parent_keys = from_repo._find_parent_keys_of_revisions(
 
1140
                        self._revision_keys)
 
1141
        for stream_info in self._get_filtered_chk_streams(parent_keys):
 
1142
            yield (stream_info[0], wrap_and_count(pb, rc, stream_info[1]))
 
1143
        self.from_repository.chk_bytes.clear_cache()
 
1144
        s = self._get_text_stream()
 
1145
        yield (s[0], wrap_and_count(pb, rc, s[1]))
 
1146
        self.from_repository.texts.clear_cache()
 
1147
        pb.update('Done', rc.max, rc.max)
 
1148
        pb.finished()
1299
1149
 
1300
1150
    def get_stream_for_missing_keys(self, missing_keys):
1301
1151
        # missing keys can only occur when we are byte copying and not
1305
1155
        for key in missing_keys:
1306
1156
            if key[0] != 'inventories':
1307
1157
                raise AssertionError('The only missing keys we should'
1308
 
                                     ' be filling in are inventory keys, not %s'
1309
 
                                     % (key[0],))
 
1158
                    ' be filling in are inventory keys, not %s'
 
1159
                    % (key[0],))
1310
1160
            missing_inventory_keys.add(key[1:])
1311
1161
        if self._chk_id_roots or self._chk_p_id_roots:
1312
1162
            raise AssertionError('Cannot call get_stream_for_missing_keys'
1313
 
                                 ' until all of get_stream() has been consumed.')
 
1163
                ' until all of get_stream() has been consumed.')
1314
1164
        # Yield the inventory stream, so we can find the chk stream
1315
1165
        # Some of the missing_keys will be missing because they are ghosts.
1316
1166
        # As such, we can ignore them. The Sink is required to verify there are
1361
1211
    """
1362
1212
    text_keys_update = text_keys.update
1363
1213
    for record, items in interesting_nodes_iterable:
1364
 
        text_keys_update([bytes_to_text_key(b) for n, b in items])
 
1214
        text_keys_update([bytes_to_text_key(b) for n,b in items])
1365
1215
        yield record
1366
1216
 
1367
1217
 
1368
 
class RepositoryFormat2a(RepositoryFormatPack):
1369
 
    """A CHK repository that uses the bencode revision serializer."""
 
1218
 
 
1219
 
 
1220
class RepositoryFormatCHK1(RepositoryFormatPack):
 
1221
    """A hashed CHK+group compress pack repository."""
1370
1222
 
1371
1223
    repository_class = CHKInventoryRepository
1372
1224
    supports_external_lookups = True
1373
1225
    supports_chks = True
1374
 
    _commit_builder_class = PackCommitBuilder
 
1226
    # For right now, setting this to True gives us InterModel1And2 rather
 
1227
    # than InterDifferingSerializer
 
1228
    _commit_builder_class = PackRootCommitBuilder
1375
1229
    rich_root_data = True
1376
 
    _serializer = chk_serializer.chk_bencode_serializer
 
1230
    _serializer = chk_serializer.chk_serializer_255_bigpage
1377
1231
    _commit_inv_deltas = True
1378
1232
    # What index classes to use
1379
1233
    index_builder_class = BTreeBuilder
1385
1239
    # multiple in-a-row (and sharing strings). Topological is better
1386
1240
    # for remote, because we access less data.
1387
1241
    _fetch_order = 'unordered'
1388
 
    # essentially ignored by the groupcompress code.
1389
 
    _fetch_uses_deltas = False
 
1242
    _fetch_uses_deltas = False # essentially ignored by the groupcompress code.
1390
1243
    fast_deltas = True
1391
1244
    pack_compresses = True
1392
 
    supports_tree_reference = True
1393
 
 
1394
 
    def _get_matching_bzrdir(self):
1395
 
        return controldir.format_registry.make_controldir('2a')
1396
 
 
1397
 
    def _ignore_setting_bzrdir(self, format):
1398
 
        pass
1399
 
 
1400
 
    _matchingcontroldir = property(
1401
 
        _get_matching_bzrdir, _ignore_setting_bzrdir)
1402
 
 
1403
 
    @classmethod
1404
 
    def get_format_string(cls):
1405
 
        return b'Bazaar repository format 2a (needs bzr 1.16 or later)\n'
 
1245
 
 
1246
    def _get_matching_bzrdir(self):
 
1247
        return bzrdir.format_registry.make_bzrdir('development6-rich-root')
 
1248
 
 
1249
    def _ignore_setting_bzrdir(self, format):
 
1250
        pass
 
1251
 
 
1252
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
1253
 
 
1254
    def get_format_string(self):
 
1255
        """See RepositoryFormat.get_format_string()."""
 
1256
        return ('Bazaar development format - group compression and chk inventory'
 
1257
                ' (needs bzr.dev from 1.14)\n')
 
1258
 
 
1259
    def get_format_description(self):
 
1260
        """See RepositoryFormat.get_format_description()."""
 
1261
        return ("Development repository format - rich roots, group compression"
 
1262
            " and chk inventories")
 
1263
 
 
1264
 
 
1265
class RepositoryFormatCHK2(RepositoryFormatCHK1):
 
1266
    """A CHK repository that uses the bencode revision serializer."""
 
1267
 
 
1268
    _serializer = chk_serializer.chk_bencode_serializer
 
1269
 
 
1270
    def _get_matching_bzrdir(self):
 
1271
        return bzrdir.format_registry.make_bzrdir('development7-rich-root')
 
1272
 
 
1273
    def _ignore_setting_bzrdir(self, format):
 
1274
        pass
 
1275
 
 
1276
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
1277
 
 
1278
    def get_format_string(self):
 
1279
        """See RepositoryFormat.get_format_string()."""
 
1280
        return ('Bazaar development format - chk repository with bencode '
 
1281
                'revision serialization (needs bzr.dev from 1.16)\n')
 
1282
 
 
1283
 
 
1284
class RepositoryFormat2a(RepositoryFormatCHK2):
 
1285
    """A CHK repository that uses the bencode revision serializer.
 
1286
 
 
1287
    This is the same as RepositoryFormatCHK2 but with a public name.
 
1288
    """
 
1289
 
 
1290
    _serializer = chk_serializer.chk_bencode_serializer
 
1291
 
 
1292
    def _get_matching_bzrdir(self):
 
1293
        return bzrdir.format_registry.make_bzrdir('2a')
 
1294
 
 
1295
    def _ignore_setting_bzrdir(self, format):
 
1296
        pass
 
1297
 
 
1298
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
1299
 
 
1300
    def get_format_string(self):
 
1301
        return ('Bazaar repository format 2a (needs bzr 1.16 or later)\n')
1406
1302
 
1407
1303
    def get_format_description(self):
1408
1304
        """See RepositoryFormat.get_format_description()."""
1409
1305
        return ("Repository format 2a - rich roots, group compression"
1410
 
                " and chk inventories")
1411
 
 
1412
 
 
1413
 
class RepositoryFormat2aSubtree(RepositoryFormat2a):
1414
 
    """A 2a repository format that supports nested trees.
1415
 
 
1416
 
    """
1417
 
 
1418
 
    def _get_matching_bzrdir(self):
1419
 
        return controldir.format_registry.make_controldir('development-subtree')
1420
 
 
1421
 
    def _ignore_setting_bzrdir(self, format):
1422
 
        pass
1423
 
 
1424
 
    _matchingcontroldir = property(
1425
 
        _get_matching_bzrdir, _ignore_setting_bzrdir)
1426
 
 
1427
 
    @classmethod
1428
 
    def get_format_string(cls):
1429
 
        return b'Bazaar development format 8\n'
1430
 
 
1431
 
    def get_format_description(self):
1432
 
        """See RepositoryFormat.get_format_description()."""
1433
 
        return ("Development repository format 8 - nested trees, "
1434
 
                "group compression and chk inventories")
1435
 
 
1436
 
    experimental = True
1437
 
    supports_tree_reference = True
 
1306
            " and chk inventories")