~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/repository.py

  • Committer: Andrew Bennetts
  • Date: 2010-03-11 04:33:41 UTC
  • mfrom: (4797.33.4 2.1)
  • mto: This revision was merged to the branch mainline in revision 5082.
  • Revision ID: andrew.bennetts@canonical.com-20100311043341-rzdik83fnactjsxs
Merge lp:bzr/2.1, including fixes for #496813, #526211, #526353.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
 
1
# Copyright (C) 2005-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
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
from bzrlib.lazy_import import lazy_import
18
18
lazy_import(globals(), """
23
23
from bzrlib import (
24
24
    bzrdir,
25
25
    check,
 
26
    chk_map,
 
27
    config,
26
28
    debug,
27
29
    errors,
 
30
    fetch as _mod_fetch,
28
31
    fifo_cache,
29
32
    generate_ids,
30
33
    gpg,
31
34
    graph,
 
35
    inventory,
 
36
    inventory_delta,
32
37
    lazy_regex,
33
38
    lockable_files,
34
39
    lockdir,
35
40
    lru_cache,
36
41
    osutils,
37
 
    remote,
38
42
    revision as _mod_revision,
39
43
    symbol_versioning,
 
44
    trace,
40
45
    tsort,
41
46
    ui,
42
47
    versionedfile,
47
52
from bzrlib.testament import Testament
48
53
""")
49
54
 
 
55
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
 
56
from bzrlib.inter import InterObject
 
57
from bzrlib.inventory import (
 
58
    Inventory,
 
59
    InventoryDirectory,
 
60
    ROOT_ID,
 
61
    entry_factory,
 
62
    )
 
63
from bzrlib.lock import _RelockDebugMixin
50
64
from bzrlib import registry
51
 
from bzrlib.decorators import needs_read_lock, needs_write_lock
52
 
from bzrlib.inter import InterObject
53
 
from bzrlib.inventory import Inventory, InventoryDirectory, ROOT_ID
54
 
from bzrlib.symbol_versioning import (
55
 
        deprecated_method,
56
 
        one_one,
57
 
        one_two,
58
 
        one_six,
59
 
        )
60
65
from bzrlib.trace import (
61
66
    log_exception_quietly, note, mutter, mutter_callsite, warning)
62
67
 
126
131
        # valid. Callers that will call record_delete() should call
127
132
        # .will_record_deletes() to indicate that.
128
133
        self._recording_deletes = False
 
134
        # memo'd check for no-op commits.
 
135
        self._any_changes = False
 
136
 
 
137
    def any_changes(self):
 
138
        """Return True if any entries were changed.
 
139
        
 
140
        This includes merge-only changes. It is the core for the --unchanged
 
141
        detection in commit.
 
142
 
 
143
        :return: True if any changes have occured.
 
144
        """
 
145
        return self._any_changes
129
146
 
130
147
    def _validate_unicode_text(self, text, context):
131
148
        """Verify things like commit messages don't have bogus characters."""
176
193
        deserializing the inventory, while we already have a copy in
177
194
        memory.
178
195
        """
 
196
        if self.new_inventory is None:
 
197
            self.new_inventory = self.repository.get_inventory(
 
198
                self._new_revision_id)
179
199
        return RevisionTree(self.repository, self.new_inventory,
180
 
                            self._new_revision_id)
 
200
            self._new_revision_id)
181
201
 
182
202
    def finish_inventory(self):
183
 
        """Tell the builder that the inventory is finished."""
184
 
        if self.new_inventory.root is None:
185
 
            raise AssertionError('Root entry should be supplied to'
186
 
                ' record_entry_contents, as of bzr 0.10.')
187
 
            self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
188
 
        self.new_inventory.revision_id = self._new_revision_id
189
 
        self.inv_sha1 = self.repository.add_inventory(
190
 
            self._new_revision_id,
191
 
            self.new_inventory,
192
 
            self.parents
193
 
            )
 
203
        """Tell the builder that the inventory is finished.
 
204
 
 
205
        :return: The inventory id in the repository, which can be used with
 
206
            repository.get_inventory.
 
207
        """
 
208
        if self.new_inventory is None:
 
209
            # an inventory delta was accumulated without creating a new
 
210
            # inventory.
 
211
            basis_id = self.basis_delta_revision
 
212
            # We ignore the 'inventory' returned by add_inventory_by_delta
 
213
            # because self.new_inventory is used to hint to the rest of the
 
214
            # system what code path was taken
 
215
            self.inv_sha1, _ = self.repository.add_inventory_by_delta(
 
216
                basis_id, self._basis_delta, self._new_revision_id,
 
217
                self.parents)
 
218
        else:
 
219
            if self.new_inventory.root is None:
 
220
                raise AssertionError('Root entry should be supplied to'
 
221
                    ' record_entry_contents, as of bzr 0.10.')
 
222
                self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
 
223
            self.new_inventory.revision_id = self._new_revision_id
 
224
            self.inv_sha1 = self.repository.add_inventory(
 
225
                self._new_revision_id,
 
226
                self.new_inventory,
 
227
                self.parents
 
228
                )
 
229
        return self._new_revision_id
194
230
 
195
231
    def _gen_revision_id(self):
196
232
        """Return new revision-id."""
199
235
 
200
236
    def _generate_revision_if_needed(self):
201
237
        """Create a revision id if None was supplied.
202
 
        
 
238
 
203
239
        If the repository can not support user-specified revision ids
204
240
        they should override this function and raise CannotSetRevisionId
205
241
        if _new_revision_id is not None.
233
269
        # _new_revision_id
234
270
        ie.revision = self._new_revision_id
235
271
 
 
272
    def _require_root_change(self, tree):
 
273
        """Enforce an appropriate root object change.
 
274
 
 
275
        This is called once when record_iter_changes is called, if and only if
 
276
        the root was not in the delta calculated by record_iter_changes.
 
277
 
 
278
        :param tree: The tree which is being committed.
 
279
        """
 
280
        # NB: if there are no parents then this method is not called, so no
 
281
        # need to guard on parents having length.
 
282
        entry = entry_factory['directory'](tree.path2id(''), '',
 
283
            None)
 
284
        entry.revision = self._new_revision_id
 
285
        self._basis_delta.append(('', '', entry.file_id, entry))
 
286
 
236
287
    def _get_delta(self, ie, basis_inv, path):
237
288
        """Get a delta against the basis inventory for ie."""
238
289
        if ie.file_id not in basis_inv:
280
331
            raise AssertionError("recording deletes not activated.")
281
332
        delta = (path, None, file_id, None)
282
333
        self._basis_delta.append(delta)
 
334
        self._any_changes = True
283
335
        return delta
284
336
 
285
337
    def will_record_deletes(self):
290
342
        builder.record_delete().
291
343
        """
292
344
        self._recording_deletes = True
 
345
        try:
 
346
            basis_id = self.parents[0]
 
347
        except IndexError:
 
348
            basis_id = _mod_revision.NULL_REVISION
 
349
        self.basis_delta_revision = basis_id
293
350
 
294
351
    def record_entry_contents(self, ie, parent_invs, path, tree,
295
352
        content_summary):
301
358
        :param parent_invs: The inventories of the parent revisions of the
302
359
            commit.
303
360
        :param path: The path the entry is at in the tree.
304
 
        :param tree: The tree which contains this entry and should be used to 
 
361
        :param tree: The tree which contains this entry and should be used to
305
362
            obtain content.
306
363
        :param content_summary: Summary data from the tree about the paths
307
364
            content - stat, length, exec, sha/link target. This is only
415
472
            if content_summary[2] is None:
416
473
                raise ValueError("Files must not have executable = None")
417
474
            if not store:
418
 
                if (# if the file length changed we have to store:
419
 
                    parent_entry.text_size != content_summary[1] or
420
 
                    # if the exec bit has changed we have to store:
 
475
                # We can't trust a check of the file length because of content
 
476
                # filtering...
 
477
                if (# if the exec bit has changed we have to store:
421
478
                    parent_entry.executable != content_summary[2]):
422
479
                    store = True
423
480
                elif parent_entry.text_sha1 == content_summary[3]:
442
499
            ie.executable = content_summary[2]
443
500
            file_obj, stat_value = tree.get_file_with_stat(ie.file_id, path)
444
501
            try:
445
 
                lines = file_obj.readlines()
 
502
                text = file_obj.read()
446
503
            finally:
447
504
                file_obj.close()
448
505
            try:
449
506
                ie.text_sha1, ie.text_size = self._add_text_to_weave(
450
 
                    ie.file_id, lines, heads, nostore_sha)
 
507
                    ie.file_id, text, heads, nostore_sha)
451
508
                # Let the caller know we generated a stat fingerprint.
452
509
                fingerprint = (ie.text_sha1, stat_value)
453
510
            except errors.ExistingContent:
465
522
                # carry over:
466
523
                ie.revision = parent_entry.revision
467
524
                return self._get_delta(ie, basis_inv, path), False, None
468
 
            lines = []
469
 
            self._add_text_to_weave(ie.file_id, lines, heads, None)
 
525
            self._add_text_to_weave(ie.file_id, '', heads, None)
470
526
        elif kind == 'symlink':
471
527
            current_link_target = content_summary[3]
472
528
            if not store:
480
536
                ie.symlink_target = parent_entry.symlink_target
481
537
                return self._get_delta(ie, basis_inv, path), False, None
482
538
            ie.symlink_target = current_link_target
483
 
            lines = []
484
 
            self._add_text_to_weave(ie.file_id, lines, heads, None)
 
539
            self._add_text_to_weave(ie.file_id, '', heads, None)
485
540
        elif kind == 'tree-reference':
486
541
            if not store:
487
542
                if content_summary[3] != parent_entry.reference_revision:
492
547
                ie.revision = parent_entry.revision
493
548
                return self._get_delta(ie, basis_inv, path), False, None
494
549
            ie.reference_revision = content_summary[3]
495
 
            lines = []
496
 
            self._add_text_to_weave(ie.file_id, lines, heads, None)
 
550
            if ie.reference_revision is None:
 
551
                raise AssertionError("invalid content_summary for nested tree: %r"
 
552
                    % (content_summary,))
 
553
            self._add_text_to_weave(ie.file_id, '', heads, None)
497
554
        else:
498
555
            raise NotImplementedError('unknown kind')
499
556
        ie.revision = self._new_revision_id
 
557
        self._any_changes = True
500
558
        return self._get_delta(ie, basis_inv, path), True, fingerprint
501
559
 
502
 
    def _add_text_to_weave(self, file_id, new_lines, parents, nostore_sha):
503
 
        # Note: as we read the content directly from the tree, we know its not
504
 
        # been turned into unicode or badly split - but a broken tree
505
 
        # implementation could give us bad output from readlines() so this is
506
 
        # not a guarantee of safety. What would be better is always checking
507
 
        # the content during test suite execution. RBC 20070912
508
 
        parent_keys = tuple((file_id, parent) for parent in parents)
509
 
        return self.repository.texts.add_lines(
510
 
            (file_id, self._new_revision_id), parent_keys, new_lines,
511
 
            nostore_sha=nostore_sha, random_id=self.random_revid,
512
 
            check_content=False)[0:2]
 
560
    def record_iter_changes(self, tree, basis_revision_id, iter_changes,
 
561
        _entry_factory=entry_factory):
 
562
        """Record a new tree via iter_changes.
 
563
 
 
564
        :param tree: The tree to obtain text contents from for changed objects.
 
565
        :param basis_revision_id: The revision id of the tree the iter_changes
 
566
            has been generated against. Currently assumed to be the same
 
567
            as self.parents[0] - if it is not, errors may occur.
 
568
        :param iter_changes: An iter_changes iterator with the changes to apply
 
569
            to basis_revision_id. The iterator must not include any items with
 
570
            a current kind of None - missing items must be either filtered out
 
571
            or errored-on beefore record_iter_changes sees the item.
 
572
        :param _entry_factory: Private method to bind entry_factory locally for
 
573
            performance.
 
574
        :return: A generator of (file_id, relpath, fs_hash) tuples for use with
 
575
            tree._observed_sha1.
 
576
        """
 
577
        # Create an inventory delta based on deltas between all the parents and
 
578
        # deltas between all the parent inventories. We use inventory delta's 
 
579
        # between the inventory objects because iter_changes masks
 
580
        # last-changed-field only changes.
 
581
        # Working data:
 
582
        # file_id -> change map, change is fileid, paths, changed, versioneds,
 
583
        # parents, names, kinds, executables
 
584
        merged_ids = {}
 
585
        # {file_id -> revision_id -> inventory entry, for entries in parent
 
586
        # trees that are not parents[0]
 
587
        parent_entries = {}
 
588
        ghost_basis = False
 
589
        try:
 
590
            revtrees = list(self.repository.revision_trees(self.parents))
 
591
        except errors.NoSuchRevision:
 
592
            # one or more ghosts, slow path.
 
593
            revtrees = []
 
594
            for revision_id in self.parents:
 
595
                try:
 
596
                    revtrees.append(self.repository.revision_tree(revision_id))
 
597
                except errors.NoSuchRevision:
 
598
                    if not revtrees:
 
599
                        basis_revision_id = _mod_revision.NULL_REVISION
 
600
                        ghost_basis = True
 
601
                    revtrees.append(self.repository.revision_tree(
 
602
                        _mod_revision.NULL_REVISION))
 
603
        # The basis inventory from a repository 
 
604
        if revtrees:
 
605
            basis_inv = revtrees[0].inventory
 
606
        else:
 
607
            basis_inv = self.repository.revision_tree(
 
608
                _mod_revision.NULL_REVISION).inventory
 
609
        if len(self.parents) > 0:
 
610
            if basis_revision_id != self.parents[0] and not ghost_basis:
 
611
                raise Exception(
 
612
                    "arbitrary basis parents not yet supported with merges")
 
613
            for revtree in revtrees[1:]:
 
614
                for change in revtree.inventory._make_delta(basis_inv):
 
615
                    if change[1] is None:
 
616
                        # Not present in this parent.
 
617
                        continue
 
618
                    if change[2] not in merged_ids:
 
619
                        if change[0] is not None:
 
620
                            basis_entry = basis_inv[change[2]]
 
621
                            merged_ids[change[2]] = [
 
622
                                # basis revid
 
623
                                basis_entry.revision,
 
624
                                # new tree revid
 
625
                                change[3].revision]
 
626
                            parent_entries[change[2]] = {
 
627
                                # basis parent
 
628
                                basis_entry.revision:basis_entry,
 
629
                                # this parent 
 
630
                                change[3].revision:change[3],
 
631
                                }
 
632
                        else:
 
633
                            merged_ids[change[2]] = [change[3].revision]
 
634
                            parent_entries[change[2]] = {change[3].revision:change[3]}
 
635
                    else:
 
636
                        merged_ids[change[2]].append(change[3].revision)
 
637
                        parent_entries[change[2]][change[3].revision] = change[3]
 
638
        else:
 
639
            merged_ids = {}
 
640
        # Setup the changes from the tree:
 
641
        # changes maps file_id -> (change, [parent revision_ids])
 
642
        changes= {}
 
643
        for change in iter_changes:
 
644
            # This probably looks up in basis_inv way to much.
 
645
            if change[1][0] is not None:
 
646
                head_candidate = [basis_inv[change[0]].revision]
 
647
            else:
 
648
                head_candidate = []
 
649
            changes[change[0]] = change, merged_ids.get(change[0],
 
650
                head_candidate)
 
651
        unchanged_merged = set(merged_ids) - set(changes)
 
652
        # Extend the changes dict with synthetic changes to record merges of
 
653
        # texts.
 
654
        for file_id in unchanged_merged:
 
655
            # Record a merged version of these items that did not change vs the
 
656
            # basis. This can be either identical parallel changes, or a revert
 
657
            # of a specific file after a merge. The recorded content will be
 
658
            # that of the current tree (which is the same as the basis), but
 
659
            # the per-file graph will reflect a merge.
 
660
            # NB:XXX: We are reconstructing path information we had, this
 
661
            # should be preserved instead.
 
662
            # inv delta  change: (file_id, (path_in_source, path_in_target),
 
663
            #   changed_content, versioned, parent, name, kind,
 
664
            #   executable)
 
665
            try:
 
666
                basis_entry = basis_inv[file_id]
 
667
            except errors.NoSuchId:
 
668
                # a change from basis->some_parents but file_id isn't in basis
 
669
                # so was new in the merge, which means it must have changed
 
670
                # from basis -> current, and as it hasn't the add was reverted
 
671
                # by the user. So we discard this change.
 
672
                pass
 
673
            else:
 
674
                change = (file_id,
 
675
                    (basis_inv.id2path(file_id), tree.id2path(file_id)),
 
676
                    False, (True, True),
 
677
                    (basis_entry.parent_id, basis_entry.parent_id),
 
678
                    (basis_entry.name, basis_entry.name),
 
679
                    (basis_entry.kind, basis_entry.kind),
 
680
                    (basis_entry.executable, basis_entry.executable))
 
681
                changes[file_id] = (change, merged_ids[file_id])
 
682
        # changes contains tuples with the change and a set of inventory
 
683
        # candidates for the file.
 
684
        # inv delta is:
 
685
        # old_path, new_path, file_id, new_inventory_entry
 
686
        seen_root = False # Is the root in the basis delta?
 
687
        inv_delta = self._basis_delta
 
688
        modified_rev = self._new_revision_id
 
689
        for change, head_candidates in changes.values():
 
690
            if change[3][1]: # versioned in target.
 
691
                # Several things may be happening here:
 
692
                # We may have a fork in the per-file graph
 
693
                #  - record a change with the content from tree
 
694
                # We may have a change against < all trees  
 
695
                #  - carry over the tree that hasn't changed
 
696
                # We may have a change against all trees
 
697
                #  - record the change with the content from tree
 
698
                kind = change[6][1]
 
699
                file_id = change[0]
 
700
                entry = _entry_factory[kind](file_id, change[5][1],
 
701
                    change[4][1])
 
702
                head_set = self._heads(change[0], set(head_candidates))
 
703
                heads = []
 
704
                # Preserve ordering.
 
705
                for head_candidate in head_candidates:
 
706
                    if head_candidate in head_set:
 
707
                        heads.append(head_candidate)
 
708
                        head_set.remove(head_candidate)
 
709
                carried_over = False
 
710
                if len(heads) == 1:
 
711
                    # Could be a carry-over situation:
 
712
                    parent_entry_revs = parent_entries.get(file_id, None)
 
713
                    if parent_entry_revs:
 
714
                        parent_entry = parent_entry_revs.get(heads[0], None)
 
715
                    else:
 
716
                        parent_entry = None
 
717
                    if parent_entry is None:
 
718
                        # The parent iter_changes was called against is the one
 
719
                        # that is the per-file head, so any change is relevant
 
720
                        # iter_changes is valid.
 
721
                        carry_over_possible = False
 
722
                    else:
 
723
                        # could be a carry over situation
 
724
                        # A change against the basis may just indicate a merge,
 
725
                        # we need to check the content against the source of the
 
726
                        # merge to determine if it was changed after the merge
 
727
                        # or carried over.
 
728
                        if (parent_entry.kind != entry.kind or
 
729
                            parent_entry.parent_id != entry.parent_id or
 
730
                            parent_entry.name != entry.name):
 
731
                            # Metadata common to all entries has changed
 
732
                            # against per-file parent
 
733
                            carry_over_possible = False
 
734
                        else:
 
735
                            carry_over_possible = True
 
736
                        # per-type checks for changes against the parent_entry
 
737
                        # are done below.
 
738
                else:
 
739
                    # Cannot be a carry-over situation
 
740
                    carry_over_possible = False
 
741
                # Populate the entry in the delta
 
742
                if kind == 'file':
 
743
                    # XXX: There is still a small race here: If someone reverts the content of a file
 
744
                    # after iter_changes examines and decides it has changed,
 
745
                    # we will unconditionally record a new version even if some
 
746
                    # other process reverts it while commit is running (with
 
747
                    # the revert happening after iter_changes did it's
 
748
                    # examination).
 
749
                    if change[7][1]:
 
750
                        entry.executable = True
 
751
                    else:
 
752
                        entry.executable = False
 
753
                    if (carry_over_possible and
 
754
                        parent_entry.executable == entry.executable):
 
755
                            # Check the file length, content hash after reading
 
756
                            # the file.
 
757
                            nostore_sha = parent_entry.text_sha1
 
758
                    else:
 
759
                        nostore_sha = None
 
760
                    file_obj, stat_value = tree.get_file_with_stat(file_id, change[1][1])
 
761
                    try:
 
762
                        text = file_obj.read()
 
763
                    finally:
 
764
                        file_obj.close()
 
765
                    try:
 
766
                        entry.text_sha1, entry.text_size = self._add_text_to_weave(
 
767
                            file_id, text, heads, nostore_sha)
 
768
                        yield file_id, change[1][1], (entry.text_sha1, stat_value)
 
769
                    except errors.ExistingContent:
 
770
                        # No content change against a carry_over parent
 
771
                        # Perhaps this should also yield a fs hash update?
 
772
                        carried_over = True
 
773
                        entry.text_size = parent_entry.text_size
 
774
                        entry.text_sha1 = parent_entry.text_sha1
 
775
                elif kind == 'symlink':
 
776
                    # Wants a path hint?
 
777
                    entry.symlink_target = tree.get_symlink_target(file_id)
 
778
                    if (carry_over_possible and
 
779
                        parent_entry.symlink_target == entry.symlink_target):
 
780
                        carried_over = True
 
781
                    else:
 
782
                        self._add_text_to_weave(change[0], '', heads, None)
 
783
                elif kind == 'directory':
 
784
                    if carry_over_possible:
 
785
                        carried_over = True
 
786
                    else:
 
787
                        # Nothing to set on the entry.
 
788
                        # XXX: split into the Root and nonRoot versions.
 
789
                        if change[1][1] != '' or self.repository.supports_rich_root():
 
790
                            self._add_text_to_weave(change[0], '', heads, None)
 
791
                elif kind == 'tree-reference':
 
792
                    if not self.repository._format.supports_tree_reference:
 
793
                        # This isn't quite sane as an error, but we shouldn't
 
794
                        # ever see this code path in practice: tree's don't
 
795
                        # permit references when the repo doesn't support tree
 
796
                        # references.
 
797
                        raise errors.UnsupportedOperation(tree.add_reference,
 
798
                            self.repository)
 
799
                    reference_revision = tree.get_reference_revision(change[0])
 
800
                    entry.reference_revision = reference_revision
 
801
                    if (carry_over_possible and
 
802
                        parent_entry.reference_revision == reference_revision):
 
803
                        carried_over = True
 
804
                    else:
 
805
                        self._add_text_to_weave(change[0], '', heads, None)
 
806
                else:
 
807
                    raise AssertionError('unknown kind %r' % kind)
 
808
                if not carried_over:
 
809
                    entry.revision = modified_rev
 
810
                else:
 
811
                    entry.revision = parent_entry.revision
 
812
            else:
 
813
                entry = None
 
814
            new_path = change[1][1]
 
815
            inv_delta.append((change[1][0], new_path, change[0], entry))
 
816
            if new_path == '':
 
817
                seen_root = True
 
818
        self.new_inventory = None
 
819
        if len(inv_delta):
 
820
            # This should perhaps be guarded by a check that the basis we
 
821
            # commit against is the basis for the commit and if not do a delta
 
822
            # against the basis.
 
823
            self._any_changes = True
 
824
        if not seen_root:
 
825
            # housekeeping root entry changes do not affect no-change commits.
 
826
            self._require_root_change(tree)
 
827
        self.basis_delta_revision = basis_revision_id
 
828
 
 
829
    def _add_text_to_weave(self, file_id, new_text, parents, nostore_sha):
 
830
        parent_keys = tuple([(file_id, parent) for parent in parents])
 
831
        return self.repository.texts._add_text(
 
832
            (file_id, self._new_revision_id), parent_keys, new_text,
 
833
            nostore_sha=nostore_sha, random_id=self.random_revid)[0:2]
513
834
 
514
835
 
515
836
class RootCommitBuilder(CommitBuilder):
516
837
    """This commitbuilder actually records the root id"""
517
 
    
 
838
 
518
839
    # the root entry gets versioned properly by this builder.
519
840
    _versioned_root = True
520
841
 
527
848
        :param tree: The tree that is being committed.
528
849
        """
529
850
 
 
851
    def _require_root_change(self, tree):
 
852
        """Enforce an appropriate root object change.
 
853
 
 
854
        This is called once when record_iter_changes is called, if and only if
 
855
        the root was not in the delta calculated by record_iter_changes.
 
856
 
 
857
        :param tree: The tree which is being committed.
 
858
        """
 
859
        # versioned roots do not change unless the tree found a change.
 
860
 
530
861
 
531
862
######################################################################
532
863
# Repositories
533
864
 
534
 
class Repository(object):
 
865
 
 
866
class Repository(_RelockDebugMixin):
535
867
    """Repository holding history for one or more branches.
536
868
 
537
869
    The repository holds and retrieves historical information including
539
871
    which views a particular line of development through that history.
540
872
 
541
873
    The Repository builds on top of some byte storage facilies (the revisions,
542
 
    signatures, inventories and texts attributes) and a Transport, which
543
 
    respectively provide byte storage and a means to access the (possibly
 
874
    signatures, inventories, texts and chk_bytes attributes) and a Transport,
 
875
    which respectively provide byte storage and a means to access the (possibly
544
876
    remote) disk.
545
877
 
546
878
    The byte storage facilities are addressed via tuples, which we refer to
547
879
    as 'keys' throughout the code base. Revision_keys, inventory_keys and
548
880
    signature_keys are all 1-tuples: (revision_id,). text_keys are two-tuples:
549
 
    (file_id, revision_id). We use this interface because it allows low
550
 
    friction with the underlying code that implements disk indices, network
551
 
    encoding and other parts of bzrlib.
 
881
    (file_id, revision_id). chk_bytes uses CHK keys - a 1-tuple with a single
 
882
    byte string made up of a hash identifier and a hash value.
 
883
    We use this interface because it allows low friction with the underlying
 
884
    code that implements disk indices, network encoding and other parts of
 
885
    bzrlib.
552
886
 
553
887
    :ivar revisions: A bzrlib.versionedfile.VersionedFiles instance containing
554
888
        the serialised revisions for the repository. This can be used to obtain
573
907
        The result of trying to insert data into the repository via this store
574
908
        is undefined: it should be considered read-only except for implementors
575
909
        of repositories.
 
910
    :ivar chk_bytes: A bzrlib.versionedfile.VersionedFiles instance containing
 
911
        any data the repository chooses to store or have indexed by its hash.
 
912
        The result of trying to insert data into the repository via this store
 
913
        is undefined: it should be considered read-only except for implementors
 
914
        of repositories.
576
915
    :ivar _transport: Transport for file access to repository, typically
577
916
        pointing to .bzr/repository.
578
917
    """
599
938
        """
600
939
        if self._write_group is not self.get_transaction():
601
940
            # has an unlock or relock occured ?
602
 
            raise errors.BzrError('mismatched lock context and write group.')
 
941
            if suppress_errors:
 
942
                mutter(
 
943
                '(suppressed) mismatched lock context and write group. %r, %r',
 
944
                self._write_group, self.get_transaction())
 
945
                return
 
946
            raise errors.BzrError(
 
947
                'mismatched lock context and write group. %r, %r' %
 
948
                (self._write_group, self.get_transaction()))
603
949
        try:
604
950
            self._abort_write_group()
605
951
        except Exception, exc:
613
959
 
614
960
    def _abort_write_group(self):
615
961
        """Template method for per-repository write group cleanup.
616
 
        
617
 
        This is called during abort before the write group is considered to be 
 
962
 
 
963
        This is called during abort before the write group is considered to be
618
964
        finished and should cleanup any internal state accrued during the write
619
965
        group. There is no requirement that data handed to the repository be
620
966
        *not* made available - this is not a rollback - but neither should any
626
972
 
627
973
    def add_fallback_repository(self, repository):
628
974
        """Add a repository to use for looking up data not held locally.
629
 
        
 
975
 
630
976
        :param repository: A repository.
631
977
        """
632
978
        if not self._format.supports_external_lookups:
633
979
            raise errors.UnstackableRepositoryFormat(self._format, self.base)
 
980
        if self.is_locked():
 
981
            # This repository will call fallback.unlock() when we transition to
 
982
            # the unlocked state, so we make sure to increment the lock count
 
983
            repository.lock_read()
634
984
        self._check_fallback_repository(repository)
635
985
        self._fallback_repositories.append(repository)
636
986
        self.texts.add_fallback_versioned_files(repository.texts)
637
987
        self.inventories.add_fallback_versioned_files(repository.inventories)
638
988
        self.revisions.add_fallback_versioned_files(repository.revisions)
639
989
        self.signatures.add_fallback_versioned_files(repository.signatures)
640
 
        self._fetch_order = 'topological'
 
990
        if self.chk_bytes is not None:
 
991
            self.chk_bytes.add_fallback_versioned_files(repository.chk_bytes)
641
992
 
642
993
    def _check_fallback_repository(self, repository):
643
994
        """Check that this repository can fallback to repository safely.
644
995
 
645
996
        Raise an error if not.
646
 
        
 
997
 
647
998
        :param repository: A repository to fallback to.
648
999
        """
649
1000
        return InterRepository._assert_same_model(self, repository)
650
1001
 
651
1002
    def add_inventory(self, revision_id, inv, parents):
652
1003
        """Add the inventory inv to the repository as revision_id.
653
 
        
 
1004
 
654
1005
        :param parents: The revision ids of the parents that revision_id
655
1006
                        is known to have and are in the repository already.
656
1007
 
667
1018
                % (inv.revision_id, revision_id))
668
1019
        if inv.root is None:
669
1020
            raise AssertionError()
670
 
        inv_lines = self._serialise_inventory_to_lines(inv)
 
1021
        return self._add_inventory_checked(revision_id, inv, parents)
 
1022
 
 
1023
    def _add_inventory_checked(self, revision_id, inv, parents):
 
1024
        """Add inv to the repository after checking the inputs.
 
1025
 
 
1026
        This function can be overridden to allow different inventory styles.
 
1027
 
 
1028
        :seealso: add_inventory, for the contract.
 
1029
        """
 
1030
        inv_lines = self._serializer.write_inventory_to_lines(inv)
671
1031
        return self._inventory_add_lines(revision_id, parents,
672
1032
            inv_lines, check_content=False)
673
1033
 
674
1034
    def add_inventory_by_delta(self, basis_revision_id, delta, new_revision_id,
675
 
                               parents):
 
1035
                               parents, basis_inv=None, propagate_caches=False):
676
1036
        """Add a new inventory expressed as a delta against another revision.
677
1037
 
 
1038
        See the inventory developers documentation for the theory behind
 
1039
        inventory deltas.
 
1040
 
678
1041
        :param basis_revision_id: The inventory id the delta was created
679
1042
            against. (This does not have to be a direct parent.)
680
1043
        :param delta: The inventory delta (see Inventory.apply_delta for
686
1049
            for repositories that depend on the inventory graph for revision
687
1050
            graph access, as well as for those that pun ancestry with delta
688
1051
            compression.
 
1052
        :param basis_inv: The basis inventory if it is already known,
 
1053
            otherwise None.
 
1054
        :param propagate_caches: If True, the caches for this inventory are
 
1055
          copied to and updated for the result if possible.
689
1056
 
690
1057
        :returns: (validator, new_inv)
691
1058
            The validator(which is a sha1 digest, though what is sha'd is
702
1069
            # inventory implementations may support: A better idiom would be to
703
1070
            # return a new inventory, but as there is no revision tree cache in
704
1071
            # repository this is safe for now - RBC 20081013
705
 
            basis_inv = basis_tree.inventory
 
1072
            if basis_inv is None:
 
1073
                basis_inv = basis_tree.inventory
706
1074
            basis_inv.apply_delta(delta)
707
1075
            basis_inv.revision_id = new_revision_id
708
1076
            return (self.add_inventory(new_revision_id, basis_inv, parents),
714
1082
        check_content=True):
715
1083
        """Store lines in inv_vf and return the sha1 of the inventory."""
716
1084
        parents = [(parent,) for parent in parents]
717
 
        return self.inventories.add_lines((revision_id,), parents, lines,
 
1085
        result = self.inventories.add_lines((revision_id,), parents, lines,
718
1086
            check_content=check_content)[0]
 
1087
        self.inventories._access.flush()
 
1088
        return result
719
1089
 
720
1090
    def add_revision(self, revision_id, rev, inv=None, config=None):
721
1091
        """Add rev to the revision store as revision_id.
758
1128
        self.revisions.add_lines(key, parents, osutils.split_lines(text))
759
1129
 
760
1130
    def all_revision_ids(self):
761
 
        """Returns a list of all the revision ids in the repository. 
 
1131
        """Returns a list of all the revision ids in the repository.
762
1132
 
763
1133
        This is conceptually deprecated because code should generally work on
764
1134
        the graph reachable from a particular revision, and ignore any other
770
1140
        return self._all_revision_ids()
771
1141
 
772
1142
    def _all_revision_ids(self):
773
 
        """Returns a list of all the revision ids in the repository. 
 
1143
        """Returns a list of all the revision ids in the repository.
774
1144
 
775
 
        These are in as much topological order as the underlying store can 
 
1145
        These are in as much topological order as the underlying store can
776
1146
        present.
777
1147
        """
778
1148
        raise NotImplementedError(self._all_revision_ids)
797
1167
        # The old API returned a list, should this actually be a set?
798
1168
        return parent_map.keys()
799
1169
 
 
1170
    def _check_inventories(self, checker):
 
1171
        """Check the inventories found from the revision scan.
 
1172
        
 
1173
        This is responsible for verifying the sha1 of inventories and
 
1174
        creating a pending_keys set that covers data referenced by inventories.
 
1175
        """
 
1176
        bar = ui.ui_factory.nested_progress_bar()
 
1177
        try:
 
1178
            self._do_check_inventories(checker, bar)
 
1179
        finally:
 
1180
            bar.finished()
 
1181
 
 
1182
    def _do_check_inventories(self, checker, bar):
 
1183
        """Helper for _check_inventories."""
 
1184
        revno = 0
 
1185
        keys = {'chk_bytes':set(), 'inventories':set(), 'texts':set()}
 
1186
        kinds = ['chk_bytes', 'texts']
 
1187
        count = len(checker.pending_keys)
 
1188
        bar.update("inventories", 0, 2)
 
1189
        current_keys = checker.pending_keys
 
1190
        checker.pending_keys = {}
 
1191
        # Accumulate current checks.
 
1192
        for key in current_keys:
 
1193
            if key[0] != 'inventories' and key[0] not in kinds:
 
1194
                checker._report_items.append('unknown key type %r' % (key,))
 
1195
            keys[key[0]].add(key[1:])
 
1196
        if keys['inventories']:
 
1197
            # NB: output order *should* be roughly sorted - topo or
 
1198
            # inverse topo depending on repository - either way decent
 
1199
            # to just delta against. However, pre-CHK formats didn't
 
1200
            # try to optimise inventory layout on disk. As such the
 
1201
            # pre-CHK code path does not use inventory deltas.
 
1202
            last_object = None
 
1203
            for record in self.inventories.check(keys=keys['inventories']):
 
1204
                if record.storage_kind == 'absent':
 
1205
                    checker._report_items.append(
 
1206
                        'Missing inventory {%s}' % (record.key,))
 
1207
                else:
 
1208
                    last_object = self._check_record('inventories', record,
 
1209
                        checker, last_object,
 
1210
                        current_keys[('inventories',) + record.key])
 
1211
            del keys['inventories']
 
1212
        else:
 
1213
            return
 
1214
        bar.update("texts", 1)
 
1215
        while (checker.pending_keys or keys['chk_bytes']
 
1216
            or keys['texts']):
 
1217
            # Something to check.
 
1218
            current_keys = checker.pending_keys
 
1219
            checker.pending_keys = {}
 
1220
            # Accumulate current checks.
 
1221
            for key in current_keys:
 
1222
                if key[0] not in kinds:
 
1223
                    checker._report_items.append('unknown key type %r' % (key,))
 
1224
                keys[key[0]].add(key[1:])
 
1225
            # Check the outermost kind only - inventories || chk_bytes || texts
 
1226
            for kind in kinds:
 
1227
                if keys[kind]:
 
1228
                    last_object = None
 
1229
                    for record in getattr(self, kind).check(keys=keys[kind]):
 
1230
                        if record.storage_kind == 'absent':
 
1231
                            checker._report_items.append(
 
1232
                                'Missing %s {%s}' % (kind, record.key,))
 
1233
                        else:
 
1234
                            last_object = self._check_record(kind, record,
 
1235
                                checker, last_object, current_keys[(kind,) + record.key])
 
1236
                    keys[kind] = set()
 
1237
                    break
 
1238
 
 
1239
    def _check_record(self, kind, record, checker, last_object, item_data):
 
1240
        """Check a single text from this repository."""
 
1241
        if kind == 'inventories':
 
1242
            rev_id = record.key[0]
 
1243
            inv = self._deserialise_inventory(rev_id,
 
1244
                record.get_bytes_as('fulltext'))
 
1245
            if last_object is not None:
 
1246
                delta = inv._make_delta(last_object)
 
1247
                for old_path, path, file_id, ie in delta:
 
1248
                    if ie is None:
 
1249
                        continue
 
1250
                    ie.check(checker, rev_id, inv)
 
1251
            else:
 
1252
                for path, ie in inv.iter_entries():
 
1253
                    ie.check(checker, rev_id, inv)
 
1254
            if self._format.fast_deltas:
 
1255
                return inv
 
1256
        elif kind == 'chk_bytes':
 
1257
            # No code written to check chk_bytes for this repo format.
 
1258
            checker._report_items.append(
 
1259
                'unsupported key type chk_bytes for %s' % (record.key,))
 
1260
        elif kind == 'texts':
 
1261
            self._check_text(record, checker, item_data)
 
1262
        else:
 
1263
            checker._report_items.append(
 
1264
                'unknown key type %s for %s' % (kind, record.key))
 
1265
 
 
1266
    def _check_text(self, record, checker, item_data):
 
1267
        """Check a single text."""
 
1268
        # Check it is extractable.
 
1269
        # TODO: check length.
 
1270
        if record.storage_kind == 'chunked':
 
1271
            chunks = record.get_bytes_as(record.storage_kind)
 
1272
            sha1 = osutils.sha_strings(chunks)
 
1273
            length = sum(map(len, chunks))
 
1274
        else:
 
1275
            content = record.get_bytes_as('fulltext')
 
1276
            sha1 = osutils.sha_string(content)
 
1277
            length = len(content)
 
1278
        if item_data and sha1 != item_data[1]:
 
1279
            checker._report_items.append(
 
1280
                'sha1 mismatch: %s has sha1 %s expected %s referenced by %s' %
 
1281
                (record.key, sha1, item_data[1], item_data[2]))
 
1282
 
800
1283
    @staticmethod
801
1284
    def create(a_bzrdir):
802
1285
        """Construct the current default format repository in a_bzrdir."""
823
1306
        self._reconcile_does_inventory_gc = True
824
1307
        self._reconcile_fixes_text_parents = False
825
1308
        self._reconcile_backsup_inventory = True
826
 
        # not right yet - should be more semantically clear ? 
827
 
        # 
828
 
        # TODO: make sure to construct the right store classes, etc, depending
829
 
        # on whether escaping is required.
830
 
        self._warn_if_deprecated()
831
1309
        self._write_group = None
832
1310
        # Additional places to query for data.
833
1311
        self._fallback_repositories = []
834
 
        # What order should fetch operations request streams in?
835
 
        # The default is unordered as that is the cheapest for an origin to
836
 
        # provide.
837
 
        self._fetch_order = 'unordered'
838
 
        # Does this repository use deltas that can be fetched as-deltas ?
839
 
        # (E.g. knits, where the knit deltas can be transplanted intact.
840
 
        # We default to False, which will ensure that enough data to get
841
 
        # a full text out of any fetch stream will be grabbed.
842
 
        self._fetch_uses_deltas = False
843
 
        # Should fetch trigger a reconcile after the fetch? Only needed for
844
 
        # some repository formats that can suffer internal inconsistencies.
845
 
        self._fetch_reconcile = False
846
1312
        # An InventoryEntry cache, used during deserialization
847
1313
        self._inventory_entry_cache = fifo_cache.FIFOCache(10*1024)
 
1314
        # Is it safe to return inventory entries directly from the entry cache,
 
1315
        # rather copying them?
 
1316
        self._safe_to_return_from_cache = False
848
1317
 
849
1318
    def __repr__(self):
850
 
        return '%s(%r)' % (self.__class__.__name__,
851
 
                           self.base)
 
1319
        if self._fallback_repositories:
 
1320
            return '%s(%r, fallback_repositories=%r)' % (
 
1321
                self.__class__.__name__,
 
1322
                self.base,
 
1323
                self._fallback_repositories)
 
1324
        else:
 
1325
            return '%s(%r)' % (self.__class__.__name__,
 
1326
                               self.base)
 
1327
 
 
1328
    def _has_same_fallbacks(self, other_repo):
 
1329
        """Returns true if the repositories have the same fallbacks."""
 
1330
        my_fb = self._fallback_repositories
 
1331
        other_fb = other_repo._fallback_repositories
 
1332
        if len(my_fb) != len(other_fb):
 
1333
            return False
 
1334
        for f, g in zip(my_fb, other_fb):
 
1335
            if not f.has_same_location(g):
 
1336
                return False
 
1337
        return True
852
1338
 
853
1339
    def has_same_location(self, other):
854
1340
        """Returns a boolean indicating if this repository is at the same
881
1367
        This causes caching within the repository obejct to start accumlating
882
1368
        data during reads, and allows a 'write_group' to be obtained. Write
883
1369
        groups must be used for actual data insertion.
884
 
        
 
1370
 
885
1371
        :param token: if this is already locked, then lock_write will fail
886
1372
            unless the token matches the existing lock.
887
1373
        :returns: a token if this instance supports tokens, otherwise None.
897
1383
 
898
1384
        XXX: this docstring is duplicated in many places, e.g. lockable_files.py
899
1385
        """
 
1386
        locked = self.is_locked()
900
1387
        result = self.control_files.lock_write(token=token)
901
 
        for repo in self._fallback_repositories:
902
 
            # Writes don't affect fallback repos
903
 
            repo.lock_read()
904
 
        self._refresh_data()
 
1388
        if not locked:
 
1389
            self._warn_if_deprecated()
 
1390
            self._note_lock('w')
 
1391
            for repo in self._fallback_repositories:
 
1392
                # Writes don't affect fallback repos
 
1393
                repo.lock_read()
 
1394
            self._refresh_data()
905
1395
        return result
906
1396
 
907
1397
    def lock_read(self):
 
1398
        locked = self.is_locked()
908
1399
        self.control_files.lock_read()
909
 
        for repo in self._fallback_repositories:
910
 
            repo.lock_read()
911
 
        self._refresh_data()
 
1400
        if not locked:
 
1401
            self._warn_if_deprecated()
 
1402
            self._note_lock('r')
 
1403
            for repo in self._fallback_repositories:
 
1404
                repo.lock_read()
 
1405
            self._refresh_data()
912
1406
 
913
1407
    def get_physical_lock_status(self):
914
1408
        return self.control_files.get_physical_lock_status()
916
1410
    def leave_lock_in_place(self):
917
1411
        """Tell this repository not to release the physical lock when this
918
1412
        object is unlocked.
919
 
        
 
1413
 
920
1414
        If lock_write doesn't return a token, then this method is not supported.
921
1415
        """
922
1416
        self.control_files.leave_in_place()
990
1484
        :param using: If True, list only branches using this repository.
991
1485
        """
992
1486
        if using and not self.is_shared():
993
 
            try:
994
 
                return [self.bzrdir.open_branch()]
995
 
            except errors.NotBranchError:
996
 
                return []
 
1487
            return self.bzrdir.list_branches()
997
1488
        class Evaluator(object):
998
1489
 
999
1490
            def __init__(self):
1008
1499
                    except errors.NoRepositoryPresent:
1009
1500
                        pass
1010
1501
                    else:
1011
 
                        return False, (None, repository)
 
1502
                        return False, ([], repository)
1012
1503
                self.first_call = False
1013
 
                try:
1014
 
                    value = (bzrdir.open_branch(), None)
1015
 
                except errors.NotBranchError:
1016
 
                    value = (None, None)
 
1504
                value = (bzrdir.list_branches(), None)
1017
1505
                return True, value
1018
1506
 
1019
 
        branches = []
1020
 
        for branch, repository in bzrdir.BzrDir.find_bzrdirs(
 
1507
        ret = []
 
1508
        for branches, repository in bzrdir.BzrDir.find_bzrdirs(
1021
1509
                self.bzrdir.root_transport, evaluate=Evaluator()):
1022
 
            if branch is not None:
1023
 
                branches.append(branch)
 
1510
            if branches is not None:
 
1511
                ret.extend(branches)
1024
1512
            if not using and repository is not None:
1025
 
                branches.extend(repository.find_branches())
1026
 
        return branches
 
1513
                ret.extend(repository.find_branches())
 
1514
        return ret
1027
1515
 
1028
1516
    @needs_read_lock
1029
1517
    def search_missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
1030
1518
        """Return the revision ids that other has that this does not.
1031
 
        
 
1519
 
1032
1520
        These are returned in topological order.
1033
1521
 
1034
1522
        revision_id: only return revision ids included by revision_id.
1036
1524
        return InterRepository.get(other, self).search_missing_revision_ids(
1037
1525
            revision_id, find_ghosts)
1038
1526
 
1039
 
    @deprecated_method(one_two)
1040
 
    @needs_read_lock
1041
 
    def missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
1042
 
        """Return the revision ids that other has that this does not.
1043
 
        
1044
 
        These are returned in topological order.
1045
 
 
1046
 
        revision_id: only return revision ids included by revision_id.
1047
 
        """
1048
 
        keys =  self.search_missing_revision_ids(
1049
 
            other, revision_id, find_ghosts).get_keys()
1050
 
        other.lock_read()
1051
 
        try:
1052
 
            parents = other.get_graph().get_parent_map(keys)
1053
 
        finally:
1054
 
            other.unlock()
1055
 
        return tsort.topo_sort(parents)
1056
 
 
1057
1527
    @staticmethod
1058
1528
    def open(base):
1059
1529
        """Open the repository rooted at base.
1066
1536
 
1067
1537
    def copy_content_into(self, destination, revision_id=None):
1068
1538
        """Make a complete copy of the content in self into destination.
1069
 
        
1070
 
        This is a destructive operation! Do not use it on existing 
 
1539
 
 
1540
        This is a destructive operation! Do not use it on existing
1071
1541
        repositories.
1072
1542
        """
1073
1543
        return InterRepository.get(self, destination).copy_content(revision_id)
1076
1546
        """Commit the contents accrued within the current write group.
1077
1547
 
1078
1548
        :seealso: start_write_group.
 
1549
        
 
1550
        :return: it may return an opaque hint that can be passed to 'pack'.
1079
1551
        """
1080
1552
        if self._write_group is not self.get_transaction():
1081
1553
            # has an unlock or relock occured ?
1082
1554
            raise errors.BzrError('mismatched lock context %r and '
1083
1555
                'write group %r.' %
1084
1556
                (self.get_transaction(), self._write_group))
1085
 
        self._commit_write_group()
 
1557
        result = self._commit_write_group()
1086
1558
        self._write_group = None
 
1559
        return result
1087
1560
 
1088
1561
    def _commit_write_group(self):
1089
1562
        """Template method for per-repository write group cleanup.
1090
 
        
1091
 
        This is called before the write group is considered to be 
 
1563
 
 
1564
        This is called before the write group is considered to be
1092
1565
        finished and should ensure that all data handed to the repository
1093
 
        for writing during the write group is safely committed (to the 
 
1566
        for writing during the write group is safely committed (to the
1094
1567
        extent possible considering file system caching etc).
1095
1568
        """
1096
1569
 
1097
 
    def fetch(self, source, revision_id=None, pb=None, find_ghosts=False):
 
1570
    def suspend_write_group(self):
 
1571
        raise errors.UnsuspendableWriteGroup(self)
 
1572
 
 
1573
    def get_missing_parent_inventories(self, check_for_missing_texts=True):
 
1574
        """Return the keys of missing inventory parents for revisions added in
 
1575
        this write group.
 
1576
 
 
1577
        A revision is not complete if the inventory delta for that revision
 
1578
        cannot be calculated.  Therefore if the parent inventories of a
 
1579
        revision are not present, the revision is incomplete, and e.g. cannot
 
1580
        be streamed by a smart server.  This method finds missing inventory
 
1581
        parents for revisions added in this write group.
 
1582
        """
 
1583
        if not self._format.supports_external_lookups:
 
1584
            # This is only an issue for stacked repositories
 
1585
            return set()
 
1586
        if not self.is_in_write_group():
 
1587
            raise AssertionError('not in a write group')
 
1588
 
 
1589
        # XXX: We assume that every added revision already has its
 
1590
        # corresponding inventory, so we only check for parent inventories that
 
1591
        # might be missing, rather than all inventories.
 
1592
        parents = set(self.revisions._index.get_missing_parents())
 
1593
        parents.discard(_mod_revision.NULL_REVISION)
 
1594
        unstacked_inventories = self.inventories._index
 
1595
        present_inventories = unstacked_inventories.get_parent_map(
 
1596
            key[-1:] for key in parents)
 
1597
        parents.difference_update(present_inventories)
 
1598
        if len(parents) == 0:
 
1599
            # No missing parent inventories.
 
1600
            return set()
 
1601
        if not check_for_missing_texts:
 
1602
            return set(('inventories', rev_id) for (rev_id,) in parents)
 
1603
        # Ok, now we have a list of missing inventories.  But these only matter
 
1604
        # if the inventories that reference them are missing some texts they
 
1605
        # appear to introduce.
 
1606
        # XXX: Texts referenced by all added inventories need to be present,
 
1607
        # but at the moment we're only checking for texts referenced by
 
1608
        # inventories at the graph's edge.
 
1609
        key_deps = self.revisions._index._key_dependencies
 
1610
        key_deps.satisfy_refs_for_keys(present_inventories)
 
1611
        referrers = frozenset(r[0] for r in key_deps.get_referrers())
 
1612
        file_ids = self.fileids_altered_by_revision_ids(referrers)
 
1613
        missing_texts = set()
 
1614
        for file_id, version_ids in file_ids.iteritems():
 
1615
            missing_texts.update(
 
1616
                (file_id, version_id) for version_id in version_ids)
 
1617
        present_texts = self.texts.get_parent_map(missing_texts)
 
1618
        missing_texts.difference_update(present_texts)
 
1619
        if not missing_texts:
 
1620
            # No texts are missing, so all revisions and their deltas are
 
1621
            # reconstructable.
 
1622
            return set()
 
1623
        # Alternatively the text versions could be returned as the missing
 
1624
        # keys, but this is likely to be less data.
 
1625
        missing_keys = set(('inventories', rev_id) for (rev_id,) in parents)
 
1626
        return missing_keys
 
1627
 
 
1628
    def refresh_data(self):
 
1629
        """Re-read any data needed to to synchronise with disk.
 
1630
 
 
1631
        This method is intended to be called after another repository instance
 
1632
        (such as one used by a smart server) has inserted data into the
 
1633
        repository. It may not be called during a write group, but may be
 
1634
        called at any other time.
 
1635
        """
 
1636
        if self.is_in_write_group():
 
1637
            raise errors.InternalBzrError(
 
1638
                "May not refresh_data while in a write group.")
 
1639
        self._refresh_data()
 
1640
 
 
1641
    def resume_write_group(self, tokens):
 
1642
        if not self.is_write_locked():
 
1643
            raise errors.NotWriteLocked(self)
 
1644
        if self._write_group:
 
1645
            raise errors.BzrError('already in a write group')
 
1646
        self._resume_write_group(tokens)
 
1647
        # so we can detect unlock/relock - the write group is now entered.
 
1648
        self._write_group = self.get_transaction()
 
1649
 
 
1650
    def _resume_write_group(self, tokens):
 
1651
        raise errors.UnsuspendableWriteGroup(self)
 
1652
 
 
1653
    def fetch(self, source, revision_id=None, pb=None, find_ghosts=False,
 
1654
            fetch_spec=None):
1098
1655
        """Fetch the content required to construct revision_id from source.
1099
1656
 
1100
 
        If revision_id is None all content is copied.
 
1657
        If revision_id is None and fetch_spec is None, then all content is
 
1658
        copied.
 
1659
 
 
1660
        fetch() may not be used when the repository is in a write group -
 
1661
        either finish the current write group before using fetch, or use
 
1662
        fetch before starting the write group.
 
1663
 
1101
1664
        :param find_ghosts: Find and copy revisions in the source that are
1102
1665
            ghosts in the target (and not reachable directly by walking out to
1103
1666
            the first-present revision in target from revision_id).
 
1667
        :param revision_id: If specified, all the content needed for this
 
1668
            revision ID will be copied to the target.  Fetch will determine for
 
1669
            itself which content needs to be copied.
 
1670
        :param fetch_spec: If specified, a SearchResult or
 
1671
            PendingAncestryResult that describes which revisions to copy.  This
 
1672
            allows copying multiple heads at once.  Mutually exclusive with
 
1673
            revision_id.
1104
1674
        """
 
1675
        if fetch_spec is not None and revision_id is not None:
 
1676
            raise AssertionError(
 
1677
                "fetch_spec and revision_id are mutually exclusive.")
 
1678
        if self.is_in_write_group():
 
1679
            raise errors.InternalBzrError(
 
1680
                "May not fetch while in a write group.")
1105
1681
        # fast path same-url fetch operations
1106
 
        if self.has_same_location(source):
 
1682
        # TODO: lift out to somewhere common with RemoteRepository
 
1683
        # <https://bugs.edge.launchpad.net/bzr/+bug/401646>
 
1684
        if (self.has_same_location(source)
 
1685
            and fetch_spec is None
 
1686
            and self._has_same_fallbacks(source)):
1107
1687
            # check that last_revision is in 'from' and then return a
1108
1688
            # no-operation.
1109
1689
            if (revision_id is not None and
1115
1695
        # IncompatibleRepositories when asked to fetch.
1116
1696
        inter = InterRepository.get(source, self)
1117
1697
        return inter.fetch(revision_id=revision_id, pb=pb,
1118
 
            find_ghosts=find_ghosts)
 
1698
            find_ghosts=find_ghosts, fetch_spec=fetch_spec)
1119
1699
 
1120
1700
    def create_bundle(self, target, base, fileobj, format=None):
1121
1701
        return serializer.write_bundle(self, target, base, fileobj, format)
1124
1704
                           timezone=None, committer=None, revprops=None,
1125
1705
                           revision_id=None):
1126
1706
        """Obtain a CommitBuilder for this repository.
1127
 
        
 
1707
 
1128
1708
        :param branch: Branch to commit to.
1129
1709
        :param parents: Revision ids of the parents of the new revision.
1130
1710
        :param config: Configuration to use.
1134
1714
        :param revprops: Optional dictionary of revision properties.
1135
1715
        :param revision_id: Optional revision id.
1136
1716
        """
 
1717
        if self._fallback_repositories:
 
1718
            raise errors.BzrError("Cannot commit from a lightweight checkout "
 
1719
                "to a stacked branch. See "
 
1720
                "https://bugs.launchpad.net/bzr/+bug/375013 for details.")
1137
1721
        result = self._commit_builder_class(self, parents, config,
1138
1722
            timestamp, timezone, committer, revprops, revision_id)
1139
1723
        self.start_write_group()
1140
1724
        return result
1141
1725
 
 
1726
    @only_raises(errors.LockNotHeld, errors.LockBroken)
1142
1727
    def unlock(self):
1143
1728
        if (self.control_files._lock_count == 1 and
1144
1729
            self.control_files._lock_mode == 'w'):
1150
1735
        self.control_files.unlock()
1151
1736
        if self.control_files._lock_count == 0:
1152
1737
            self._inventory_entry_cache.clear()
1153
 
        for repo in self._fallback_repositories:
1154
 
            repo.unlock()
 
1738
            for repo in self._fallback_repositories:
 
1739
                repo.unlock()
1155
1740
 
1156
1741
    @needs_read_lock
1157
1742
    def clone(self, a_bzrdir, revision_id=None):
1192
1777
 
1193
1778
    def _start_write_group(self):
1194
1779
        """Template method for per-repository write group startup.
1195
 
        
1196
 
        This is called before the write group is considered to be 
 
1780
 
 
1781
        This is called before the write group is considered to be
1197
1782
        entered.
1198
1783
        """
1199
1784
 
1220
1805
                dest_repo = a_bzrdir.open_repository()
1221
1806
        return dest_repo
1222
1807
 
 
1808
    def _get_sink(self):
 
1809
        """Return a sink for streaming into this repository."""
 
1810
        return StreamSink(self)
 
1811
 
 
1812
    def _get_source(self, to_format):
 
1813
        """Return a source for streaming from this repository."""
 
1814
        return StreamSource(self, to_format)
 
1815
 
1223
1816
    @needs_read_lock
1224
1817
    def has_revision(self, revision_id):
1225
1818
        """True if this repository has a copy of the revision."""
1248
1841
    @needs_read_lock
1249
1842
    def get_revision_reconcile(self, revision_id):
1250
1843
        """'reconcile' helper routine that allows access to a revision always.
1251
 
        
 
1844
 
1252
1845
        This variant of get_revision does not cross check the weave graph
1253
1846
        against the revision one as get_revision does: but it should only
1254
1847
        be used by reconcile, or reconcile-alike commands that are correcting
1258
1851
 
1259
1852
    @needs_read_lock
1260
1853
    def get_revisions(self, revision_ids):
1261
 
        """Get many revisions at once."""
 
1854
        """Get many revisions at once.
 
1855
        
 
1856
        Repositories that need to check data on every revision read should 
 
1857
        subclass this method.
 
1858
        """
1262
1859
        return self._get_revisions(revision_ids)
1263
1860
 
1264
1861
    @needs_read_lock
1265
1862
    def _get_revisions(self, revision_ids):
1266
1863
        """Core work logic to get many revisions without sanity checks."""
1267
 
        for rev_id in revision_ids:
1268
 
            if not rev_id or not isinstance(rev_id, basestring):
1269
 
                raise errors.InvalidRevisionId(revision_id=rev_id, branch=self)
 
1864
        revs = {}
 
1865
        for revid, rev in self._iter_revisions(revision_ids):
 
1866
            if rev is None:
 
1867
                raise errors.NoSuchRevision(self, revid)
 
1868
            revs[revid] = rev
 
1869
        return [revs[revid] for revid in revision_ids]
 
1870
 
 
1871
    def _iter_revisions(self, revision_ids):
 
1872
        """Iterate over revision objects.
 
1873
 
 
1874
        :param revision_ids: An iterable of revisions to examine. None may be
 
1875
            passed to request all revisions known to the repository. Note that
 
1876
            not all repositories can find unreferenced revisions; for those
 
1877
            repositories only referenced ones will be returned.
 
1878
        :return: An iterator of (revid, revision) tuples. Absent revisions (
 
1879
            those asked for but not available) are returned as (revid, None).
 
1880
        """
 
1881
        if revision_ids is None:
 
1882
            revision_ids = self.all_revision_ids()
 
1883
        else:
 
1884
            for rev_id in revision_ids:
 
1885
                if not rev_id or not isinstance(rev_id, basestring):
 
1886
                    raise errors.InvalidRevisionId(revision_id=rev_id, branch=self)
1270
1887
        keys = [(key,) for key in revision_ids]
1271
1888
        stream = self.revisions.get_record_stream(keys, 'unordered', True)
1272
 
        revs = {}
1273
1889
        for record in stream:
 
1890
            revid = record.key[0]
1274
1891
            if record.storage_kind == 'absent':
1275
 
                raise errors.NoSuchRevision(self, record.key[0])
1276
 
            text = record.get_bytes_as('fulltext')
1277
 
            rev = self._serializer.read_revision_from_string(text)
1278
 
            revs[record.key[0]] = rev
1279
 
        return [revs[revid] for revid in revision_ids]
1280
 
 
1281
 
    @needs_read_lock
1282
 
    def get_revision_xml(self, revision_id):
1283
 
        # TODO: jam 20070210 This shouldn't be necessary since get_revision
1284
 
        #       would have already do it.
1285
 
        # TODO: jam 20070210 Just use _serializer.write_revision_to_string()
1286
 
        rev = self.get_revision(revision_id)
1287
 
        rev_tmp = cStringIO.StringIO()
1288
 
        # the current serializer..
1289
 
        self._serializer.write_revision(rev, rev_tmp)
1290
 
        rev_tmp.seek(0)
1291
 
        return rev_tmp.getvalue()
1292
 
 
1293
 
    def get_deltas_for_revisions(self, revisions):
 
1892
                yield (revid, None)
 
1893
            else:
 
1894
                text = record.get_bytes_as('fulltext')
 
1895
                rev = self._serializer.read_revision_from_string(text)
 
1896
                yield (revid, rev)
 
1897
 
 
1898
    def get_deltas_for_revisions(self, revisions, specific_fileids=None):
1294
1899
        """Produce a generator of revision deltas.
1295
 
        
 
1900
 
1296
1901
        Note that the input is a sequence of REVISIONS, not revision_ids.
1297
1902
        Trees will be held in memory until the generator exits.
1298
1903
        Each delta is relative to the revision's lefthand predecessor.
 
1904
 
 
1905
        :param specific_fileids: if not None, the result is filtered
 
1906
          so that only those file-ids, their parents and their
 
1907
          children are included.
1299
1908
        """
 
1909
        # Get the revision-ids of interest
1300
1910
        required_trees = set()
1301
1911
        for revision in revisions:
1302
1912
            required_trees.add(revision.revision_id)
1303
1913
            required_trees.update(revision.parent_ids[:1])
1304
 
        trees = dict((t.get_revision_id(), t) for 
1305
 
                     t in self.revision_trees(required_trees))
 
1914
 
 
1915
        # Get the matching filtered trees. Note that it's more
 
1916
        # efficient to pass filtered trees to changes_from() rather
 
1917
        # than doing the filtering afterwards. changes_from() could
 
1918
        # arguably do the filtering itself but it's path-based, not
 
1919
        # file-id based, so filtering before or afterwards is
 
1920
        # currently easier.
 
1921
        if specific_fileids is None:
 
1922
            trees = dict((t.get_revision_id(), t) for
 
1923
                t in self.revision_trees(required_trees))
 
1924
        else:
 
1925
            trees = dict((t.get_revision_id(), t) for
 
1926
                t in self._filtered_revision_trees(required_trees,
 
1927
                specific_fileids))
 
1928
 
 
1929
        # Calculate the deltas
1306
1930
        for revision in revisions:
1307
1931
            if not revision.parent_ids:
1308
1932
                old_tree = self.revision_tree(_mod_revision.NULL_REVISION)
1311
1935
            yield trees[revision.revision_id].changes_from(old_tree)
1312
1936
 
1313
1937
    @needs_read_lock
1314
 
    def get_revision_delta(self, revision_id):
 
1938
    def get_revision_delta(self, revision_id, specific_fileids=None):
1315
1939
        """Return the delta for one revision.
1316
1940
 
1317
1941
        The delta is relative to the left-hand predecessor of the
1318
1942
        revision.
 
1943
 
 
1944
        :param specific_fileids: if not None, the result is filtered
 
1945
          so that only those file-ids, their parents and their
 
1946
          children are included.
1319
1947
        """
1320
1948
        r = self.get_revision(revision_id)
1321
 
        return list(self.get_deltas_for_revisions([r]))[0]
 
1949
        return list(self.get_deltas_for_revisions([r],
 
1950
            specific_fileids=specific_fileids))[0]
1322
1951
 
1323
1952
    @needs_write_lock
1324
1953
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1333
1962
    def find_text_key_references(self):
1334
1963
        """Find the text key references within the repository.
1335
1964
 
1336
 
        :return: a dictionary mapping (file_id, revision_id) tuples to altered file-ids to an iterable of
1337
 
        revision_ids. Each altered file-ids has the exact revision_ids that
1338
 
        altered it listed explicitly.
1339
1965
        :return: A dictionary mapping text keys ((fileid, revision_id) tuples)
1340
1966
            to whether they were referred to by the inventory of the
1341
1967
            revision_id that they contain. The inventory texts from all present
1372
1998
 
1373
1999
        # this code needs to read every new line in every inventory for the
1374
2000
        # inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
1375
 
        # not present in one of those inventories is unnecessary but not 
 
2001
        # not present in one of those inventories is unnecessary but not
1376
2002
        # harmful because we are filtering by the revision id marker in the
1377
 
        # inventory lines : we only select file ids altered in one of those  
 
2003
        # inventory lines : we only select file ids altered in one of those
1378
2004
        # revisions. We don't need to see all lines in the inventory because
1379
2005
        # only those added in an inventory in rev X can contain a revision=X
1380
2006
        # line.
1430
2056
                result[key] = True
1431
2057
        return result
1432
2058
 
 
2059
    def _inventory_xml_lines_for_keys(self, keys):
 
2060
        """Get a line iterator of the sort needed for findind references.
 
2061
 
 
2062
        Not relevant for non-xml inventory repositories.
 
2063
 
 
2064
        Ghosts in revision_keys are ignored.
 
2065
 
 
2066
        :param revision_keys: The revision keys for the inventories to inspect.
 
2067
        :return: An iterator over (inventory line, revid) for the fulltexts of
 
2068
            all of the xml inventories specified by revision_keys.
 
2069
        """
 
2070
        stream = self.inventories.get_record_stream(keys, 'unordered', True)
 
2071
        for record in stream:
 
2072
            if record.storage_kind != 'absent':
 
2073
                chunks = record.get_bytes_as('chunked')
 
2074
                revid = record.key[-1]
 
2075
                lines = osutils.chunks_to_lines(chunks)
 
2076
                for line in lines:
 
2077
                    yield line, revid
 
2078
 
1433
2079
    def _find_file_ids_from_xml_inventory_lines(self, line_iterator,
1434
 
        revision_ids):
 
2080
        revision_keys):
1435
2081
        """Helper routine for fileids_altered_by_revision_ids.
1436
2082
 
1437
2083
        This performs the translation of xml lines to revision ids.
1438
2084
 
1439
2085
        :param line_iterator: An iterator of lines, origin_version_id
1440
 
        :param revision_ids: The revision ids to filter for. This should be a
 
2086
        :param revision_keys: The revision ids to filter for. This should be a
1441
2087
            set or other type which supports efficient __contains__ lookups, as
1442
 
            the revision id from each parsed line will be looked up in the
1443
 
            revision_ids filter.
 
2088
            the revision key from each parsed line will be looked up in the
 
2089
            revision_keys filter.
1444
2090
        :return: a dictionary mapping altered file-ids to an iterable of
1445
2091
        revision_ids. Each altered file-ids has the exact revision_ids that
1446
2092
        altered it listed explicitly.
1447
2093
        """
 
2094
        seen = set(self._find_text_key_references_from_xml_inventory_lines(
 
2095
                line_iterator).iterkeys())
 
2096
        parent_keys = self._find_parent_keys_of_revisions(revision_keys)
 
2097
        parent_seen = set(self._find_text_key_references_from_xml_inventory_lines(
 
2098
            self._inventory_xml_lines_for_keys(parent_keys)))
 
2099
        new_keys = seen - parent_seen
1448
2100
        result = {}
1449
2101
        setdefault = result.setdefault
1450
 
        for key in \
1451
 
            self._find_text_key_references_from_xml_inventory_lines(
1452
 
                line_iterator).iterkeys():
1453
 
            # once data is all ensured-consistent; then this is
1454
 
            # if revision_id == version_id
1455
 
            if key[-1:] in revision_ids:
1456
 
                setdefault(key[0], set()).add(key[-1])
 
2102
        for key in new_keys:
 
2103
            setdefault(key[0], set()).add(key[-1])
1457
2104
        return result
1458
2105
 
 
2106
    def _find_parent_ids_of_revisions(self, revision_ids):
 
2107
        """Find all parent ids that are mentioned in the revision graph.
 
2108
 
 
2109
        :return: set of revisions that are parents of revision_ids which are
 
2110
            not part of revision_ids themselves
 
2111
        """
 
2112
        parent_map = self.get_parent_map(revision_ids)
 
2113
        parent_ids = set()
 
2114
        map(parent_ids.update, parent_map.itervalues())
 
2115
        parent_ids.difference_update(revision_ids)
 
2116
        parent_ids.discard(_mod_revision.NULL_REVISION)
 
2117
        return parent_ids
 
2118
 
 
2119
    def _find_parent_keys_of_revisions(self, revision_keys):
 
2120
        """Similar to _find_parent_ids_of_revisions, but used with keys.
 
2121
 
 
2122
        :param revision_keys: An iterable of revision_keys.
 
2123
        :return: The parents of all revision_keys that are not already in
 
2124
            revision_keys
 
2125
        """
 
2126
        parent_map = self.revisions.get_parent_map(revision_keys)
 
2127
        parent_keys = set()
 
2128
        map(parent_keys.update, parent_map.itervalues())
 
2129
        parent_keys.difference_update(revision_keys)
 
2130
        parent_keys.discard(_mod_revision.NULL_REVISION)
 
2131
        return parent_keys
 
2132
 
1459
2133
    def fileids_altered_by_revision_ids(self, revision_ids, _inv_weave=None):
1460
2134
        """Find the file ids and versions affected by revisions.
1461
2135
 
1468
2142
        """
1469
2143
        selected_keys = set((revid,) for revid in revision_ids)
1470
2144
        w = _inv_weave or self.inventories
1471
 
        pb = ui.ui_factory.nested_progress_bar()
1472
 
        try:
1473
 
            return self._find_file_ids_from_xml_inventory_lines(
1474
 
                w.iter_lines_added_or_present_in_keys(
1475
 
                    selected_keys, pb=pb),
1476
 
                selected_keys)
1477
 
        finally:
1478
 
            pb.finished()
 
2145
        return self._find_file_ids_from_xml_inventory_lines(
 
2146
            w.iter_lines_added_or_present_in_keys(
 
2147
                selected_keys, pb=None),
 
2148
            selected_keys)
1479
2149
 
1480
2150
    def iter_files_bytes(self, desired_files):
1481
2151
        """Iterate through file versions.
1502
2172
        for record in self.texts.get_record_stream(text_keys, 'unordered', True):
1503
2173
            if record.storage_kind == 'absent':
1504
2174
                raise errors.RevisionNotPresent(record.key, self)
1505
 
            yield text_keys[record.key], record.get_bytes_as('fulltext')
 
2175
            yield text_keys[record.key], record.get_bytes_as('chunked')
1506
2176
 
1507
2177
    def _generate_text_key_index(self, text_key_references=None,
1508
2178
        ancestors=None):
1557
2227
        batch_size = 10 # should be ~150MB on a 55K path tree
1558
2228
        batch_count = len(revision_order) / batch_size + 1
1559
2229
        processed_texts = 0
1560
 
        pb.update("Calculating text parents.", processed_texts, text_count)
 
2230
        pb.update("Calculating text parents", processed_texts, text_count)
1561
2231
        for offset in xrange(batch_count):
1562
2232
            to_query = revision_order[offset * batch_size:(offset + 1) *
1563
2233
                batch_size]
1564
2234
            if not to_query:
1565
2235
                break
1566
 
            for rev_tree in self.revision_trees(to_query):
1567
 
                revision_id = rev_tree.get_revision_id()
 
2236
            for revision_id in to_query:
1568
2237
                parent_ids = ancestors[revision_id]
1569
2238
                for text_key in revision_keys[revision_id]:
1570
 
                    pb.update("Calculating text parents.", processed_texts)
 
2239
                    pb.update("Calculating text parents", processed_texts)
1571
2240
                    processed_texts += 1
1572
2241
                    candidate_parents = []
1573
2242
                    for parent_id in parent_ids:
1589
2258
                            except KeyError:
1590
2259
                                inv = self.revision_tree(parent_id).inventory
1591
2260
                                inventory_cache[parent_id] = inv
1592
 
                            parent_entry = inv._byid.get(text_key[0], None)
 
2261
                            try:
 
2262
                                parent_entry = inv[text_key[0]]
 
2263
                            except (KeyError, errors.NoSuchId):
 
2264
                                parent_entry = None
1593
2265
                            if parent_entry is not None:
1594
2266
                                parent_text_key = (
1595
2267
                                    text_key[0], parent_entry.revision)
1620
2292
            versions).  knit-kind is one of 'file', 'inventory', 'signatures',
1621
2293
            'revisions'.  file-id is None unless knit-kind is 'file'.
1622
2294
        """
 
2295
        for result in self._find_file_keys_to_fetch(revision_ids, _files_pb):
 
2296
            yield result
 
2297
        del _files_pb
 
2298
        for result in self._find_non_file_keys_to_fetch(revision_ids):
 
2299
            yield result
 
2300
 
 
2301
    def _find_file_keys_to_fetch(self, revision_ids, pb):
1623
2302
        # XXX: it's a bit weird to control the inventory weave caching in this
1624
2303
        # generator.  Ideally the caching would be done in fetch.py I think.  Or
1625
2304
        # maybe this generator should explicitly have the contract that it
1632
2311
        count = 0
1633
2312
        num_file_ids = len(file_ids)
1634
2313
        for file_id, altered_versions in file_ids.iteritems():
1635
 
            if _files_pb is not None:
1636
 
                _files_pb.update("fetch texts", count, num_file_ids)
 
2314
            if pb is not None:
 
2315
                pb.update("Fetch texts", count, num_file_ids)
1637
2316
            count += 1
1638
2317
            yield ("file", file_id, altered_versions)
1639
 
        # We're done with the files_pb.  Note that it finished by the caller,
1640
 
        # just as it was created by the caller.
1641
 
        del _files_pb
1642
2318
 
 
2319
    def _find_non_file_keys_to_fetch(self, revision_ids):
1643
2320
        # inventory
1644
2321
        yield ("inventory", None, revision_ids)
1645
2322
 
1662
2339
        """Get Inventory object by revision id."""
1663
2340
        return self.iter_inventories([revision_id]).next()
1664
2341
 
1665
 
    def iter_inventories(self, revision_ids):
 
2342
    def iter_inventories(self, revision_ids, ordering=None):
1666
2343
        """Get many inventories by revision_ids.
1667
2344
 
1668
2345
        This will buffer some or all of the texts used in constructing the
1669
2346
        inventories in memory, but will only parse a single inventory at a
1670
2347
        time.
1671
2348
 
 
2349
        :param revision_ids: The expected revision ids of the inventories.
 
2350
        :param ordering: optional ordering, e.g. 'topological'.  If not
 
2351
            specified, the order of revision_ids will be preserved (by
 
2352
            buffering if necessary).
1672
2353
        :return: An iterator of inventories.
1673
2354
        """
1674
2355
        if ((None in revision_ids)
1675
2356
            or (_mod_revision.NULL_REVISION in revision_ids)):
1676
2357
            raise ValueError('cannot get null revision inventory')
1677
 
        return self._iter_inventories(revision_ids)
 
2358
        return self._iter_inventories(revision_ids, ordering)
1678
2359
 
1679
 
    def _iter_inventories(self, revision_ids):
 
2360
    def _iter_inventories(self, revision_ids, ordering):
1680
2361
        """single-document based inventory iteration."""
1681
 
        for text, revision_id in self._iter_inventory_xmls(revision_ids):
1682
 
            yield self.deserialise_inventory(revision_id, text)
 
2362
        inv_xmls = self._iter_inventory_xmls(revision_ids, ordering)
 
2363
        for text, revision_id in inv_xmls:
 
2364
            yield self._deserialise_inventory(revision_id, text)
1683
2365
 
1684
 
    def _iter_inventory_xmls(self, revision_ids):
 
2366
    def _iter_inventory_xmls(self, revision_ids, ordering):
 
2367
        if ordering is None:
 
2368
            order_as_requested = True
 
2369
            ordering = 'unordered'
 
2370
        else:
 
2371
            order_as_requested = False
1685
2372
        keys = [(revision_id,) for revision_id in revision_ids]
1686
 
        stream = self.inventories.get_record_stream(keys, 'unordered', True)
 
2373
        if not keys:
 
2374
            return
 
2375
        if order_as_requested:
 
2376
            key_iter = iter(keys)
 
2377
            next_key = key_iter.next()
 
2378
        stream = self.inventories.get_record_stream(keys, ordering, True)
1687
2379
        text_chunks = {}
1688
2380
        for record in stream:
1689
2381
            if record.storage_kind != 'absent':
1690
 
                text_chunks[record.key] = record.get_bytes_as('chunked')
 
2382
                chunks = record.get_bytes_as('chunked')
 
2383
                if order_as_requested:
 
2384
                    text_chunks[record.key] = chunks
 
2385
                else:
 
2386
                    yield ''.join(chunks), record.key[-1]
1691
2387
            else:
1692
2388
                raise errors.NoSuchRevision(self, record.key)
1693
 
        for key in keys:
1694
 
            chunks = text_chunks.pop(key)
1695
 
            yield ''.join(chunks), key[-1]
 
2389
            if order_as_requested:
 
2390
                # Yield as many results as we can while preserving order.
 
2391
                while next_key in text_chunks:
 
2392
                    chunks = text_chunks.pop(next_key)
 
2393
                    yield ''.join(chunks), next_key[-1]
 
2394
                    try:
 
2395
                        next_key = key_iter.next()
 
2396
                    except StopIteration:
 
2397
                        # We still want to fully consume the get_record_stream,
 
2398
                        # just in case it is not actually finished at this point
 
2399
                        next_key = None
 
2400
                        break
1696
2401
 
1697
 
    def deserialise_inventory(self, revision_id, xml):
1698
 
        """Transform the xml into an inventory object. 
 
2402
    def _deserialise_inventory(self, revision_id, xml):
 
2403
        """Transform the xml into an inventory object.
1699
2404
 
1700
2405
        :param revision_id: The expected revision id of the inventory.
1701
2406
        :param xml: A serialised inventory.
1702
2407
        """
1703
2408
        result = self._serializer.read_inventory_from_string(xml, revision_id,
1704
 
                    entry_cache=self._inventory_entry_cache)
 
2409
                    entry_cache=self._inventory_entry_cache,
 
2410
                    return_from_cache=self._safe_to_return_from_cache)
1705
2411
        if result.revision_id != revision_id:
1706
2412
            raise AssertionError('revision id mismatch %s != %s' % (
1707
2413
                result.revision_id, revision_id))
1708
2414
        return result
1709
2415
 
1710
 
    def serialise_inventory(self, inv):
1711
 
        return self._serializer.write_inventory_to_string(inv)
1712
 
 
1713
 
    def _serialise_inventory_to_lines(self, inv):
1714
 
        return self._serializer.write_inventory_to_lines(inv)
1715
 
 
1716
2416
    def get_serializer_format(self):
1717
2417
        return self._serializer.format_num
1718
2418
 
1719
2419
    @needs_read_lock
1720
 
    def get_inventory_xml(self, revision_id):
1721
 
        """Get inventory XML as a file object."""
1722
 
        texts = self._iter_inventory_xmls([revision_id])
 
2420
    def _get_inventory_xml(self, revision_id):
 
2421
        """Get serialized inventory as a string."""
 
2422
        texts = self._iter_inventory_xmls([revision_id], 'unordered')
1723
2423
        try:
1724
2424
            text, revision_id = texts.next()
1725
2425
        except StopIteration:
1726
2426
            raise errors.HistoryMissing(self, 'inventory', revision_id)
1727
2427
        return text
1728
2428
 
1729
 
    @needs_read_lock
1730
 
    def get_inventory_sha1(self, revision_id):
1731
 
        """Return the sha1 hash of the inventory entry
 
2429
    def get_rev_id_for_revno(self, revno, known_pair):
 
2430
        """Return the revision id of a revno, given a later (revno, revid)
 
2431
        pair in the same history.
 
2432
 
 
2433
        :return: if found (True, revid).  If the available history ran out
 
2434
            before reaching the revno, then this returns
 
2435
            (False, (closest_revno, closest_revid)).
1732
2436
        """
1733
 
        return self.get_revision(revision_id).inventory_sha1
 
2437
        known_revno, known_revid = known_pair
 
2438
        partial_history = [known_revid]
 
2439
        distance_from_known = known_revno - revno
 
2440
        if distance_from_known < 0:
 
2441
            raise ValueError(
 
2442
                'requested revno (%d) is later than given known revno (%d)'
 
2443
                % (revno, known_revno))
 
2444
        try:
 
2445
            _iter_for_revno(
 
2446
                self, partial_history, stop_index=distance_from_known)
 
2447
        except errors.RevisionNotPresent, err:
 
2448
            if err.revision_id == known_revid:
 
2449
                # The start revision (known_revid) wasn't found.
 
2450
                raise
 
2451
            # This is a stacked repository with no fallbacks, or a there's a
 
2452
            # left-hand ghost.  Either way, even though the revision named in
 
2453
            # the error isn't in this repo, we know it's the next step in this
 
2454
            # left-hand history.
 
2455
            partial_history.append(err.revision_id)
 
2456
        if len(partial_history) <= distance_from_known:
 
2457
            # Didn't find enough history to get a revid for the revno.
 
2458
            earliest_revno = known_revno - len(partial_history) + 1
 
2459
            return (False, (earliest_revno, partial_history[-1]))
 
2460
        if len(partial_history) - 1 > distance_from_known:
 
2461
            raise AssertionError('_iter_for_revno returned too much history')
 
2462
        return (True, partial_history[-1])
1734
2463
 
1735
2464
    def iter_reverse_revision_history(self, revision_id):
1736
2465
        """Iterate backwards through revision ids in the lefthand history
1743
2472
        while True:
1744
2473
            if next_id in (None, _mod_revision.NULL_REVISION):
1745
2474
                return
 
2475
            try:
 
2476
                parents = graph.get_parent_map([next_id])[next_id]
 
2477
            except KeyError:
 
2478
                raise errors.RevisionNotPresent(next_id, self)
1746
2479
            yield next_id
1747
 
            # Note: The following line may raise KeyError in the event of
1748
 
            # truncated history. We decided not to have a try:except:raise
1749
 
            # RevisionNotPresent here until we see a use for it, because of the
1750
 
            # cost in an inner loop that is by its very nature O(history).
1751
 
            # Robert Collins 20080326
1752
 
            parents = graph.get_parent_map([next_id])[next_id]
1753
2480
            if len(parents) == 0:
1754
2481
                return
1755
2482
            else:
1756
2483
                next_id = parents[0]
1757
2484
 
1758
 
    @needs_read_lock
1759
 
    def get_revision_inventory(self, revision_id):
1760
 
        """Return inventory of a past revision."""
1761
 
        # TODO: Unify this with get_inventory()
1762
 
        # bzr 0.0.6 and later imposes the constraint that the inventory_id
1763
 
        # must be the same as its revision, so this is trivial.
1764
 
        if revision_id is None:
1765
 
            # This does not make sense: if there is no revision,
1766
 
            # then it is the current tree inventory surely ?!
1767
 
            # and thus get_root_id() is something that looks at the last
1768
 
            # commit on the branch, and the get_root_id is an inventory check.
1769
 
            raise NotImplementedError
1770
 
            # return Inventory(self.get_root_id())
1771
 
        else:
1772
 
            return self.get_inventory(revision_id)
1773
 
 
1774
2485
    def is_shared(self):
1775
2486
        """Return True if this repository is flagged as a shared repository."""
1776
2487
        raise NotImplementedError(self.is_shared)
1790
2501
        for repositories to maintain loaded indices across multiple locks
1791
2502
        by checking inside their implementation of this method to see
1792
2503
        whether their indices are still valid. This depends of course on
1793
 
        the disk format being validatable in this manner.
 
2504
        the disk format being validatable in this manner. This method is
 
2505
        also called by the refresh_data() public interface to cause a refresh
 
2506
        to occur while in a write lock so that data inserted by a smart server
 
2507
        push operation is visible on the client's instance of the physical
 
2508
        repository.
1794
2509
        """
1795
2510
 
1796
2511
    @needs_read_lock
1803
2518
        # TODO: refactor this to use an existing revision object
1804
2519
        # so we don't need to read it in twice.
1805
2520
        if revision_id == _mod_revision.NULL_REVISION:
1806
 
            return RevisionTree(self, Inventory(root_id=None), 
 
2521
            return RevisionTree(self, Inventory(root_id=None),
1807
2522
                                _mod_revision.NULL_REVISION)
1808
2523
        else:
1809
 
            inv = self.get_revision_inventory(revision_id)
 
2524
            inv = self.get_inventory(revision_id)
1810
2525
            return RevisionTree(self, inv, revision_id)
1811
2526
 
1812
2527
    def revision_trees(self, revision_ids):
1813
 
        """Return Tree for a revision on this branch.
 
2528
        """Return Trees for revisions in this repository.
1814
2529
 
1815
 
        `revision_id` may not be None or 'null:'"""
 
2530
        :param revision_ids: a sequence of revision-ids;
 
2531
          a revision-id may not be None or 'null:'
 
2532
        """
1816
2533
        inventories = self.iter_inventories(revision_ids)
1817
2534
        for inv in inventories:
1818
2535
            yield RevisionTree(self, inv, inv.revision_id)
1819
2536
 
 
2537
    def _filtered_revision_trees(self, revision_ids, file_ids):
 
2538
        """Return Tree for a revision on this branch with only some files.
 
2539
 
 
2540
        :param revision_ids: a sequence of revision-ids;
 
2541
          a revision-id may not be None or 'null:'
 
2542
        :param file_ids: if not None, the result is filtered
 
2543
          so that only those file-ids, their parents and their
 
2544
          children are included.
 
2545
        """
 
2546
        inventories = self.iter_inventories(revision_ids)
 
2547
        for inv in inventories:
 
2548
            # Should we introduce a FilteredRevisionTree class rather
 
2549
            # than pre-filter the inventory here?
 
2550
            filtered_inv = inv.filter(file_ids)
 
2551
            yield RevisionTree(self, filtered_inv, filtered_inv.revision_id)
 
2552
 
1820
2553
    @needs_read_lock
1821
2554
    def get_ancestry(self, revision_id, topo_sorted=True):
1822
2555
        """Return a list of revision-ids integrated by a revision.
1823
2556
 
1824
 
        The first element of the list is always None, indicating the origin 
1825
 
        revision.  This might change when we have history horizons, or 
 
2557
        The first element of the list is always None, indicating the origin
 
2558
        revision.  This might change when we have history horizons, or
1826
2559
        perhaps we should have a new API.
1827
 
        
 
2560
 
1828
2561
        This is topologically sorted.
1829
2562
        """
1830
2563
        if _mod_revision.is_null(revision_id):
1847
2580
            keys = tsort.topo_sort(parent_map)
1848
2581
        return [None] + list(keys)
1849
2582
 
1850
 
    def pack(self):
 
2583
    def pack(self, hint=None):
1851
2584
        """Compress the data within the repository.
1852
2585
 
1853
2586
        This operation only makes sense for some repository types. For other
1854
2587
        types it should be a no-op that just returns.
1855
2588
 
1856
2589
        This stub method does not require a lock, but subclasses should use
1857
 
        @needs_write_lock as this is a long running call its reasonable to 
 
2590
        @needs_write_lock as this is a long running call its reasonable to
1858
2591
        implicitly lock for the user.
1859
 
        """
1860
2592
 
1861
 
    @needs_read_lock
1862
 
    @deprecated_method(one_six)
1863
 
    def print_file(self, file, revision_id):
1864
 
        """Print `file` to stdout.
1865
 
        
1866
 
        FIXME RBC 20060125 as John Meinel points out this is a bad api
1867
 
        - it writes to stdout, it assumes that that is valid etc. Fix
1868
 
        by creating a new more flexible convenience function.
 
2593
        :param hint: If not supplied, the whole repository is packed.
 
2594
            If supplied, the repository may use the hint parameter as a
 
2595
            hint for the parts of the repository to pack. A hint can be
 
2596
            obtained from the result of commit_write_group(). Out of
 
2597
            date hints are simply ignored, because concurrent operations
 
2598
            can obsolete them rapidly.
1869
2599
        """
1870
 
        tree = self.revision_tree(revision_id)
1871
 
        # use inventory as it was in that revision
1872
 
        file_id = tree.inventory.path2id(file)
1873
 
        if not file_id:
1874
 
            # TODO: jam 20060427 Write a test for this code path
1875
 
            #       it had a bug in it, and was raising the wrong
1876
 
            #       exception.
1877
 
            raise errors.BzrError("%r is not present in revision %s" % (file, revision_id))
1878
 
        tree.print_file(file_id)
1879
2600
 
1880
2601
    def get_transaction(self):
1881
2602
        return self.control_files.get_transaction()
1882
2603
 
1883
 
    @deprecated_method(one_one)
1884
 
    def get_parents(self, revision_ids):
1885
 
        """See StackedParentsProvider.get_parents"""
1886
 
        parent_map = self.get_parent_map(revision_ids)
1887
 
        return [parent_map.get(r, None) for r in revision_ids]
1888
 
 
1889
2604
    def get_parent_map(self, revision_ids):
1890
 
        """See graph._StackedParentsProvider.get_parent_map"""
 
2605
        """See graph.StackedParentsProvider.get_parent_map"""
1891
2606
        # revisions index works in keys; this just works in revisions
1892
2607
        # therefore wrap and unwrap
1893
2608
        query_keys = []
1902
2617
        for ((revision_id,), parent_keys) in \
1903
2618
                self.revisions.get_parent_map(query_keys).iteritems():
1904
2619
            if parent_keys:
1905
 
                result[revision_id] = tuple(parent_revid
1906
 
                    for (parent_revid,) in parent_keys)
 
2620
                result[revision_id] = tuple([parent_revid
 
2621
                    for (parent_revid,) in parent_keys])
1907
2622
            else:
1908
2623
                result[revision_id] = (_mod_revision.NULL_REVISION,)
1909
2624
        return result
1916
2631
        parents_provider = self._make_parents_provider()
1917
2632
        if (other_repository is not None and
1918
2633
            not self.has_same_location(other_repository)):
1919
 
            parents_provider = graph._StackedParentsProvider(
 
2634
            parents_provider = graph.StackedParentsProvider(
1920
2635
                [parents_provider, other_repository._make_parents_provider()])
1921
2636
        return graph.Graph(parents_provider)
1922
2637
 
1923
 
    def _get_versioned_file_checker(self):
1924
 
        """Return an object suitable for checking versioned files."""
1925
 
        return _VersionedFileChecker(self)
 
2638
    def _get_versioned_file_checker(self, text_key_references=None,
 
2639
        ancestors=None):
 
2640
        """Return an object suitable for checking versioned files.
 
2641
        
 
2642
        :param text_key_references: if non-None, an already built
 
2643
            dictionary mapping text keys ((fileid, revision_id) tuples)
 
2644
            to whether they were referred to by the inventory of the
 
2645
            revision_id that they contain. If None, this will be
 
2646
            calculated.
 
2647
        :param ancestors: Optional result from
 
2648
            self.get_graph().get_parent_map(self.all_revision_ids()) if already
 
2649
            available.
 
2650
        """
 
2651
        return _VersionedFileChecker(self,
 
2652
            text_key_references=text_key_references, ancestors=ancestors)
1926
2653
 
1927
2654
    def revision_ids_to_search_result(self, result_set):
1928
2655
        """Convert a set of revision ids to a graph SearchResult."""
1948
2675
                          working trees.
1949
2676
        """
1950
2677
        raise NotImplementedError(self.set_make_working_trees)
1951
 
    
 
2678
 
1952
2679
    def make_working_trees(self):
1953
2680
        """Returns the policy for making working trees on new branches."""
1954
2681
        raise NotImplementedError(self.make_working_trees)
1978
2705
        return record.get_bytes_as('fulltext')
1979
2706
 
1980
2707
    @needs_read_lock
1981
 
    def check(self, revision_ids=None):
 
2708
    def check(self, revision_ids=None, callback_refs=None, check_repo=True):
1982
2709
        """Check consistency of all history of given revision_ids.
1983
2710
 
1984
2711
        Different repository implementations should override _check().
1985
2712
 
1986
2713
        :param revision_ids: A non-empty list of revision_ids whose ancestry
1987
2714
             will be checked.  Typically the last revision_id of a branch.
 
2715
        :param callback_refs: A dict of check-refs to resolve and callback
 
2716
            the check/_check method on the items listed as wanting the ref.
 
2717
            see bzrlib.check.
 
2718
        :param check_repo: If False do not check the repository contents, just 
 
2719
            calculate the data callback_refs requires and call them back.
1988
2720
        """
1989
 
        return self._check(revision_ids)
 
2721
        return self._check(revision_ids, callback_refs=callback_refs,
 
2722
            check_repo=check_repo)
1990
2723
 
1991
 
    def _check(self, revision_ids):
1992
 
        result = check.Check(self)
1993
 
        result.check()
 
2724
    def _check(self, revision_ids, callback_refs, check_repo):
 
2725
        result = check.Check(self, check_repo=check_repo)
 
2726
        result.check(callback_refs)
1994
2727
        return result
1995
2728
 
1996
 
    def _warn_if_deprecated(self):
 
2729
    def _warn_if_deprecated(self, branch=None):
1997
2730
        global _deprecation_warning_done
1998
2731
        if _deprecation_warning_done:
1999
2732
            return
2000
 
        _deprecation_warning_done = True
2001
 
        warning("Format %s for %s is deprecated - please use 'bzr upgrade' to get better performance"
2002
 
                % (self._format, self.bzrdir.transport.base))
 
2733
        try:
 
2734
            if branch is None:
 
2735
                conf = config.GlobalConfig()
 
2736
            else:
 
2737
                conf = branch.get_config()
 
2738
            if conf.suppress_warning('format_deprecation'):
 
2739
                return
 
2740
            warning("Format %s for %s is deprecated -"
 
2741
                    " please use 'bzr upgrade' to get better performance"
 
2742
                    % (self._format, self.bzrdir.transport.base))
 
2743
        finally:
 
2744
            _deprecation_warning_done = True
2003
2745
 
2004
2746
    def supports_rich_root(self):
2005
2747
        return self._format.rich_root_data
2019
2761
                    revision_id.decode('ascii')
2020
2762
                except UnicodeDecodeError:
2021
2763
                    raise errors.NonAsciiRevisionId(method, self)
2022
 
    
 
2764
 
2023
2765
    def revision_graph_can_have_wrong_parents(self):
2024
2766
        """Is it possible for this repository to have a revision graph with
2025
2767
        incorrect parents?
2079
2821
    """
2080
2822
    repository.start_write_group()
2081
2823
    try:
 
2824
        inventory_cache = lru_cache.LRUCache(10)
2082
2825
        for n, (revision, revision_tree, signature) in enumerate(iterable):
2083
 
            _install_revision(repository, revision, revision_tree, signature)
 
2826
            _install_revision(repository, revision, revision_tree, signature,
 
2827
                inventory_cache)
2084
2828
            if pb is not None:
2085
2829
                pb.update('Transferring revisions', n + 1, num_revisions)
2086
2830
    except:
2090
2834
        repository.commit_write_group()
2091
2835
 
2092
2836
 
2093
 
def _install_revision(repository, rev, revision_tree, signature):
 
2837
def _install_revision(repository, rev, revision_tree, signature,
 
2838
    inventory_cache):
2094
2839
    """Install all revision data into a repository."""
2095
2840
    present_parents = []
2096
2841
    parent_trees = {}
2133
2878
        repository.texts.add_lines(text_key, text_parents, lines)
2134
2879
    try:
2135
2880
        # install the inventory
2136
 
        repository.add_inventory(rev.revision_id, inv, present_parents)
 
2881
        if repository._format._commit_inv_deltas and len(rev.parent_ids):
 
2882
            # Cache this inventory
 
2883
            inventory_cache[rev.revision_id] = inv
 
2884
            try:
 
2885
                basis_inv = inventory_cache[rev.parent_ids[0]]
 
2886
            except KeyError:
 
2887
                repository.add_inventory(rev.revision_id, inv, present_parents)
 
2888
            else:
 
2889
                delta = inv._make_delta(basis_inv)
 
2890
                repository.add_inventory_by_delta(rev.parent_ids[0], delta,
 
2891
                    rev.revision_id, present_parents)
 
2892
        else:
 
2893
            repository.add_inventory(rev.revision_id, inv, present_parents)
2137
2894
    except errors.RevisionAlreadyPresent:
2138
2895
        pass
2139
2896
    if signature is not None:
2143
2900
 
2144
2901
class MetaDirRepository(Repository):
2145
2902
    """Repositories in the new meta-dir layout.
2146
 
    
 
2903
 
2147
2904
    :ivar _transport: Transport for access to repository control files,
2148
2905
        typically pointing to .bzr/repository.
2149
2906
    """
2174
2931
        else:
2175
2932
            self._transport.put_bytes('no-working-trees', '',
2176
2933
                mode=self.bzrdir._get_file_mode())
2177
 
    
 
2934
 
2178
2935
    def make_working_trees(self):
2179
2936
        """Returns the policy for making working trees on new branches."""
2180
2937
        return not self._transport.has('no-working-trees')
2188
2945
            control_files)
2189
2946
 
2190
2947
 
2191
 
class RepositoryFormatRegistry(registry.Registry):
2192
 
    """Registry of RepositoryFormats."""
2193
 
 
2194
 
    def get(self, format_string):
2195
 
        r = registry.Registry.get(self, format_string)
2196
 
        if callable(r):
2197
 
            r = r()
2198
 
        return r
2199
 
    
2200
 
 
2201
 
format_registry = RepositoryFormatRegistry()
2202
 
"""Registry of formats, indexed by their identifying format string.
 
2948
network_format_registry = registry.FormatRegistry()
 
2949
"""Registry of formats indexed by their network name.
 
2950
 
 
2951
The network name for a repository format is an identifier that can be used when
 
2952
referring to formats with smart server operations. See
 
2953
RepositoryFormat.network_name() for more detail.
 
2954
"""
 
2955
 
 
2956
 
 
2957
format_registry = registry.FormatRegistry(network_format_registry)
 
2958
"""Registry of formats, indexed by their BzrDirMetaFormat format string.
2203
2959
 
2204
2960
This can contain either format instances themselves, or classes/factories that
2205
2961
can be called to obtain one.
2212
2968
class RepositoryFormat(object):
2213
2969
    """A repository format.
2214
2970
 
2215
 
    Formats provide three things:
 
2971
    Formats provide four things:
2216
2972
     * An initialization routine to construct repository data on disk.
2217
 
     * a format string which is used when the BzrDir supports versioned
2218
 
       children.
 
2973
     * a optional format string which is used when the BzrDir supports
 
2974
       versioned children.
2219
2975
     * an open routine which returns a Repository instance.
 
2976
     * A network name for referring to the format in smart server RPC
 
2977
       methods.
2220
2978
 
2221
2979
    There is one and only one Format subclass for each on-disk format. But
2222
2980
    there can be one Repository subclass that is used for several different
2223
2981
    formats. The _format attribute on a Repository instance can be used to
2224
2982
    determine the disk format.
2225
2983
 
2226
 
    Formats are placed in an dict by their format string for reference 
2227
 
    during opening. These should be subclasses of RepositoryFormat
2228
 
    for consistency.
 
2984
    Formats are placed in a registry by their format string for reference
 
2985
    during opening. These should be subclasses of RepositoryFormat for
 
2986
    consistency.
2229
2987
 
2230
2988
    Once a format is deprecated, just deprecate the initialize and open
2231
 
    methods on the format class. Do not deprecate the object, as the 
2232
 
    object will be created every system load.
 
2989
    methods on the format class. Do not deprecate the object, as the
 
2990
    object may be created even when a repository instance hasn't been
 
2991
    created.
2233
2992
 
2234
2993
    Common instance attributes:
2235
2994
    _matchingbzrdir - the bzrdir format that the repository format was
2244
3003
    # Can this repository be given external locations to lookup additional
2245
3004
    # data. Set to True or False in derived classes.
2246
3005
    supports_external_lookups = None
 
3006
    # Does this format support CHK bytestring lookups. Set to True or False in
 
3007
    # derived classes.
 
3008
    supports_chks = None
 
3009
    # Should commit add an inventory, or an inventory delta to the repository.
 
3010
    _commit_inv_deltas = True
 
3011
    # What order should fetch operations request streams in?
 
3012
    # The default is unordered as that is the cheapest for an origin to
 
3013
    # provide.
 
3014
    _fetch_order = 'unordered'
 
3015
    # Does this repository format use deltas that can be fetched as-deltas ?
 
3016
    # (E.g. knits, where the knit deltas can be transplanted intact.
 
3017
    # We default to False, which will ensure that enough data to get
 
3018
    # a full text out of any fetch stream will be grabbed.
 
3019
    _fetch_uses_deltas = False
 
3020
    # Should fetch trigger a reconcile after the fetch? Only needed for
 
3021
    # some repository formats that can suffer internal inconsistencies.
 
3022
    _fetch_reconcile = False
 
3023
    # Does this format have < O(tree_size) delta generation. Used to hint what
 
3024
    # code path for commit, amongst other things.
 
3025
    fast_deltas = None
 
3026
    # Does doing a pack operation compress data? Useful for the pack UI command
 
3027
    # (so if there is one pack, the operation can still proceed because it may
 
3028
    # help), and for fetching when data won't have come from the same
 
3029
    # compressor.
 
3030
    pack_compresses = False
 
3031
    # Does the repository inventory storage understand references to trees?
 
3032
    supports_tree_reference = None
 
3033
    # Is the format experimental ?
 
3034
    experimental = False
2247
3035
 
2248
3036
    def __str__(self):
2249
3037
        return "<%s>" % self.__class__.__name__
2258
3046
    @classmethod
2259
3047
    def find_format(klass, a_bzrdir):
2260
3048
        """Return the format for the repository object in a_bzrdir.
2261
 
        
 
3049
 
2262
3050
        This is used by bzr native formats that have a "format" file in
2263
 
        the repository.  Other methods may be used by different types of 
 
3051
        the repository.  Other methods may be used by different types of
2264
3052
        control directory.
2265
3053
        """
2266
3054
        try:
2267
3055
            transport = a_bzrdir.get_repository_transport(None)
2268
 
            format_string = transport.get("format").read()
 
3056
            format_string = transport.get_bytes("format")
2269
3057
            return format_registry.get(format_string)
2270
3058
        except errors.NoSuchFile:
2271
3059
            raise errors.NoRepositoryPresent(a_bzrdir)
2280
3068
    @classmethod
2281
3069
    def unregister_format(klass, format):
2282
3070
        format_registry.remove(format.get_format_string())
2283
 
    
 
3071
 
2284
3072
    @classmethod
2285
3073
    def get_default_format(klass):
2286
3074
        """Return the current default format."""
2289
3077
 
2290
3078
    def get_format_string(self):
2291
3079
        """Return the ASCII format string that identifies this format.
2292
 
        
2293
 
        Note that in pre format ?? repositories the format string is 
 
3080
 
 
3081
        Note that in pre format ?? repositories the format string is
2294
3082
        not permitted nor written to disk.
2295
3083
        """
2296
3084
        raise NotImplementedError(self.get_format_string)
2327
3115
        :param a_bzrdir: The bzrdir to put the new repository in it.
2328
3116
        :param shared: The repository should be initialized as a sharable one.
2329
3117
        :returns: The new repository object.
2330
 
        
 
3118
 
2331
3119
        This may raise UninitializableFormat if shared repository are not
2332
3120
        compatible the a_bzrdir.
2333
3121
        """
2337
3125
        """Is this format supported?
2338
3126
 
2339
3127
        Supported formats must be initializable and openable.
2340
 
        Unsupported formats may not support initialization or committing or 
 
3128
        Unsupported formats may not support initialization or committing or
2341
3129
        some other features depending on the reason for not being supported.
2342
3130
        """
2343
3131
        return True
2344
3132
 
 
3133
    def network_name(self):
 
3134
        """A simple byte string uniquely identifying this format for RPC calls.
 
3135
 
 
3136
        MetaDir repository formats use their disk format string to identify the
 
3137
        repository over the wire. All in one formats such as bzr < 0.8, and
 
3138
        foreign formats like svn/git and hg should use some marker which is
 
3139
        unique and immutable.
 
3140
        """
 
3141
        raise NotImplementedError(self.network_name)
 
3142
 
2345
3143
    def check_conversion_target(self, target_format):
2346
 
        raise NotImplementedError(self.check_conversion_target)
 
3144
        if self.rich_root_data and not target_format.rich_root_data:
 
3145
            raise errors.BadConversionTarget(
 
3146
                'Does not support rich root data.', target_format,
 
3147
                from_format=self)
 
3148
        if (self.supports_tree_reference and 
 
3149
            not getattr(target_format, 'supports_tree_reference', False)):
 
3150
            raise errors.BadConversionTarget(
 
3151
                'Does not support nested trees', target_format,
 
3152
                from_format=self)
2347
3153
 
2348
3154
    def open(self, a_bzrdir, _found=False):
2349
3155
        """Return an instance of this format for the bzrdir a_bzrdir.
2350
 
        
 
3156
 
2351
3157
        _found is a private parameter, do not use it.
2352
3158
        """
2353
3159
        raise NotImplementedError(self.open)
2397
3203
        finally:
2398
3204
            control_files.unlock()
2399
3205
 
2400
 
 
2401
 
# formats which have no format string are not discoverable
2402
 
# and not independently creatable, so are not registered.  They're 
 
3206
    def network_name(self):
 
3207
        """Metadir formats have matching disk and network format strings."""
 
3208
        return self.get_format_string()
 
3209
 
 
3210
 
 
3211
# Pre-0.8 formats that don't have a disk format string (because they are
 
3212
# versioned by the matching control directory). We use the control directories
 
3213
# disk format string as a key for the network_name because they meet the
 
3214
# constraints (simple string, unique, immutable).
 
3215
network_format_registry.register_lazy(
 
3216
    "Bazaar-NG branch, format 5\n",
 
3217
    'bzrlib.repofmt.weaverepo',
 
3218
    'RepositoryFormat5',
 
3219
)
 
3220
network_format_registry.register_lazy(
 
3221
    "Bazaar-NG branch, format 6\n",
 
3222
    'bzrlib.repofmt.weaverepo',
 
3223
    'RepositoryFormat6',
 
3224
)
 
3225
 
 
3226
# formats which have no format string are not discoverable or independently
 
3227
# creatable on disk, so are not registered in format_registry.  They're
2403
3228
# all in bzrlib.repofmt.weaverepo now.  When an instance of one of these is
2404
3229
# needed, it's constructed directly by the BzrDir.  Non-native formats where
2405
3230
# the repository is not separately opened are similar.
2472
3297
    'RepositoryFormatKnitPack6RichRoot',
2473
3298
    )
2474
3299
 
2475
 
# Development formats. 
2476
 
# 1.7->1.8 go below here
2477
 
format_registry.register_lazy(
2478
 
    "Bazaar development format 2 (needs bzr.dev from before 1.8)\n",
2479
 
    'bzrlib.repofmt.pack_repo',
2480
 
    'RepositoryFormatPackDevelopment2',
2481
 
    )
 
3300
# Development formats.
 
3301
# Obsolete but kept pending a CHK based subtree format.
2482
3302
format_registry.register_lazy(
2483
3303
    ("Bazaar development format 2 with subtree support "
2484
3304
        "(needs bzr.dev from before 1.8)\n"),
2486
3306
    'RepositoryFormatPackDevelopment2Subtree',
2487
3307
    )
2488
3308
 
 
3309
# 1.14->1.16 go below here
 
3310
format_registry.register_lazy(
 
3311
    'Bazaar development format - group compression and chk inventory'
 
3312
        ' (needs bzr.dev from 1.14)\n',
 
3313
    'bzrlib.repofmt.groupcompress_repo',
 
3314
    'RepositoryFormatCHK1',
 
3315
    )
 
3316
 
 
3317
format_registry.register_lazy(
 
3318
    'Bazaar development format - chk repository with bencode revision '
 
3319
        'serialization (needs bzr.dev from 1.16)\n',
 
3320
    'bzrlib.repofmt.groupcompress_repo',
 
3321
    'RepositoryFormatCHK2',
 
3322
    )
 
3323
format_registry.register_lazy(
 
3324
    'Bazaar repository format 2a (needs bzr 1.16 or later)\n',
 
3325
    'bzrlib.repofmt.groupcompress_repo',
 
3326
    'RepositoryFormat2a',
 
3327
    )
 
3328
 
2489
3329
 
2490
3330
class InterRepository(InterObject):
2491
3331
    """This class represents operations taking place between two repositories.
2492
3332
 
2493
3333
    Its instances have methods like copy_content and fetch, and contain
2494
 
    references to the source and target repositories these operations can be 
 
3334
    references to the source and target repositories these operations can be
2495
3335
    carried out on.
2496
3336
 
2497
3337
    Often we will provide convenience methods on 'repository' which carry out
2499
3339
    InterRepository.get(other).method_name(parameters).
2500
3340
    """
2501
3341
 
2502
 
    _walk_to_common_revisions_batch_size = 1
 
3342
    _walk_to_common_revisions_batch_size = 50
2503
3343
    _optimisers = []
2504
3344
    """The available optimised InterRepository types."""
2505
3345
 
2506
 
    def __init__(self, source, target):
2507
 
        InterObject.__init__(self, source, target)
2508
 
        # These two attributes may be overridden by e.g. InterOtherToRemote to
2509
 
        # provide a faster implementation.
2510
 
        self.target_get_graph = self.target.get_graph
2511
 
        self.target_get_parent_map = self.target.get_parent_map
2512
 
 
 
3346
    @needs_write_lock
2513
3347
    def copy_content(self, revision_id=None):
2514
 
        raise NotImplementedError(self.copy_content)
2515
 
 
2516
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
 
3348
        """Make a complete copy of the content in self into destination.
 
3349
 
 
3350
        This is a destructive operation! Do not use it on existing
 
3351
        repositories.
 
3352
 
 
3353
        :param revision_id: Only copy the content needed to construct
 
3354
                            revision_id and its parents.
 
3355
        """
 
3356
        try:
 
3357
            self.target.set_make_working_trees(self.source.make_working_trees())
 
3358
        except NotImplementedError:
 
3359
            pass
 
3360
        self.target.fetch(self.source, revision_id=revision_id)
 
3361
 
 
3362
    @needs_write_lock
 
3363
    def fetch(self, revision_id=None, pb=None, find_ghosts=False,
 
3364
            fetch_spec=None):
2517
3365
        """Fetch the content required to construct revision_id.
2518
3366
 
2519
3367
        The content is copied from self.source to self.target.
2520
3368
 
2521
3369
        :param revision_id: if None all content is copied, if NULL_REVISION no
2522
3370
                            content is copied.
2523
 
        :param pb: optional progress bar to use for progress reports. If not
2524
 
                   provided a default one will be created.
2525
 
 
2526
 
        :returns: (copied_revision_count, failures).
 
3371
        :param pb: ignored.
 
3372
        :return: None.
2527
3373
        """
2528
 
        # Normally we should find a specific InterRepository subclass to do
2529
 
        # the fetch; if nothing else then at least InterSameDataRepository.
2530
 
        # If none of them is suitable it looks like fetching is not possible;
2531
 
        # we try to give a good message why.  _assert_same_model will probably
2532
 
        # give a helpful message; otherwise a generic one.
2533
 
        self._assert_same_model(self.source, self.target)
2534
 
        raise errors.IncompatibleRepositories(self.source, self.target,
2535
 
            "no suitableInterRepository found")
 
3374
        ui.ui_factory.warn_experimental_format_fetch(self)
 
3375
        f = _mod_fetch.RepoFetcher(to_repository=self.target,
 
3376
                               from_repository=self.source,
 
3377
                               last_revision=revision_id,
 
3378
                               fetch_spec=fetch_spec,
 
3379
                               find_ghosts=find_ghosts)
2536
3380
 
2537
3381
    def _walk_to_common_revisions(self, revision_ids):
2538
3382
        """Walk out from revision_ids in source to revisions target has.
2540
3384
        :param revision_ids: The start point for the search.
2541
3385
        :return: A set of revision ids.
2542
3386
        """
2543
 
        target_graph = self.target_get_graph()
 
3387
        target_graph = self.target.get_graph()
2544
3388
        revision_ids = frozenset(revision_ids)
2545
 
        # Fast path for the case where all the revisions are already in the
2546
 
        # target repo.
2547
 
        # (Although this does incur an extra round trip for the
2548
 
        # fairly common case where the target doesn't already have the revision
2549
 
        # we're pushing.)
2550
 
        if set(target_graph.get_parent_map(revision_ids)) == revision_ids:
2551
 
            return graph.SearchResult(revision_ids, set(), 0, set())
2552
3389
        missing_revs = set()
2553
3390
        source_graph = self.source.get_graph()
2554
3391
        # ensure we don't pay silly lookup costs.
2593
3430
                break
2594
3431
        return searcher.get_result()
2595
3432
 
2596
 
    @deprecated_method(one_two)
2597
 
    @needs_read_lock
2598
 
    def missing_revision_ids(self, revision_id=None, find_ghosts=True):
2599
 
        """Return the revision ids that source has that target does not.
2600
 
        
2601
 
        These are returned in topological order.
2602
 
 
2603
 
        :param revision_id: only return revision ids included by this
2604
 
                            revision_id.
2605
 
        :param find_ghosts: If True find missing revisions in deep history
2606
 
            rather than just finding the surface difference.
2607
 
        """
2608
 
        return list(self.search_missing_revision_ids(
2609
 
            revision_id, find_ghosts).get_keys())
2610
 
 
2611
3433
    @needs_read_lock
2612
3434
    def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
2613
3435
        """Return the revision ids that source has that target does not.
2614
 
        
 
3436
 
2615
3437
        :param revision_id: only return revision ids included by this
2616
3438
                            revision_id.
2617
3439
        :param find_ghosts: If True find missing revisions in deep history
2636
3458
    @staticmethod
2637
3459
    def _same_model(source, target):
2638
3460
        """True if source and target have the same data representation.
2639
 
        
 
3461
 
2640
3462
        Note: this is always called on the base class; overriding it in a
2641
3463
        subclass will have no effect.
2642
3464
        """
2660
3482
 
2661
3483
class InterSameDataRepository(InterRepository):
2662
3484
    """Code for converting between repositories that represent the same data.
2663
 
    
 
3485
 
2664
3486
    Data format and model must match for this to work.
2665
3487
    """
2666
3488
 
2667
3489
    @classmethod
2668
3490
    def _get_repo_format_to_test(self):
2669
3491
        """Repository format for testing with.
2670
 
        
 
3492
 
2671
3493
        InterSameData can pull from subtree to subtree and from non-subtree to
2672
3494
        non-subtree, so we test this with the richest repository format.
2673
3495
        """
2678
3500
    def is_compatible(source, target):
2679
3501
        return InterRepository._same_model(source, target)
2680
3502
 
2681
 
    @needs_write_lock
2682
 
    def copy_content(self, revision_id=None):
2683
 
        """Make a complete copy of the content in self into destination.
2684
 
 
2685
 
        This copies both the repository's revision data, and configuration information
2686
 
        such as the make_working_trees setting.
2687
 
        
2688
 
        This is a destructive operation! Do not use it on existing 
2689
 
        repositories.
2690
 
 
2691
 
        :param revision_id: Only copy the content needed to construct
2692
 
                            revision_id and its parents.
2693
 
        """
2694
 
        try:
2695
 
            self.target.set_make_working_trees(self.source.make_working_trees())
2696
 
        except NotImplementedError:
2697
 
            pass
2698
 
        # but don't bother fetching if we have the needed data now.
2699
 
        if (revision_id not in (None, _mod_revision.NULL_REVISION) and 
2700
 
            self.target.has_revision(revision_id)):
2701
 
            return
2702
 
        self.target.fetch(self.source, revision_id=revision_id)
2703
 
 
2704
 
    @needs_write_lock
2705
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2706
 
        """See InterRepository.fetch()."""
2707
 
        from bzrlib.fetch import RepoFetcher
2708
 
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2709
 
               self.source, self.source._format, self.target,
2710
 
               self.target._format)
2711
 
        f = RepoFetcher(to_repository=self.target,
2712
 
                               from_repository=self.source,
2713
 
                               last_revision=revision_id,
2714
 
                               pb=pb, find_ghosts=find_ghosts)
2715
 
        return f.count_copied, f.failed_revisions
2716
 
 
2717
3503
 
2718
3504
class InterWeaveRepo(InterSameDataRepository):
2719
3505
    """Optimised code paths between Weave based repositories.
2720
 
    
 
3506
 
2721
3507
    This should be in bzrlib/repofmt/weaverepo.py but we have not yet
2722
3508
    implemented lazy inter-object optimisation.
2723
3509
    """
2730
3516
    @staticmethod
2731
3517
    def is_compatible(source, target):
2732
3518
        """Be compatible with known Weave formats.
2733
 
        
 
3519
 
2734
3520
        We don't test for the stores being of specific types because that
2735
 
        could lead to confusing results, and there is no need to be 
 
3521
        could lead to confusing results, and there is no need to be
2736
3522
        overly general.
2737
3523
        """
2738
3524
        from bzrlib.repofmt.weaverepo import (
2749
3535
                                                RepositoryFormat7)))
2750
3536
        except AttributeError:
2751
3537
            return False
2752
 
    
 
3538
 
2753
3539
    @needs_write_lock
2754
3540
    def copy_content(self, revision_id=None):
2755
3541
        """See InterRepository.copy_content()."""
2765
3551
                self.target.texts.insert_record_stream(
2766
3552
                    self.source.texts.get_record_stream(
2767
3553
                        self.source.texts.keys(), 'topological', False))
2768
 
                pb.update('copying inventory', 0, 1)
 
3554
                pb.update('Copying inventory', 0, 1)
2769
3555
                self.target.inventories.insert_record_stream(
2770
3556
                    self.source.inventories.get_record_stream(
2771
3557
                        self.source.inventories.keys(), 'topological', False))
2782
3568
        else:
2783
3569
            self.target.fetch(self.source, revision_id=revision_id)
2784
3570
 
2785
 
    @needs_write_lock
2786
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2787
 
        """See InterRepository.fetch()."""
2788
 
        from bzrlib.fetch import RepoFetcher
2789
 
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2790
 
               self.source, self.source._format, self.target, self.target._format)
2791
 
        f = RepoFetcher(to_repository=self.target,
2792
 
                               from_repository=self.source,
2793
 
                               last_revision=revision_id,
2794
 
                               pb=pb, find_ghosts=find_ghosts)
2795
 
        return f.count_copied, f.failed_revisions
2796
 
 
2797
3571
    @needs_read_lock
2798
3572
    def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
2799
3573
        """See InterRepository.missing_revision_ids()."""
2800
3574
        # we want all revisions to satisfy revision_id in source.
2801
3575
        # but we don't want to stat every file here and there.
2802
 
        # we want then, all revisions other needs to satisfy revision_id 
 
3576
        # we want then, all revisions other needs to satisfy revision_id
2803
3577
        # checked, but not those that we have locally.
2804
 
        # so the first thing is to get a subset of the revisions to 
 
3578
        # so the first thing is to get a subset of the revisions to
2805
3579
        # satisfy revision_id in source, and then eliminate those that
2806
 
        # we do already have. 
2807
 
        # this is slow on high latency connection to self, but as as this
2808
 
        # disk format scales terribly for push anyway due to rewriting 
 
3580
        # we do already have.
 
3581
        # this is slow on high latency connection to self, but as this
 
3582
        # disk format scales terribly for push anyway due to rewriting
2809
3583
        # inventory.weave, this is considered acceptable.
2810
3584
        # - RBC 20060209
2811
3585
        if revision_id is not None:
2831
3605
            # and the tip revision was validated by get_ancestry.
2832
3606
            result_set = required_revisions
2833
3607
        else:
2834
 
            # if we just grabbed the possibly available ids, then 
 
3608
            # if we just grabbed the possibly available ids, then
2835
3609
            # we only have an estimate of whats available and need to validate
2836
3610
            # that against the revision records.
2837
3611
            result_set = set(
2850
3624
    @staticmethod
2851
3625
    def is_compatible(source, target):
2852
3626
        """Be compatible with known Knit formats.
2853
 
        
 
3627
 
2854
3628
        We don't test for the stores being of specific types because that
2855
 
        could lead to confusing results, and there is no need to be 
 
3629
        could lead to confusing results, and there is no need to be
2856
3630
        overly general.
2857
3631
        """
2858
3632
        from bzrlib.repofmt.knitrepo import RepositoryFormatKnit
2863
3637
            return False
2864
3638
        return are_knits and InterRepository._same_model(source, target)
2865
3639
 
2866
 
    @needs_write_lock
2867
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2868
 
        """See InterRepository.fetch()."""
2869
 
        from bzrlib.fetch import RepoFetcher
2870
 
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2871
 
               self.source, self.source._format, self.target, self.target._format)
2872
 
        f = RepoFetcher(to_repository=self.target,
2873
 
                            from_repository=self.source,
2874
 
                            last_revision=revision_id,
2875
 
                            pb=pb, find_ghosts=find_ghosts)
2876
 
        return f.count_copied, f.failed_revisions
2877
 
 
2878
3640
    @needs_read_lock
2879
3641
    def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
2880
3642
        """See InterRepository.missing_revision_ids()."""
2901
3663
            # and the tip revision was validated by get_ancestry.
2902
3664
            result_set = required_revisions
2903
3665
        else:
2904
 
            # if we just grabbed the possibly available ids, then 
 
3666
            # if we just grabbed the possibly available ids, then
2905
3667
            # we only have an estimate of whats available and need to validate
2906
3668
            # that against the revision records.
2907
3669
            result_set = set(
2909
3671
        return self.source.revision_ids_to_search_result(result_set)
2910
3672
 
2911
3673
 
2912
 
class InterPackRepo(InterSameDataRepository):
2913
 
    """Optimised code paths between Pack based repositories."""
2914
 
 
2915
 
    @classmethod
2916
 
    def _get_repo_format_to_test(self):
2917
 
        from bzrlib.repofmt import pack_repo
2918
 
        return pack_repo.RepositoryFormatKnitPack1()
2919
 
 
2920
 
    @staticmethod
2921
 
    def is_compatible(source, target):
2922
 
        """Be compatible with known Pack formats.
2923
 
        
2924
 
        We don't test for the stores being of specific types because that
2925
 
        could lead to confusing results, and there is no need to be 
2926
 
        overly general.
2927
 
        """
2928
 
        from bzrlib.repofmt.pack_repo import RepositoryFormatPack
2929
 
        try:
2930
 
            are_packs = (isinstance(source._format, RepositoryFormatPack) and
2931
 
                isinstance(target._format, RepositoryFormatPack))
2932
 
        except AttributeError:
2933
 
            return False
2934
 
        return are_packs and InterRepository._same_model(source, target)
2935
 
 
2936
 
    @needs_write_lock
2937
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
2938
 
        """See InterRepository.fetch()."""
2939
 
        if (len(self.source._fallback_repositories) > 0 or
2940
 
            len(self.target._fallback_repositories) > 0):
2941
 
            # The pack layer is not aware of fallback repositories, so when
2942
 
            # fetching from a stacked repository or into a stacked repository
2943
 
            # we use the generic fetch logic which uses the VersionedFiles
2944
 
            # attributes on repository.
2945
 
            from bzrlib.fetch import RepoFetcher
2946
 
            fetcher = RepoFetcher(self.target, self.source, revision_id,
2947
 
                                  pb, find_ghosts)
2948
 
            return fetcher.count_copied, fetcher.failed_revisions
2949
 
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
2950
 
               self.source, self.source._format, self.target, self.target._format)
2951
 
        self.count_copied = 0
2952
 
        if revision_id is None:
2953
 
            # TODO:
2954
 
            # everything to do - use pack logic
2955
 
            # to fetch from all packs to one without
2956
 
            # inventory parsing etc, IFF nothing to be copied is in the target.
2957
 
            # till then:
2958
 
            source_revision_ids = frozenset(self.source.all_revision_ids())
2959
 
            revision_ids = source_revision_ids - \
2960
 
                frozenset(self.target_get_parent_map(source_revision_ids))
2961
 
            revision_keys = [(revid,) for revid in revision_ids]
2962
 
            target_pack_collection = self._get_target_pack_collection()
2963
 
            index = target_pack_collection.revision_index.combined_index
2964
 
            present_revision_ids = set(item[1][0] for item in
2965
 
                index.iter_entries(revision_keys))
2966
 
            revision_ids = set(revision_ids) - present_revision_ids
2967
 
            # implementing the TODO will involve:
2968
 
            # - detecting when all of a pack is selected
2969
 
            # - avoiding as much as possible pre-selection, so the
2970
 
            # more-core routines such as create_pack_from_packs can filter in
2971
 
            # a just-in-time fashion. (though having a HEADS list on a
2972
 
            # repository might make this a lot easier, because we could
2973
 
            # sensibly detect 'new revisions' without doing a full index scan.
2974
 
        elif _mod_revision.is_null(revision_id):
2975
 
            # nothing to do:
2976
 
            return (0, [])
2977
 
        else:
2978
 
            try:
2979
 
                revision_ids = self.search_missing_revision_ids(revision_id,
2980
 
                    find_ghosts=find_ghosts).get_keys()
2981
 
            except errors.NoSuchRevision:
2982
 
                raise errors.InstallFailed([revision_id])
2983
 
            if len(revision_ids) == 0:
2984
 
                return (0, [])
2985
 
        return self._pack(self.source, self.target, revision_ids)
2986
 
 
2987
 
    def _pack(self, source, target, revision_ids):
2988
 
        from bzrlib.repofmt.pack_repo import Packer
2989
 
        target_pack_collection = self._get_target_pack_collection()
2990
 
        packs = source._pack_collection.all_packs()
2991
 
        pack = Packer(target_pack_collection, packs, '.fetch',
2992
 
            revision_ids).pack()
2993
 
        if pack is not None:
2994
 
            target_pack_collection._save_pack_names()
2995
 
            copied_revs = pack.get_revision_count()
2996
 
            # Trigger an autopack. This may duplicate effort as we've just done
2997
 
            # a pack creation, but for now it is simpler to think about as
2998
 
            # 'upload data, then repack if needed'.
2999
 
            self._autopack()
3000
 
            return (copied_revs, [])
3001
 
        else:
3002
 
            return (0, [])
3003
 
 
3004
 
    def _autopack(self):
3005
 
        self.target._pack_collection.autopack()
3006
 
        
3007
 
    def _get_target_pack_collection(self):
3008
 
        return self.target._pack_collection
3009
 
 
3010
 
    @needs_read_lock
3011
 
    def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
3012
 
        """See InterRepository.missing_revision_ids().
3013
 
        
3014
 
        :param find_ghosts: Find ghosts throughout the ancestry of
3015
 
            revision_id.
3016
 
        """
3017
 
        if not find_ghosts and revision_id is not None:
3018
 
            return self._walk_to_common_revisions([revision_id])
3019
 
        elif revision_id is not None:
3020
 
            # Find ghosts: search for revisions pointing from one repository to
3021
 
            # the other, and vice versa, anywhere in the history of revision_id.
3022
 
            graph = self.target_get_graph(other_repository=self.source)
3023
 
            searcher = graph._make_breadth_first_searcher([revision_id])
3024
 
            found_ids = set()
3025
 
            while True:
3026
 
                try:
3027
 
                    next_revs, ghosts = searcher.next_with_ghosts()
3028
 
                except StopIteration:
3029
 
                    break
3030
 
                if revision_id in ghosts:
3031
 
                    raise errors.NoSuchRevision(self.source, revision_id)
3032
 
                found_ids.update(next_revs)
3033
 
                found_ids.update(ghosts)
3034
 
            found_ids = frozenset(found_ids)
3035
 
            # Double query here: should be able to avoid this by changing the
3036
 
            # graph api further.
3037
 
            result_set = found_ids - frozenset(
3038
 
                self.target_get_parent_map(found_ids))
3039
 
        else:
3040
 
            source_ids = self.source.all_revision_ids()
3041
 
            # source_ids is the worst possible case we may need to pull.
3042
 
            # now we want to filter source_ids against what we actually
3043
 
            # have in target, but don't try to check for existence where we know
3044
 
            # we do not have a revision as that would be pointless.
3045
 
            target_ids = set(self.target.all_revision_ids())
3046
 
            result_set = set(source_ids).difference(target_ids)
3047
 
        return self.source.revision_ids_to_search_result(result_set)
3048
 
 
3049
 
 
3050
 
class InterModel1and2(InterRepository):
3051
 
 
3052
 
    @classmethod
3053
 
    def _get_repo_format_to_test(self):
3054
 
        return None
3055
 
 
3056
 
    @staticmethod
3057
 
    def is_compatible(source, target):
3058
 
        if not source.supports_rich_root() and target.supports_rich_root():
3059
 
            return True
3060
 
        else:
3061
 
            return False
3062
 
 
3063
 
    @needs_write_lock
3064
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
3065
 
        """See InterRepository.fetch()."""
3066
 
        from bzrlib.fetch import Model1toKnit2Fetcher
3067
 
        f = Model1toKnit2Fetcher(to_repository=self.target,
3068
 
                                 from_repository=self.source,
3069
 
                                 last_revision=revision_id,
3070
 
                                 pb=pb, find_ghosts=find_ghosts)
3071
 
        return f.count_copied, f.failed_revisions
3072
 
 
3073
 
    @needs_write_lock
3074
 
    def copy_content(self, revision_id=None):
3075
 
        """Make a complete copy of the content in self into destination.
3076
 
        
3077
 
        This is a destructive operation! Do not use it on existing 
3078
 
        repositories.
3079
 
 
3080
 
        :param revision_id: Only copy the content needed to construct
3081
 
                            revision_id and its parents.
3082
 
        """
3083
 
        try:
3084
 
            self.target.set_make_working_trees(self.source.make_working_trees())
3085
 
        except NotImplementedError:
3086
 
            pass
3087
 
        # but don't bother fetching if we have the needed data now.
3088
 
        if (revision_id not in (None, _mod_revision.NULL_REVISION) and 
3089
 
            self.target.has_revision(revision_id)):
3090
 
            return
3091
 
        self.target.fetch(self.source, revision_id=revision_id)
3092
 
 
3093
 
 
3094
 
class InterKnit1and2(InterKnitRepo):
3095
 
 
3096
 
    @classmethod
3097
 
    def _get_repo_format_to_test(self):
3098
 
        return None
3099
 
 
3100
 
    @staticmethod
3101
 
    def is_compatible(source, target):
3102
 
        """Be compatible with Knit1 source and Knit3 target"""
3103
 
        try:
3104
 
            from bzrlib.repofmt.knitrepo import (
3105
 
                RepositoryFormatKnit1,
3106
 
                RepositoryFormatKnit3,
3107
 
                )
3108
 
            from bzrlib.repofmt.pack_repo import (
3109
 
                RepositoryFormatKnitPack1,
3110
 
                RepositoryFormatKnitPack3,
3111
 
                RepositoryFormatKnitPack4,
3112
 
                RepositoryFormatKnitPack5,
3113
 
                RepositoryFormatKnitPack5RichRoot,
3114
 
                RepositoryFormatKnitPack6,
3115
 
                RepositoryFormatKnitPack6RichRoot,
3116
 
                RepositoryFormatPackDevelopment2,
3117
 
                RepositoryFormatPackDevelopment2Subtree,
3118
 
                )
3119
 
            norichroot = (
3120
 
                RepositoryFormatKnit1,            # no rr, no subtree
3121
 
                RepositoryFormatKnitPack1,        # no rr, no subtree
3122
 
                RepositoryFormatPackDevelopment2, # no rr, no subtree
3123
 
                RepositoryFormatKnitPack5,        # no rr, no subtree
3124
 
                RepositoryFormatKnitPack6,        # no rr, no subtree
3125
 
                )
3126
 
            richroot = (
3127
 
                RepositoryFormatKnit3,            # rr, subtree
3128
 
                RepositoryFormatKnitPack3,        # rr, subtree
3129
 
                RepositoryFormatKnitPack4,        # rr, no subtree
3130
 
                RepositoryFormatKnitPack5RichRoot,# rr, no subtree
3131
 
                RepositoryFormatKnitPack6RichRoot,# rr, no subtree
3132
 
                RepositoryFormatPackDevelopment2Subtree, # rr, subtree
3133
 
                )
3134
 
            for format in norichroot:
3135
 
                if format.rich_root_data:
3136
 
                    raise AssertionError('Format %s is a rich-root format'
3137
 
                        ' but is included in the non-rich-root list'
3138
 
                        % (format,))
3139
 
            for format in richroot:
3140
 
                if not format.rich_root_data:
3141
 
                    raise AssertionError('Format %s is not a rich-root format'
3142
 
                        ' but is included in the rich-root list'
3143
 
                        % (format,))
3144
 
            # TODO: One alternative is to just check format.rich_root_data,
3145
 
            #       instead of keeping membership lists. However, the formats
3146
 
            #       *also* have to use the same 'Knit' style of storage
3147
 
            #       (line-deltas, fulltexts, etc.)
3148
 
            return (isinstance(source._format, norichroot) and
3149
 
                    isinstance(target._format, richroot))
3150
 
        except AttributeError:
3151
 
            return False
3152
 
 
3153
 
    @needs_write_lock
3154
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
3155
 
        """See InterRepository.fetch()."""
3156
 
        from bzrlib.fetch import Knit1to2Fetcher
3157
 
        mutter("Using fetch logic to copy between %s(%s) and %s(%s)",
3158
 
               self.source, self.source._format, self.target, 
3159
 
               self.target._format)
3160
 
        f = Knit1to2Fetcher(to_repository=self.target,
3161
 
                            from_repository=self.source,
3162
 
                            last_revision=revision_id,
3163
 
                            pb=pb, find_ghosts=find_ghosts)
3164
 
        return f.count_copied, f.failed_revisions
3165
 
 
3166
 
 
3167
 
class InterDifferingSerializer(InterKnitRepo):
 
3674
class InterDifferingSerializer(InterRepository):
3168
3675
 
3169
3676
    @classmethod
3170
3677
    def _get_repo_format_to_test(self):
3173
3680
    @staticmethod
3174
3681
    def is_compatible(source, target):
3175
3682
        """Be compatible with Knit2 source and Knit3 target"""
3176
 
        if source.supports_rich_root() != target.supports_rich_root():
3177
 
            return False
3178
 
        # Ideally, we'd support fetching if the source had no tree references
3179
 
        # even if it supported them...
3180
 
        if (getattr(source, '_format.supports_tree_reference', False) and
3181
 
            not getattr(target, '_format.supports_tree_reference', False)):
 
3683
        # This is redundant with format.check_conversion_target(), however that
 
3684
        # raises an exception, and we just want to say "False" as in we won't
 
3685
        # support converting between these formats.
 
3686
        if 'IDS_never' in debug.debug_flags:
 
3687
            return False
 
3688
        if source.supports_rich_root() and not target.supports_rich_root():
 
3689
            return False
 
3690
        if (source._format.supports_tree_reference
 
3691
            and not target._format.supports_tree_reference):
 
3692
            return False
 
3693
        if target._fallback_repositories and target._format.supports_chks:
 
3694
            # IDS doesn't know how to copy CHKs for the parent inventories it
 
3695
            # adds to stacked repos.
 
3696
            return False
 
3697
        if 'IDS_always' in debug.debug_flags:
 
3698
            return True
 
3699
        # Only use this code path for local source and target.  IDS does far
 
3700
        # too much IO (both bandwidth and roundtrips) over a network.
 
3701
        if not source.bzrdir.transport.base.startswith('file:///'):
 
3702
            return False
 
3703
        if not target.bzrdir.transport.base.startswith('file:///'):
3182
3704
            return False
3183
3705
        return True
3184
3706
 
3185
 
    def _fetch_batch(self, revision_ids, basis_id, basis_tree):
 
3707
    def _get_trees(self, revision_ids, cache):
 
3708
        possible_trees = []
 
3709
        for rev_id in revision_ids:
 
3710
            if rev_id in cache:
 
3711
                possible_trees.append((rev_id, cache[rev_id]))
 
3712
            else:
 
3713
                # Not cached, but inventory might be present anyway.
 
3714
                try:
 
3715
                    tree = self.source.revision_tree(rev_id)
 
3716
                except errors.NoSuchRevision:
 
3717
                    # Nope, parent is ghost.
 
3718
                    pass
 
3719
                else:
 
3720
                    cache[rev_id] = tree
 
3721
                    possible_trees.append((rev_id, tree))
 
3722
        return possible_trees
 
3723
 
 
3724
    def _get_delta_for_revision(self, tree, parent_ids, possible_trees):
 
3725
        """Get the best delta and base for this revision.
 
3726
 
 
3727
        :return: (basis_id, delta)
 
3728
        """
 
3729
        deltas = []
 
3730
        # Generate deltas against each tree, to find the shortest.
 
3731
        texts_possibly_new_in_tree = set()
 
3732
        for basis_id, basis_tree in possible_trees:
 
3733
            delta = tree.inventory._make_delta(basis_tree.inventory)
 
3734
            for old_path, new_path, file_id, new_entry in delta:
 
3735
                if new_path is None:
 
3736
                    # This file_id isn't present in the new rev, so we don't
 
3737
                    # care about it.
 
3738
                    continue
 
3739
                if not new_path:
 
3740
                    # Rich roots are handled elsewhere...
 
3741
                    continue
 
3742
                kind = new_entry.kind
 
3743
                if kind != 'directory' and kind != 'file':
 
3744
                    # No text record associated with this inventory entry.
 
3745
                    continue
 
3746
                # This is a directory or file that has changed somehow.
 
3747
                texts_possibly_new_in_tree.add((file_id, new_entry.revision))
 
3748
            deltas.append((len(delta), basis_id, delta))
 
3749
        deltas.sort()
 
3750
        return deltas[0][1:]
 
3751
 
 
3752
    def _fetch_parent_invs_for_stacking(self, parent_map, cache):
 
3753
        """Find all parent revisions that are absent, but for which the
 
3754
        inventory is present, and copy those inventories.
 
3755
 
 
3756
        This is necessary to preserve correctness when the source is stacked
 
3757
        without fallbacks configured.  (Note that in cases like upgrade the
 
3758
        source may be not have _fallback_repositories even though it is
 
3759
        stacked.)
 
3760
        """
 
3761
        parent_revs = set()
 
3762
        for parents in parent_map.values():
 
3763
            parent_revs.update(parents)
 
3764
        present_parents = self.source.get_parent_map(parent_revs)
 
3765
        absent_parents = set(parent_revs).difference(present_parents)
 
3766
        parent_invs_keys_for_stacking = self.source.inventories.get_parent_map(
 
3767
            (rev_id,) for rev_id in absent_parents)
 
3768
        parent_inv_ids = [key[-1] for key in parent_invs_keys_for_stacking]
 
3769
        for parent_tree in self.source.revision_trees(parent_inv_ids):
 
3770
            current_revision_id = parent_tree.get_revision_id()
 
3771
            parents_parents_keys = parent_invs_keys_for_stacking[
 
3772
                (current_revision_id,)]
 
3773
            parents_parents = [key[-1] for key in parents_parents_keys]
 
3774
            basis_id = _mod_revision.NULL_REVISION
 
3775
            basis_tree = self.source.revision_tree(basis_id)
 
3776
            delta = parent_tree.inventory._make_delta(basis_tree.inventory)
 
3777
            self.target.add_inventory_by_delta(
 
3778
                basis_id, delta, current_revision_id, parents_parents)
 
3779
            cache[current_revision_id] = parent_tree
 
3780
 
 
3781
    def _fetch_batch(self, revision_ids, basis_id, cache, a_graph=None):
3186
3782
        """Fetch across a few revisions.
3187
3783
 
3188
3784
        :param revision_ids: The revisions to copy
3189
 
        :param basis_id: The revision_id of basis_tree
3190
 
        :param basis_tree: A tree that is not in revision_ids which should
3191
 
            already exist in the target.
3192
 
        :return: (basis_id, basis_tree) A new basis to use now that these trees
3193
 
            have been copied.
 
3785
        :param basis_id: The revision_id of a tree that must be in cache, used
 
3786
            as a basis for delta when no other base is available
 
3787
        :param cache: A cache of RevisionTrees that we can use.
 
3788
        :param a_graph: A Graph object to determine the heads() of the
 
3789
            rich-root data stream.
 
3790
        :return: The revision_id of the last converted tree. The RevisionTree
 
3791
            for it will be in cache
3194
3792
        """
3195
3793
        # Walk though all revisions; get inventory deltas, copy referenced
3196
3794
        # texts that delta references, insert the delta, revision and
3197
3795
        # signature.
 
3796
        root_keys_to_create = set()
3198
3797
        text_keys = set()
3199
3798
        pending_deltas = []
3200
3799
        pending_revisions = []
 
3800
        parent_map = self.source.get_parent_map(revision_ids)
 
3801
        self._fetch_parent_invs_for_stacking(parent_map, cache)
 
3802
        self.source._safe_to_return_from_cache = True
3201
3803
        for tree in self.source.revision_trees(revision_ids):
 
3804
            # Find a inventory delta for this revision.
 
3805
            # Find text entries that need to be copied, too.
3202
3806
            current_revision_id = tree.get_revision_id()
3203
 
            delta = tree.inventory._make_delta(basis_tree.inventory)
3204
 
            for old_path, new_path, file_id, entry in delta:
3205
 
                if new_path is not None:
3206
 
                    if not (new_path or self.target.supports_rich_root()):
3207
 
                        # We leave the inventory delta in, because that
3208
 
                        # will have the deserialised inventory root
3209
 
                        # pointer.
3210
 
                        continue
3211
 
                    # TODO: Do we need:
3212
 
                    #       "if entry.revision == current_revision_id" ?
3213
 
                    if entry.revision == current_revision_id:
3214
 
                        text_keys.add((file_id, entry.revision))
 
3807
            parent_ids = parent_map.get(current_revision_id, ())
 
3808
            parent_trees = self._get_trees(parent_ids, cache)
 
3809
            possible_trees = list(parent_trees)
 
3810
            if len(possible_trees) == 0:
 
3811
                # There either aren't any parents, or the parents are ghosts,
 
3812
                # so just use the last converted tree.
 
3813
                possible_trees.append((basis_id, cache[basis_id]))
 
3814
            basis_id, delta = self._get_delta_for_revision(tree, parent_ids,
 
3815
                                                           possible_trees)
3215
3816
            revision = self.source.get_revision(current_revision_id)
3216
3817
            pending_deltas.append((basis_id, delta,
3217
3818
                current_revision_id, revision.parent_ids))
 
3819
            if self._converting_to_rich_root:
 
3820
                self._revision_id_to_root_id[current_revision_id] = \
 
3821
                    tree.get_root_id()
 
3822
            # Determine which texts are in present in this revision but not in
 
3823
            # any of the available parents.
 
3824
            texts_possibly_new_in_tree = set()
 
3825
            for old_path, new_path, file_id, entry in delta:
 
3826
                if new_path is None:
 
3827
                    # This file_id isn't present in the new rev
 
3828
                    continue
 
3829
                if not new_path:
 
3830
                    # This is the root
 
3831
                    if not self.target.supports_rich_root():
 
3832
                        # The target doesn't support rich root, so we don't
 
3833
                        # copy
 
3834
                        continue
 
3835
                    if self._converting_to_rich_root:
 
3836
                        # This can't be copied normally, we have to insert
 
3837
                        # it specially
 
3838
                        root_keys_to_create.add((file_id, entry.revision))
 
3839
                        continue
 
3840
                kind = entry.kind
 
3841
                texts_possibly_new_in_tree.add((file_id, entry.revision))
 
3842
            for basis_id, basis_tree in possible_trees:
 
3843
                basis_inv = basis_tree.inventory
 
3844
                for file_key in list(texts_possibly_new_in_tree):
 
3845
                    file_id, file_revision = file_key
 
3846
                    try:
 
3847
                        entry = basis_inv[file_id]
 
3848
                    except errors.NoSuchId:
 
3849
                        continue
 
3850
                    if entry.revision == file_revision:
 
3851
                        texts_possibly_new_in_tree.remove(file_key)
 
3852
            text_keys.update(texts_possibly_new_in_tree)
3218
3853
            pending_revisions.append(revision)
 
3854
            cache[current_revision_id] = tree
3219
3855
            basis_id = current_revision_id
3220
 
            basis_tree = tree
 
3856
        self.source._safe_to_return_from_cache = False
3221
3857
        # Copy file texts
3222
3858
        from_texts = self.source.texts
3223
3859
        to_texts = self.target.texts
 
3860
        if root_keys_to_create:
 
3861
            root_stream = _mod_fetch._new_root_data_stream(
 
3862
                root_keys_to_create, self._revision_id_to_root_id, parent_map,
 
3863
                self.source, graph=a_graph)
 
3864
            to_texts.insert_record_stream(root_stream)
3224
3865
        to_texts.insert_record_stream(from_texts.get_record_stream(
3225
 
            text_keys, self.target._fetch_order,
3226
 
            not self.target._fetch_uses_deltas))
3227
 
        # insert deltas
 
3866
            text_keys, self.target._format._fetch_order,
 
3867
            not self.target._format._fetch_uses_deltas))
 
3868
        # insert inventory deltas
3228
3869
        for delta in pending_deltas:
3229
3870
            self.target.add_inventory_by_delta(*delta)
 
3871
        if self.target._fallback_repositories:
 
3872
            # Make sure this stacked repository has all the parent inventories
 
3873
            # for the new revisions that we are about to insert.  We do this
 
3874
            # before adding the revisions so that no revision is added until
 
3875
            # all the inventories it may depend on are added.
 
3876
            # Note that this is overzealous, as we may have fetched these in an
 
3877
            # earlier batch.
 
3878
            parent_ids = set()
 
3879
            revision_ids = set()
 
3880
            for revision in pending_revisions:
 
3881
                revision_ids.add(revision.revision_id)
 
3882
                parent_ids.update(revision.parent_ids)
 
3883
            parent_ids.difference_update(revision_ids)
 
3884
            parent_ids.discard(_mod_revision.NULL_REVISION)
 
3885
            parent_map = self.source.get_parent_map(parent_ids)
 
3886
            # we iterate over parent_map and not parent_ids because we don't
 
3887
            # want to try copying any revision which is a ghost
 
3888
            for parent_tree in self.source.revision_trees(parent_map):
 
3889
                current_revision_id = parent_tree.get_revision_id()
 
3890
                parents_parents = parent_map[current_revision_id]
 
3891
                possible_trees = self._get_trees(parents_parents, cache)
 
3892
                if len(possible_trees) == 0:
 
3893
                    # There either aren't any parents, or the parents are
 
3894
                    # ghosts, so just use the last converted tree.
 
3895
                    possible_trees.append((basis_id, cache[basis_id]))
 
3896
                basis_id, delta = self._get_delta_for_revision(parent_tree,
 
3897
                    parents_parents, possible_trees)
 
3898
                self.target.add_inventory_by_delta(
 
3899
                    basis_id, delta, current_revision_id, parents_parents)
3230
3900
        # insert signatures and revisions
3231
3901
        for revision in pending_revisions:
3232
3902
            try:
3237
3907
            except errors.NoSuchRevision:
3238
3908
                pass
3239
3909
            self.target.add_revision(revision.revision_id, revision)
3240
 
        return basis_id, basis_tree
 
3910
        return basis_id
3241
3911
 
3242
3912
    def _fetch_all_revisions(self, revision_ids, pb):
3243
3913
        """Fetch everything for the list of revisions.
3244
3914
 
3245
3915
        :param revision_ids: The list of revisions to fetch. Must be in
3246
3916
            topological order.
3247
 
        :param pb: A ProgressBar
 
3917
        :param pb: A ProgressTask
3248
3918
        :return: None
3249
3919
        """
3250
3920
        basis_id, basis_tree = self._get_basis(revision_ids[0])
3251
3921
        batch_size = 100
 
3922
        cache = lru_cache.LRUCache(100)
 
3923
        cache[basis_id] = basis_tree
 
3924
        del basis_tree # We don't want to hang on to it here
 
3925
        hints = []
 
3926
        if self._converting_to_rich_root and len(revision_ids) > 100:
 
3927
            a_graph = _mod_fetch._get_rich_root_heads_graph(self.source,
 
3928
                                                            revision_ids)
 
3929
        else:
 
3930
            a_graph = None
 
3931
 
3252
3932
        for offset in range(0, len(revision_ids), batch_size):
3253
3933
            self.target.start_write_group()
3254
3934
            try:
3255
3935
                pb.update('Transferring revisions', offset,
3256
3936
                          len(revision_ids))
3257
3937
                batch = revision_ids[offset:offset+batch_size]
3258
 
                basis_id, basis_tree = self._fetch_batch(batch,
3259
 
                    basis_id, basis_tree)
 
3938
                basis_id = self._fetch_batch(batch, basis_id, cache,
 
3939
                                             a_graph=a_graph)
3260
3940
            except:
 
3941
                self.source._safe_to_return_from_cache = False
3261
3942
                self.target.abort_write_group()
3262
3943
                raise
3263
3944
            else:
3264
 
                self.target.commit_write_group()
 
3945
                hint = self.target.commit_write_group()
 
3946
                if hint:
 
3947
                    hints.extend(hint)
 
3948
        if hints and self.target._format.pack_compresses:
 
3949
            self.target.pack(hint=hints)
3265
3950
        pb.update('Transferring revisions', len(revision_ids),
3266
3951
                  len(revision_ids))
3267
3952
 
3268
3953
    @needs_write_lock
3269
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
 
3954
    def fetch(self, revision_id=None, pb=None, find_ghosts=False,
 
3955
            fetch_spec=None):
3270
3956
        """See InterRepository.fetch()."""
 
3957
        if fetch_spec is not None:
 
3958
            raise AssertionError("Not implemented yet...")
 
3959
        # See <https://launchpad.net/bugs/456077> asking for a warning here
 
3960
        #
 
3961
        # nb this is only active for local-local fetches; other things using
 
3962
        # streaming.
 
3963
        ui.ui_factory.warn_cross_format_fetch(self.source._format,
 
3964
            self.target._format)
 
3965
        ui.ui_factory.warn_experimental_format_fetch(self)
 
3966
        if (not self.source.supports_rich_root()
 
3967
            and self.target.supports_rich_root()):
 
3968
            self._converting_to_rich_root = True
 
3969
            self._revision_id_to_root_id = {}
 
3970
        else:
 
3971
            self._converting_to_rich_root = False
3271
3972
        revision_ids = self.target.search_missing_revision_ids(self.source,
3272
3973
            revision_id, find_ghosts=find_ghosts).get_keys()
3273
3974
        if not revision_ids:
3274
3975
            return 0, 0
3275
3976
        revision_ids = tsort.topo_sort(
3276
3977
            self.source.get_graph().get_parent_map(revision_ids))
 
3978
        if not revision_ids:
 
3979
            return 0, 0
 
3980
        # Walk though all revisions; get inventory deltas, copy referenced
 
3981
        # texts that delta references, insert the delta, revision and
 
3982
        # signature.
3277
3983
        if pb is None:
3278
3984
            my_pb = ui.ui_factory.nested_progress_bar()
3279
3985
            pb = my_pb
3280
3986
        else:
 
3987
            symbol_versioning.warn(
 
3988
                symbol_versioning.deprecated_in((1, 14, 0))
 
3989
                % "pb parameter to fetch()")
3281
3990
            my_pb = None
3282
3991
        try:
3283
3992
            self._fetch_all_revisions(revision_ids, pb)
3309
4018
        return basis_id, basis_tree
3310
4019
 
3311
4020
 
3312
 
class InterOtherToRemote(InterRepository):
3313
 
    """An InterRepository that simply delegates to the 'real' InterRepository
3314
 
    calculated for (source, target._real_repository).
3315
 
    """
3316
 
 
3317
 
    _walk_to_common_revisions_batch_size = 50
3318
 
 
3319
 
    def __init__(self, source, target):
3320
 
        InterRepository.__init__(self, source, target)
3321
 
        self._real_inter = None
3322
 
 
3323
 
    @staticmethod
3324
 
    def is_compatible(source, target):
3325
 
        if isinstance(target, remote.RemoteRepository):
3326
 
            return True
3327
 
        return False
3328
 
 
3329
 
    def _ensure_real_inter(self):
3330
 
        if self._real_inter is None:
3331
 
            self.target._ensure_real()
3332
 
            real_target = self.target._real_repository
3333
 
            self._real_inter = InterRepository.get(self.source, real_target)
3334
 
            # Make _real_inter use the RemoteRepository for get_parent_map
3335
 
            self._real_inter.target_get_graph = self.target.get_graph
3336
 
            self._real_inter.target_get_parent_map = self.target.get_parent_map
3337
 
    
3338
 
    def copy_content(self, revision_id=None):
3339
 
        self._ensure_real_inter()
3340
 
        self._real_inter.copy_content(revision_id=revision_id)
3341
 
 
3342
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
3343
 
        self._ensure_real_inter()
3344
 
        return self._real_inter.fetch(revision_id=revision_id, pb=pb,
3345
 
            find_ghosts=find_ghosts)
3346
 
 
3347
 
    @classmethod
3348
 
    def _get_repo_format_to_test(self):
3349
 
        return None
3350
 
 
3351
 
 
3352
 
class InterRemoteToOther(InterRepository):
3353
 
 
3354
 
    def __init__(self, source, target):
3355
 
        InterRepository.__init__(self, source, target)
3356
 
        self._real_inter = None
3357
 
 
3358
 
    @staticmethod
3359
 
    def is_compatible(source, target):
3360
 
        if not isinstance(source, remote.RemoteRepository):
3361
 
            return False
3362
 
        # Is source's model compatible with target's model?
3363
 
        source._ensure_real()
3364
 
        real_source = source._real_repository
3365
 
        if isinstance(real_source, remote.RemoteRepository):
3366
 
            raise NotImplementedError(
3367
 
                "We don't support remote repos backed by remote repos yet.")
3368
 
        return InterRepository._same_model(real_source, target)
3369
 
 
3370
 
    def _ensure_real_inter(self):
3371
 
        if self._real_inter is None:
3372
 
            self.source._ensure_real()
3373
 
            real_source = self.source._real_repository
3374
 
            self._real_inter = InterRepository.get(real_source, self.target)
3375
 
    
3376
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False):
3377
 
        self._ensure_real_inter()
3378
 
        return self._real_inter.fetch(revision_id=revision_id, pb=pb,
3379
 
            find_ghosts=find_ghosts)
3380
 
 
3381
 
    def copy_content(self, revision_id=None):
3382
 
        self._ensure_real_inter()
3383
 
        self._real_inter.copy_content(revision_id=revision_id)
3384
 
 
3385
 
    @classmethod
3386
 
    def _get_repo_format_to_test(self):
3387
 
        return None
3388
 
 
3389
 
 
3390
 
 
3391
 
class InterPackToRemotePack(InterPackRepo):
3392
 
    """A specialisation of InterPackRepo for a target that is a
3393
 
    RemoteRepository.
3394
 
 
3395
 
    This will use the get_parent_map RPC rather than plain readvs, and also
3396
 
    uses an RPC for autopacking.
3397
 
    """
3398
 
 
3399
 
    _walk_to_common_revisions_batch_size = 50
3400
 
 
3401
 
    @staticmethod
3402
 
    def is_compatible(source, target):
3403
 
        from bzrlib.repofmt.pack_repo import RepositoryFormatPack
3404
 
        if isinstance(source._format, RepositoryFormatPack):
3405
 
            if isinstance(target, remote.RemoteRepository):
3406
 
                target._ensure_real()
3407
 
                if isinstance(target._real_repository._format,
3408
 
                              RepositoryFormatPack):
3409
 
                    if InterRepository._same_model(source, target):
3410
 
                        return True
3411
 
        return False
3412
 
    
3413
 
    def _autopack(self):
3414
 
        self.target.autopack()
3415
 
        
3416
 
    def _get_target_pack_collection(self):
3417
 
        return self.target._real_repository._pack_collection
3418
 
 
3419
 
    @classmethod
3420
 
    def _get_repo_format_to_test(self):
3421
 
        return None
3422
 
 
3423
 
 
3424
4021
InterRepository.register_optimiser(InterDifferingSerializer)
3425
4022
InterRepository.register_optimiser(InterSameDataRepository)
3426
4023
InterRepository.register_optimiser(InterWeaveRepo)
3427
4024
InterRepository.register_optimiser(InterKnitRepo)
3428
 
InterRepository.register_optimiser(InterModel1and2)
3429
 
InterRepository.register_optimiser(InterKnit1and2)
3430
 
InterRepository.register_optimiser(InterPackRepo)
3431
 
InterRepository.register_optimiser(InterOtherToRemote)
3432
 
InterRepository.register_optimiser(InterRemoteToOther)
3433
 
InterRepository.register_optimiser(InterPackToRemotePack)
3434
4025
 
3435
4026
 
3436
4027
class CopyConverter(object):
3437
4028
    """A repository conversion tool which just performs a copy of the content.
3438
 
    
 
4029
 
3439
4030
    This is slow but quite reliable.
3440
4031
    """
3441
4032
 
3445
4036
        :param target_format: The format the resulting repository should be.
3446
4037
        """
3447
4038
        self.target_format = target_format
3448
 
        
 
4039
 
3449
4040
    def convert(self, repo, pb):
3450
4041
        """Perform the conversion of to_convert, giving feedback via pb.
3451
4042
 
3452
4043
        :param to_convert: The disk object to convert.
3453
4044
        :param pb: a progress bar to use for progress information.
3454
4045
        """
3455
 
        self.pb = pb
 
4046
        pb = ui.ui_factory.nested_progress_bar()
3456
4047
        self.count = 0
3457
4048
        self.total = 4
3458
4049
        # this is only useful with metadir layouts - separated repo content.
3459
4050
        # trigger an assertion if not such
3460
4051
        repo._format.get_format_string()
3461
4052
        self.repo_dir = repo.bzrdir
3462
 
        self.step('Moving repository to repository.backup')
 
4053
        pb.update('Moving repository to repository.backup')
3463
4054
        self.repo_dir.transport.move('repository', 'repository.backup')
3464
4055
        backup_transport =  self.repo_dir.transport.clone('repository.backup')
3465
4056
        repo._format.check_conversion_target(self.target_format)
3466
4057
        self.source_repo = repo._format.open(self.repo_dir,
3467
4058
            _found=True,
3468
4059
            _override_transport=backup_transport)
3469
 
        self.step('Creating new repository')
 
4060
        pb.update('Creating new repository')
3470
4061
        converted = self.target_format.initialize(self.repo_dir,
3471
4062
                                                  self.source_repo.is_shared())
3472
4063
        converted.lock_write()
3473
4064
        try:
3474
 
            self.step('Copying content into repository.')
 
4065
            pb.update('Copying content')
3475
4066
            self.source_repo.copy_content_into(converted)
3476
4067
        finally:
3477
4068
            converted.unlock()
3478
 
        self.step('Deleting old repository content.')
 
4069
        pb.update('Deleting old repository content')
3479
4070
        self.repo_dir.transport.delete_tree('repository.backup')
3480
 
        self.pb.note('repository converted')
3481
 
 
3482
 
    def step(self, message):
3483
 
        """Update the pb by a step."""
3484
 
        self.count +=1
3485
 
        self.pb.update(message, self.count, self.total)
 
4071
        ui.ui_factory.note('repository converted')
 
4072
        pb.finished()
3486
4073
 
3487
4074
 
3488
4075
_unescape_map = {
3517
4104
 
3518
4105
class _VersionedFileChecker(object):
3519
4106
 
3520
 
    def __init__(self, repository):
 
4107
    def __init__(self, repository, text_key_references=None, ancestors=None):
3521
4108
        self.repository = repository
3522
 
        self.text_index = self.repository._generate_text_key_index()
3523
 
    
 
4109
        self.text_index = self.repository._generate_text_key_index(
 
4110
            text_key_references=text_key_references, ancestors=ancestors)
 
4111
 
3524
4112
    def calculate_file_version_parents(self, text_key):
3525
4113
        """Calculate the correct parents for a file version according to
3526
4114
        the inventories.
3543
4131
            revision_id) tuples for versions that are present in this versioned
3544
4132
            file, but not used by the corresponding inventory.
3545
4133
        """
 
4134
        local_progress = None
 
4135
        if progress_bar is None:
 
4136
            local_progress = ui.ui_factory.nested_progress_bar()
 
4137
            progress_bar = local_progress
 
4138
        try:
 
4139
            return self._check_file_version_parents(texts, progress_bar)
 
4140
        finally:
 
4141
            if local_progress:
 
4142
                local_progress.finished()
 
4143
 
 
4144
    def _check_file_version_parents(self, texts, progress_bar):
 
4145
        """See check_file_version_parents."""
3546
4146
        wrong_parents = {}
3547
4147
        self.file_ids = set([file_id for file_id, _ in
3548
4148
            self.text_index.iterkeys()])
3549
4149
        # text keys is now grouped by file_id
3550
 
        n_weaves = len(self.file_ids)
3551
 
        files_in_revisions = {}
3552
 
        revisions_of_files = {}
3553
4150
        n_versions = len(self.text_index)
3554
4151
        progress_bar.update('loading text store', 0, n_versions)
3555
4152
        parent_map = self.repository.texts.get_parent_map(self.text_index)
3557
4154
        text_keys = self.repository.texts.keys()
3558
4155
        unused_keys = frozenset(text_keys) - set(self.text_index)
3559
4156
        for num, key in enumerate(self.text_index.iterkeys()):
3560
 
            if progress_bar is not None:
3561
 
                progress_bar.update('checking text graph', num, n_versions)
 
4157
            progress_bar.update('checking text graph', num, n_versions)
3562
4158
            correct_parents = self.calculate_file_version_parents(key)
3563
4159
            try:
3564
4160
                knit_parents = parent_map[key]
3587
4183
        revision_graph[key] = tuple(parent for parent in parents if parent
3588
4184
            in revision_graph)
3589
4185
    return revision_graph
 
4186
 
 
4187
 
 
4188
class StreamSink(object):
 
4189
    """An object that can insert a stream into a repository.
 
4190
 
 
4191
    This interface handles the complexity of reserialising inventories and
 
4192
    revisions from different formats, and allows unidirectional insertion into
 
4193
    stacked repositories without looking for the missing basis parents
 
4194
    beforehand.
 
4195
    """
 
4196
 
 
4197
    def __init__(self, target_repo):
 
4198
        self.target_repo = target_repo
 
4199
 
 
4200
    def insert_stream(self, stream, src_format, resume_tokens):
 
4201
        """Insert a stream's content into the target repository.
 
4202
 
 
4203
        :param src_format: a bzr repository format.
 
4204
 
 
4205
        :return: a list of resume tokens and an  iterable of keys additional
 
4206
            items required before the insertion can be completed.
 
4207
        """
 
4208
        self.target_repo.lock_write()
 
4209
        try:
 
4210
            if resume_tokens:
 
4211
                self.target_repo.resume_write_group(resume_tokens)
 
4212
                is_resume = True
 
4213
            else:
 
4214
                self.target_repo.start_write_group()
 
4215
                is_resume = False
 
4216
            try:
 
4217
                # locked_insert_stream performs a commit|suspend.
 
4218
                return self._locked_insert_stream(stream, src_format, is_resume)
 
4219
            except:
 
4220
                self.target_repo.abort_write_group(suppress_errors=True)
 
4221
                raise
 
4222
        finally:
 
4223
            self.target_repo.unlock()
 
4224
 
 
4225
    def _locked_insert_stream(self, stream, src_format, is_resume):
 
4226
        to_serializer = self.target_repo._format._serializer
 
4227
        src_serializer = src_format._serializer
 
4228
        new_pack = None
 
4229
        if to_serializer == src_serializer:
 
4230
            # If serializers match and the target is a pack repository, set the
 
4231
            # write cache size on the new pack.  This avoids poor performance
 
4232
            # on transports where append is unbuffered (such as
 
4233
            # RemoteTransport).  This is safe to do because nothing should read
 
4234
            # back from the target repository while a stream with matching
 
4235
            # serialization is being inserted.
 
4236
            # The exception is that a delta record from the source that should
 
4237
            # be a fulltext may need to be expanded by the target (see
 
4238
            # test_fetch_revisions_with_deltas_into_pack); but we take care to
 
4239
            # explicitly flush any buffered writes first in that rare case.
 
4240
            try:
 
4241
                new_pack = self.target_repo._pack_collection._new_pack
 
4242
            except AttributeError:
 
4243
                # Not a pack repository
 
4244
                pass
 
4245
            else:
 
4246
                new_pack.set_write_cache_size(1024*1024)
 
4247
        for substream_type, substream in stream:
 
4248
            if 'stream' in debug.debug_flags:
 
4249
                mutter('inserting substream: %s', substream_type)
 
4250
            if substream_type == 'texts':
 
4251
                self.target_repo.texts.insert_record_stream(substream)
 
4252
            elif substream_type == 'inventories':
 
4253
                if src_serializer == to_serializer:
 
4254
                    self.target_repo.inventories.insert_record_stream(
 
4255
                        substream)
 
4256
                else:
 
4257
                    self._extract_and_insert_inventories(
 
4258
                        substream, src_serializer)
 
4259
            elif substream_type == 'inventory-deltas':
 
4260
                ui.ui_factory.warn_cross_format_fetch(src_format,
 
4261
                    self.target_repo._format)
 
4262
                self._extract_and_insert_inventory_deltas(
 
4263
                    substream, src_serializer)
 
4264
            elif substream_type == 'chk_bytes':
 
4265
                # XXX: This doesn't support conversions, as it assumes the
 
4266
                #      conversion was done in the fetch code.
 
4267
                self.target_repo.chk_bytes.insert_record_stream(substream)
 
4268
            elif substream_type == 'revisions':
 
4269
                # This may fallback to extract-and-insert more often than
 
4270
                # required if the serializers are different only in terms of
 
4271
                # the inventory.
 
4272
                if src_serializer == to_serializer:
 
4273
                    self.target_repo.revisions.insert_record_stream(
 
4274
                        substream)
 
4275
                else:
 
4276
                    self._extract_and_insert_revisions(substream,
 
4277
                        src_serializer)
 
4278
            elif substream_type == 'signatures':
 
4279
                self.target_repo.signatures.insert_record_stream(substream)
 
4280
            else:
 
4281
                raise AssertionError('kaboom! %s' % (substream_type,))
 
4282
        # Done inserting data, and the missing_keys calculations will try to
 
4283
        # read back from the inserted data, so flush the writes to the new pack
 
4284
        # (if this is pack format).
 
4285
        if new_pack is not None:
 
4286
            new_pack._write_data('', flush=True)
 
4287
        # Find all the new revisions (including ones from resume_tokens)
 
4288
        missing_keys = self.target_repo.get_missing_parent_inventories(
 
4289
            check_for_missing_texts=is_resume)
 
4290
        try:
 
4291
            for prefix, versioned_file in (
 
4292
                ('texts', self.target_repo.texts),
 
4293
                ('inventories', self.target_repo.inventories),
 
4294
                ('revisions', self.target_repo.revisions),
 
4295
                ('signatures', self.target_repo.signatures),
 
4296
                ('chk_bytes', self.target_repo.chk_bytes),
 
4297
                ):
 
4298
                if versioned_file is None:
 
4299
                    continue
 
4300
                # TODO: key is often going to be a StaticTuple object
 
4301
                #       I don't believe we can define a method by which
 
4302
                #       (prefix,) + StaticTuple will work, though we could
 
4303
                #       define a StaticTuple.sq_concat that would allow you to
 
4304
                #       pass in either a tuple or a StaticTuple as the second
 
4305
                #       object, so instead we could have:
 
4306
                #       StaticTuple(prefix) + key here...
 
4307
                missing_keys.update((prefix,) + key for key in
 
4308
                    versioned_file.get_missing_compression_parent_keys())
 
4309
        except NotImplementedError:
 
4310
            # cannot even attempt suspending, and missing would have failed
 
4311
            # during stream insertion.
 
4312
            missing_keys = set()
 
4313
        else:
 
4314
            if missing_keys:
 
4315
                # suspend the write group and tell the caller what we is
 
4316
                # missing. We know we can suspend or else we would not have
 
4317
                # entered this code path. (All repositories that can handle
 
4318
                # missing keys can handle suspending a write group).
 
4319
                write_group_tokens = self.target_repo.suspend_write_group()
 
4320
                return write_group_tokens, missing_keys
 
4321
        hint = self.target_repo.commit_write_group()
 
4322
        if (to_serializer != src_serializer and
 
4323
            self.target_repo._format.pack_compresses):
 
4324
            self.target_repo.pack(hint=hint)
 
4325
        return [], set()
 
4326
 
 
4327
    def _extract_and_insert_inventory_deltas(self, substream, serializer):
 
4328
        target_rich_root = self.target_repo._format.rich_root_data
 
4329
        target_tree_refs = self.target_repo._format.supports_tree_reference
 
4330
        for record in substream:
 
4331
            # Insert the delta directly
 
4332
            inventory_delta_bytes = record.get_bytes_as('fulltext')
 
4333
            deserialiser = inventory_delta.InventoryDeltaDeserializer()
 
4334
            try:
 
4335
                parse_result = deserialiser.parse_text_bytes(
 
4336
                    inventory_delta_bytes)
 
4337
            except inventory_delta.IncompatibleInventoryDelta, err:
 
4338
                trace.mutter("Incompatible delta: %s", err.msg)
 
4339
                raise errors.IncompatibleRevision(self.target_repo._format)
 
4340
            basis_id, new_id, rich_root, tree_refs, inv_delta = parse_result
 
4341
            revision_id = new_id
 
4342
            parents = [key[0] for key in record.parents]
 
4343
            self.target_repo.add_inventory_by_delta(
 
4344
                basis_id, inv_delta, revision_id, parents)
 
4345
 
 
4346
    def _extract_and_insert_inventories(self, substream, serializer,
 
4347
            parse_delta=None):
 
4348
        """Generate a new inventory versionedfile in target, converting data.
 
4349
 
 
4350
        The inventory is retrieved from the source, (deserializing it), and
 
4351
        stored in the target (reserializing it in a different format).
 
4352
        """
 
4353
        target_rich_root = self.target_repo._format.rich_root_data
 
4354
        target_tree_refs = self.target_repo._format.supports_tree_reference
 
4355
        for record in substream:
 
4356
            # It's not a delta, so it must be a fulltext in the source
 
4357
            # serializer's format.
 
4358
            bytes = record.get_bytes_as('fulltext')
 
4359
            revision_id = record.key[0]
 
4360
            inv = serializer.read_inventory_from_string(bytes, revision_id)
 
4361
            parents = [key[0] for key in record.parents]
 
4362
            self.target_repo.add_inventory(revision_id, inv, parents)
 
4363
            # No need to keep holding this full inv in memory when the rest of
 
4364
            # the substream is likely to be all deltas.
 
4365
            del inv
 
4366
 
 
4367
    def _extract_and_insert_revisions(self, substream, serializer):
 
4368
        for record in substream:
 
4369
            bytes = record.get_bytes_as('fulltext')
 
4370
            revision_id = record.key[0]
 
4371
            rev = serializer.read_revision_from_string(bytes)
 
4372
            if rev.revision_id != revision_id:
 
4373
                raise AssertionError('wtf: %s != %s' % (rev, revision_id))
 
4374
            self.target_repo.add_revision(revision_id, rev)
 
4375
 
 
4376
    def finished(self):
 
4377
        if self.target_repo._format._fetch_reconcile:
 
4378
            self.target_repo.reconcile()
 
4379
 
 
4380
 
 
4381
class StreamSource(object):
 
4382
    """A source of a stream for fetching between repositories."""
 
4383
 
 
4384
    def __init__(self, from_repository, to_format):
 
4385
        """Create a StreamSource streaming from from_repository."""
 
4386
        self.from_repository = from_repository
 
4387
        self.to_format = to_format
 
4388
 
 
4389
    def delta_on_metadata(self):
 
4390
        """Return True if delta's are permitted on metadata streams.
 
4391
 
 
4392
        That is on revisions and signatures.
 
4393
        """
 
4394
        src_serializer = self.from_repository._format._serializer
 
4395
        target_serializer = self.to_format._serializer
 
4396
        return (self.to_format._fetch_uses_deltas and
 
4397
            src_serializer == target_serializer)
 
4398
 
 
4399
    def _fetch_revision_texts(self, revs):
 
4400
        # fetch signatures first and then the revision texts
 
4401
        # may need to be a InterRevisionStore call here.
 
4402
        from_sf = self.from_repository.signatures
 
4403
        # A missing signature is just skipped.
 
4404
        keys = [(rev_id,) for rev_id in revs]
 
4405
        signatures = versionedfile.filter_absent(from_sf.get_record_stream(
 
4406
            keys,
 
4407
            self.to_format._fetch_order,
 
4408
            not self.to_format._fetch_uses_deltas))
 
4409
        # If a revision has a delta, this is actually expanded inside the
 
4410
        # insert_record_stream code now, which is an alternate fix for
 
4411
        # bug #261339
 
4412
        from_rf = self.from_repository.revisions
 
4413
        revisions = from_rf.get_record_stream(
 
4414
            keys,
 
4415
            self.to_format._fetch_order,
 
4416
            not self.delta_on_metadata())
 
4417
        return [('signatures', signatures), ('revisions', revisions)]
 
4418
 
 
4419
    def _generate_root_texts(self, revs):
 
4420
        """This will be called by get_stream between fetching weave texts and
 
4421
        fetching the inventory weave.
 
4422
        """
 
4423
        if self._rich_root_upgrade():
 
4424
            return _mod_fetch.Inter1and2Helper(
 
4425
                self.from_repository).generate_root_texts(revs)
 
4426
        else:
 
4427
            return []
 
4428
 
 
4429
    def get_stream(self, search):
 
4430
        phase = 'file'
 
4431
        revs = search.get_keys()
 
4432
        graph = self.from_repository.get_graph()
 
4433
        revs = tsort.topo_sort(graph.get_parent_map(revs))
 
4434
        data_to_fetch = self.from_repository.item_keys_introduced_by(revs)
 
4435
        text_keys = []
 
4436
        for knit_kind, file_id, revisions in data_to_fetch:
 
4437
            if knit_kind != phase:
 
4438
                phase = knit_kind
 
4439
                # Make a new progress bar for this phase
 
4440
            if knit_kind == "file":
 
4441
                # Accumulate file texts
 
4442
                text_keys.extend([(file_id, revision) for revision in
 
4443
                    revisions])
 
4444
            elif knit_kind == "inventory":
 
4445
                # Now copy the file texts.
 
4446
                from_texts = self.from_repository.texts
 
4447
                yield ('texts', from_texts.get_record_stream(
 
4448
                    text_keys, self.to_format._fetch_order,
 
4449
                    not self.to_format._fetch_uses_deltas))
 
4450
                # Cause an error if a text occurs after we have done the
 
4451
                # copy.
 
4452
                text_keys = None
 
4453
                # Before we process the inventory we generate the root
 
4454
                # texts (if necessary) so that the inventories references
 
4455
                # will be valid.
 
4456
                for _ in self._generate_root_texts(revs):
 
4457
                    yield _
 
4458
                # we fetch only the referenced inventories because we do not
 
4459
                # know for unselected inventories whether all their required
 
4460
                # texts are present in the other repository - it could be
 
4461
                # corrupt.
 
4462
                for info in self._get_inventory_stream(revs):
 
4463
                    yield info
 
4464
            elif knit_kind == "signatures":
 
4465
                # Nothing to do here; this will be taken care of when
 
4466
                # _fetch_revision_texts happens.
 
4467
                pass
 
4468
            elif knit_kind == "revisions":
 
4469
                for record in self._fetch_revision_texts(revs):
 
4470
                    yield record
 
4471
            else:
 
4472
                raise AssertionError("Unknown knit kind %r" % knit_kind)
 
4473
 
 
4474
    def get_stream_for_missing_keys(self, missing_keys):
 
4475
        # missing keys can only occur when we are byte copying and not
 
4476
        # translating (because translation means we don't send
 
4477
        # unreconstructable deltas ever).
 
4478
        keys = {}
 
4479
        keys['texts'] = set()
 
4480
        keys['revisions'] = set()
 
4481
        keys['inventories'] = set()
 
4482
        keys['chk_bytes'] = set()
 
4483
        keys['signatures'] = set()
 
4484
        for key in missing_keys:
 
4485
            keys[key[0]].add(key[1:])
 
4486
        if len(keys['revisions']):
 
4487
            # If we allowed copying revisions at this point, we could end up
 
4488
            # copying a revision without copying its required texts: a
 
4489
            # violation of the requirements for repository integrity.
 
4490
            raise AssertionError(
 
4491
                'cannot copy revisions to fill in missing deltas %s' % (
 
4492
                    keys['revisions'],))
 
4493
        for substream_kind, keys in keys.iteritems():
 
4494
            vf = getattr(self.from_repository, substream_kind)
 
4495
            if vf is None and keys:
 
4496
                    raise AssertionError(
 
4497
                        "cannot fill in keys for a versioned file we don't"
 
4498
                        " have: %s needs %s" % (substream_kind, keys))
 
4499
            if not keys:
 
4500
                # No need to stream something we don't have
 
4501
                continue
 
4502
            if substream_kind == 'inventories':
 
4503
                # Some missing keys are genuinely ghosts, filter those out.
 
4504
                present = self.from_repository.inventories.get_parent_map(keys)
 
4505
                revs = [key[0] for key in present]
 
4506
                # Get the inventory stream more-or-less as we do for the
 
4507
                # original stream; there's no reason to assume that records
 
4508
                # direct from the source will be suitable for the sink.  (Think
 
4509
                # e.g. 2a -> 1.9-rich-root).
 
4510
                for info in self._get_inventory_stream(revs, missing=True):
 
4511
                    yield info
 
4512
                continue
 
4513
 
 
4514
            # Ask for full texts always so that we don't need more round trips
 
4515
            # after this stream.
 
4516
            # Some of the missing keys are genuinely ghosts, so filter absent
 
4517
            # records. The Sink is responsible for doing another check to
 
4518
            # ensure that ghosts don't introduce missing data for future
 
4519
            # fetches.
 
4520
            stream = versionedfile.filter_absent(vf.get_record_stream(keys,
 
4521
                self.to_format._fetch_order, True))
 
4522
            yield substream_kind, stream
 
4523
 
 
4524
    def inventory_fetch_order(self):
 
4525
        if self._rich_root_upgrade():
 
4526
            return 'topological'
 
4527
        else:
 
4528
            return self.to_format._fetch_order
 
4529
 
 
4530
    def _rich_root_upgrade(self):
 
4531
        return (not self.from_repository._format.rich_root_data and
 
4532
            self.to_format.rich_root_data)
 
4533
 
 
4534
    def _get_inventory_stream(self, revision_ids, missing=False):
 
4535
        from_format = self.from_repository._format
 
4536
        if (from_format.supports_chks and self.to_format.supports_chks and
 
4537
            from_format.network_name() == self.to_format.network_name()):
 
4538
            raise AssertionError(
 
4539
                "this case should be handled by GroupCHKStreamSource")
 
4540
        elif 'forceinvdeltas' in debug.debug_flags:
 
4541
            return self._get_convertable_inventory_stream(revision_ids,
 
4542
                    delta_versus_null=missing)
 
4543
        elif from_format.network_name() == self.to_format.network_name():
 
4544
            # Same format.
 
4545
            return self._get_simple_inventory_stream(revision_ids,
 
4546
                    missing=missing)
 
4547
        elif (not from_format.supports_chks and not self.to_format.supports_chks
 
4548
                and from_format._serializer == self.to_format._serializer):
 
4549
            # Essentially the same format.
 
4550
            return self._get_simple_inventory_stream(revision_ids,
 
4551
                    missing=missing)
 
4552
        else:
 
4553
            # Any time we switch serializations, we want to use an
 
4554
            # inventory-delta based approach.
 
4555
            return self._get_convertable_inventory_stream(revision_ids,
 
4556
                    delta_versus_null=missing)
 
4557
 
 
4558
    def _get_simple_inventory_stream(self, revision_ids, missing=False):
 
4559
        # NB: This currently reopens the inventory weave in source;
 
4560
        # using a single stream interface instead would avoid this.
 
4561
        from_weave = self.from_repository.inventories
 
4562
        if missing:
 
4563
            delta_closure = True
 
4564
        else:
 
4565
            delta_closure = not self.delta_on_metadata()
 
4566
        yield ('inventories', from_weave.get_record_stream(
 
4567
            [(rev_id,) for rev_id in revision_ids],
 
4568
            self.inventory_fetch_order(), delta_closure))
 
4569
 
 
4570
    def _get_convertable_inventory_stream(self, revision_ids,
 
4571
                                          delta_versus_null=False):
 
4572
        # The two formats are sufficiently different that there is no fast
 
4573
        # path, so we need to send just inventorydeltas, which any
 
4574
        # sufficiently modern client can insert into any repository.
 
4575
        # The StreamSink code expects to be able to
 
4576
        # convert on the target, so we need to put bytes-on-the-wire that can
 
4577
        # be converted.  That means inventory deltas (if the remote is <1.19,
 
4578
        # RemoteStreamSink will fallback to VFS to insert the deltas).
 
4579
        yield ('inventory-deltas',
 
4580
           self._stream_invs_as_deltas(revision_ids,
 
4581
                                       delta_versus_null=delta_versus_null))
 
4582
 
 
4583
    def _stream_invs_as_deltas(self, revision_ids, delta_versus_null=False):
 
4584
        """Return a stream of inventory-deltas for the given rev ids.
 
4585
 
 
4586
        :param revision_ids: The list of inventories to transmit
 
4587
        :param delta_versus_null: Don't try to find a minimal delta for this
 
4588
            entry, instead compute the delta versus the NULL_REVISION. This
 
4589
            effectively streams a complete inventory. Used for stuff like
 
4590
            filling in missing parents, etc.
 
4591
        """
 
4592
        from_repo = self.from_repository
 
4593
        revision_keys = [(rev_id,) for rev_id in revision_ids]
 
4594
        parent_map = from_repo.inventories.get_parent_map(revision_keys)
 
4595
        # XXX: possibly repos could implement a more efficient iter_inv_deltas
 
4596
        # method...
 
4597
        inventories = self.from_repository.iter_inventories(
 
4598
            revision_ids, 'topological')
 
4599
        format = from_repo._format
 
4600
        invs_sent_so_far = set([_mod_revision.NULL_REVISION])
 
4601
        inventory_cache = lru_cache.LRUCache(50)
 
4602
        null_inventory = from_repo.revision_tree(
 
4603
            _mod_revision.NULL_REVISION).inventory
 
4604
        # XXX: ideally the rich-root/tree-refs flags would be per-revision, not
 
4605
        # per-repo (e.g.  streaming a non-rich-root revision out of a rich-root
 
4606
        # repo back into a non-rich-root repo ought to be allowed)
 
4607
        serializer = inventory_delta.InventoryDeltaSerializer(
 
4608
            versioned_root=format.rich_root_data,
 
4609
            tree_references=format.supports_tree_reference)
 
4610
        for inv in inventories:
 
4611
            key = (inv.revision_id,)
 
4612
            parent_keys = parent_map.get(key, ())
 
4613
            delta = None
 
4614
            if not delta_versus_null and parent_keys:
 
4615
                # The caller did not ask for complete inventories and we have
 
4616
                # some parents that we can delta against.  Make a delta against
 
4617
                # each parent so that we can find the smallest.
 
4618
                parent_ids = [parent_key[0] for parent_key in parent_keys]
 
4619
                for parent_id in parent_ids:
 
4620
                    if parent_id not in invs_sent_so_far:
 
4621
                        # We don't know that the remote side has this basis, so
 
4622
                        # we can't use it.
 
4623
                        continue
 
4624
                    if parent_id == _mod_revision.NULL_REVISION:
 
4625
                        parent_inv = null_inventory
 
4626
                    else:
 
4627
                        parent_inv = inventory_cache.get(parent_id, None)
 
4628
                        if parent_inv is None:
 
4629
                            parent_inv = from_repo.get_inventory(parent_id)
 
4630
                    candidate_delta = inv._make_delta(parent_inv)
 
4631
                    if (delta is None or
 
4632
                        len(delta) > len(candidate_delta)):
 
4633
                        delta = candidate_delta
 
4634
                        basis_id = parent_id
 
4635
            if delta is None:
 
4636
                # Either none of the parents ended up being suitable, or we
 
4637
                # were asked to delta against NULL
 
4638
                basis_id = _mod_revision.NULL_REVISION
 
4639
                delta = inv._make_delta(null_inventory)
 
4640
            invs_sent_so_far.add(inv.revision_id)
 
4641
            inventory_cache[inv.revision_id] = inv
 
4642
            delta_serialized = ''.join(
 
4643
                serializer.delta_to_lines(basis_id, key[-1], delta))
 
4644
            yield versionedfile.FulltextContentFactory(
 
4645
                key, parent_keys, None, delta_serialized)
 
4646
 
 
4647
 
 
4648
def _iter_for_revno(repo, partial_history_cache, stop_index=None,
 
4649
                    stop_revision=None):
 
4650
    """Extend the partial history to include a given index
 
4651
 
 
4652
    If a stop_index is supplied, stop when that index has been reached.
 
4653
    If a stop_revision is supplied, stop when that revision is
 
4654
    encountered.  Otherwise, stop when the beginning of history is
 
4655
    reached.
 
4656
 
 
4657
    :param stop_index: The index which should be present.  When it is
 
4658
        present, history extension will stop.
 
4659
    :param stop_revision: The revision id which should be present.  When
 
4660
        it is encountered, history extension will stop.
 
4661
    """
 
4662
    start_revision = partial_history_cache[-1]
 
4663
    iterator = repo.iter_reverse_revision_history(start_revision)
 
4664
    try:
 
4665
        #skip the last revision in the list
 
4666
        iterator.next()
 
4667
        while True:
 
4668
            if (stop_index is not None and
 
4669
                len(partial_history_cache) > stop_index):
 
4670
                break
 
4671
            if partial_history_cache[-1] == stop_revision:
 
4672
                break
 
4673
            revision_id = iterator.next()
 
4674
            partial_history_cache.append(revision_id)
 
4675
    except StopIteration:
 
4676
        # No more history
 
4677
        return
 
4678