~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2009-04-30 15:00:23 UTC
  • mfrom: (4273.1.21 branch-subtree-locations)
  • Revision ID: pqm@pqm.ubuntu.com-20090430150023-1cw4lwqf312vpuu8
(abentley) Implement references command.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 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
25
25
        bzrdir,
26
26
        cache_utf8,
27
27
        config as _mod_config,
28
 
        controldir,
29
28
        debug,
30
29
        errors,
31
30
        lockdir,
32
31
        lockable_files,
33
 
        remote,
34
32
        repository,
35
33
        revision as _mod_revision,
36
34
        rio,
48
46
    )
49
47
""")
50
48
 
51
 
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
 
49
from bzrlib.decorators import needs_read_lock, needs_write_lock
52
50
from bzrlib.hooks import HookPoint, Hooks
53
51
from bzrlib.inter import InterObject
54
 
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
55
52
from bzrlib import registry
56
53
from bzrlib.symbol_versioning import (
57
54
    deprecated_in,
65
62
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
66
63
 
67
64
 
68
 
class Branch(controldir.ControlComponent):
 
65
# TODO: Maybe include checks for common corruption of newlines, etc?
 
66
 
 
67
# TODO: Some operations like log might retrieve the same revisions
 
68
# repeatedly to calculate deltas.  We could perhaps have a weakref
 
69
# cache in memory to make this faster.  In general anything can be
 
70
# cached in memory between lock and unlock operations. .. nb thats
 
71
# what the transaction identity map provides
 
72
 
 
73
 
 
74
######################################################################
 
75
# branch objects
 
76
 
 
77
class Branch(object):
69
78
    """Branch holding a history of revisions.
70
79
 
71
 
    :ivar base:
72
 
        Base directory/url of the branch; using control_url and
73
 
        control_transport is more standardized.
 
80
    base
 
81
        Base directory/url of the branch.
74
82
 
75
83
    hooks: An instance of BranchHooks.
76
84
    """
78
86
    # - RBC 20060112
79
87
    base = None
80
88
 
81
 
    @property
82
 
    def control_transport(self):
83
 
        return self._transport
84
 
 
85
 
    @property
86
 
    def user_transport(self):
87
 
        return self.bzrdir.user_transport
88
 
 
89
89
    def __init__(self, *ignored, **ignored_too):
90
90
        self.tags = self._format.make_tags(self)
91
91
        self._revision_history_cache = None
92
92
        self._revision_id_to_revno_cache = None
93
93
        self._partial_revision_id_to_revno_cache = {}
94
 
        self._partial_revision_history_cache = []
95
94
        self._last_revision_info_cache = None
96
95
        self._merge_sorted_revisions_cache = None
97
96
        self._open_hook()
102
101
    def _open_hook(self):
103
102
        """Called by init to allow simpler extension of the base class."""
104
103
 
105
 
    def _activate_fallback_location(self, url):
 
104
    def _activate_fallback_location(self, url, lock_style):
106
105
        """Activate the branch/repository from url as a fallback repository."""
107
106
        repo = self._get_fallback_repository(url)
108
 
        if repo.has_same_location(self.repository):
109
 
            raise errors.UnstackableLocationError(self.user_url, url)
 
107
        if lock_style == 'write':
 
108
            repo.lock_write()
 
109
        elif lock_style == 'read':
 
110
            repo.lock_read()
110
111
        self.repository.add_fallback_repository(repo)
111
112
 
112
113
    def break_lock(self):
128
129
            raise errors.UnstackableRepositoryFormat(self.repository._format,
129
130
                self.repository.base)
130
131
 
131
 
    def _extend_partial_history(self, stop_index=None, stop_revision=None):
132
 
        """Extend the partial history to include a given index
133
 
 
134
 
        If a stop_index is supplied, stop when that index has been reached.
135
 
        If a stop_revision is supplied, stop when that revision is
136
 
        encountered.  Otherwise, stop when the beginning of history is
137
 
        reached.
138
 
 
139
 
        :param stop_index: The index which should be present.  When it is
140
 
            present, history extension will stop.
141
 
        :param stop_revision: The revision id which should be present.  When
142
 
            it is encountered, history extension will stop.
143
 
        """
144
 
        if len(self._partial_revision_history_cache) == 0:
145
 
            self._partial_revision_history_cache = [self.last_revision()]
146
 
        repository._iter_for_revno(
147
 
            self.repository, self._partial_revision_history_cache,
148
 
            stop_index=stop_index, stop_revision=stop_revision)
149
 
        if self._partial_revision_history_cache[-1] == _mod_revision.NULL_REVISION:
150
 
            self._partial_revision_history_cache.pop()
151
 
 
152
 
    def _get_check_refs(self):
153
 
        """Get the references needed for check().
154
 
 
155
 
        See bzrlib.check.
156
 
        """
157
 
        revid = self.last_revision()
158
 
        return [('revision-existence', revid), ('lefthand-distance', revid)]
159
 
 
160
132
    @staticmethod
161
133
    def open(base, _unsupported=False, possible_transports=None):
162
134
        """Open the branch rooted at base.
166
138
        """
167
139
        control = bzrdir.BzrDir.open(base, _unsupported,
168
140
                                     possible_transports=possible_transports)
169
 
        return control.open_branch(unsupported=_unsupported)
 
141
        return control.open_branch(_unsupported)
170
142
 
171
143
    @staticmethod
172
 
    def open_from_transport(transport, name=None, _unsupported=False):
 
144
    def open_from_transport(transport, _unsupported=False):
173
145
        """Open the branch rooted at transport"""
174
146
        control = bzrdir.BzrDir.open_from_transport(transport, _unsupported)
175
 
        return control.open_branch(name=name, unsupported=_unsupported)
 
147
        return control.open_branch(_unsupported)
176
148
 
177
149
    @staticmethod
178
150
    def open_containing(url, possible_transports=None):
199
171
        return self.supports_tags() and self.tags.get_tag_dict()
200
172
 
201
173
    def get_config(self):
202
 
        """Get a bzrlib.config.BranchConfig for this Branch.
203
 
 
204
 
        This can then be used to get and set configuration options for the
205
 
        branch.
206
 
 
207
 
        :return: A bzrlib.config.BranchConfig.
208
 
        """
209
174
        return BranchConfig(self)
210
175
 
211
176
    def _get_config(self):
223
188
    def _get_fallback_repository(self, url):
224
189
        """Get the repository we fallback to at url."""
225
190
        url = urlutils.join(self.base, url)
226
 
        a_branch = Branch.open(url,
 
191
        a_bzrdir = bzrdir.BzrDir.open(url,
227
192
            possible_transports=[self.bzrdir.root_transport])
228
 
        return a_branch.repository
 
193
        return a_bzrdir.open_branch().repository
229
194
 
230
195
    def _get_tags_bytes(self):
231
196
        """Get the bytes of a serialised tags dict.
247
212
        if not local and not config.has_explicit_nickname():
248
213
            try:
249
214
                master = self.get_master_branch(possible_transports)
250
 
                if master and self.user_url == master.user_url:
251
 
                    raise errors.RecursiveBind(self.user_url)
252
215
                if master is not None:
253
216
                    # return the master branch value
254
217
                    return master.nick
255
 
            except errors.RecursiveBind, e:
256
 
                raise e
257
218
            except errors.BzrError, e:
258
219
                # Silently fall back to local implicit nick if the master is
259
220
                # unavailable
296
257
        new_history.reverse()
297
258
        return new_history
298
259
 
299
 
    def lock_write(self, token=None):
300
 
        """Lock the branch for write operations.
301
 
 
302
 
        :param token: A token to permit reacquiring a previously held and
303
 
            preserved lock.
304
 
        :return: A BranchWriteLockResult.
305
 
        """
 
260
    def lock_write(self):
306
261
        raise NotImplementedError(self.lock_write)
307
262
 
308
263
    def lock_read(self):
309
 
        """Lock the branch for read operations.
310
 
 
311
 
        :return: A bzrlib.lock.LogicalLockResult.
312
 
        """
313
264
        raise NotImplementedError(self.lock_read)
314
265
 
315
266
    def unlock(self):
440
391
            * 'include' - the stop revision is the last item in the result
441
392
            * 'with-merges' - include the stop revision and all of its
442
393
              merged revisions in the result
443
 
            * 'with-merges-without-common-ancestry' - filter out revisions 
444
 
              that are in both ancestries
445
394
        :param direction: either 'reverse' or 'forward':
446
395
            * reverse means return the start_revision_id first, i.e.
447
396
              start at the most recent revision and go backwards in history
469
418
        # start_revision_id.
470
419
        if self._merge_sorted_revisions_cache is None:
471
420
            last_revision = self.last_revision()
472
 
            known_graph = self.repository.get_known_graph_ancestry(
473
 
                [last_revision])
474
 
            self._merge_sorted_revisions_cache = known_graph.merge_sort(
475
 
                last_revision)
 
421
            graph = self.repository.get_graph()
 
422
            parent_map = dict(((key, value) for key, value in
 
423
                     graph.iter_ancestry([last_revision]) if value is not None))
 
424
            revision_graph = repository._strip_NULL_ghosts(parent_map)
 
425
            revs = tsort.merge_sort(revision_graph, last_revision, None,
 
426
                generate_revno=True)
 
427
            # Drop the sequence # before caching
 
428
            self._merge_sorted_revisions_cache = [r[1:] for r in revs]
 
429
 
476
430
        filtered = self._filter_merge_sorted_revisions(
477
431
            self._merge_sorted_revisions_cache, start_revision_id,
478
432
            stop_revision_id, stop_rule)
479
 
        # Make sure we don't return revisions that are not part of the
480
 
        # start_revision_id ancestry.
481
 
        filtered = self._filter_start_non_ancestors(filtered)
482
433
        if direction == 'reverse':
483
434
            return filtered
484
435
        if direction == 'forward':
491
442
        """Iterate over an inclusive range of sorted revisions."""
492
443
        rev_iter = iter(merge_sorted_revisions)
493
444
        if start_revision_id is not None:
494
 
            for node in rev_iter:
495
 
                rev_id = node.key[-1]
 
445
            for rev_id, depth, revno, end_of_merge in rev_iter:
496
446
                if rev_id != start_revision_id:
497
447
                    continue
498
448
                else:
499
449
                    # The decision to include the start or not
500
450
                    # depends on the stop_rule if a stop is provided
501
 
                    # so pop this node back into the iterator
502
 
                    rev_iter = chain(iter([node]), rev_iter)
 
451
                    rev_iter = chain(
 
452
                        iter([(rev_id, depth, revno, end_of_merge)]),
 
453
                        rev_iter)
503
454
                    break
504
455
        if stop_revision_id is None:
505
 
            # Yield everything
506
 
            for node in rev_iter:
507
 
                rev_id = node.key[-1]
508
 
                yield (rev_id, node.merge_depth, node.revno,
509
 
                       node.end_of_merge)
 
456
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
457
                yield rev_id, depth, revno, end_of_merge
510
458
        elif stop_rule == 'exclude':
511
 
            for node in rev_iter:
512
 
                rev_id = node.key[-1]
 
459
            for rev_id, depth, revno, end_of_merge in rev_iter:
513
460
                if rev_id == stop_revision_id:
514
461
                    return
515
 
                yield (rev_id, node.merge_depth, node.revno,
516
 
                       node.end_of_merge)
 
462
                yield rev_id, depth, revno, end_of_merge
517
463
        elif stop_rule == 'include':
518
 
            for node in rev_iter:
519
 
                rev_id = node.key[-1]
520
 
                yield (rev_id, node.merge_depth, node.revno,
521
 
                       node.end_of_merge)
 
464
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
465
                yield rev_id, depth, revno, end_of_merge
522
466
                if rev_id == stop_revision_id:
523
467
                    return
524
 
        elif stop_rule == 'with-merges-without-common-ancestry':
525
 
            # We want to exclude all revisions that are already part of the
526
 
            # stop_revision_id ancestry.
527
 
            graph = self.repository.get_graph()
528
 
            ancestors = graph.find_unique_ancestors(start_revision_id,
529
 
                                                    [stop_revision_id])
530
 
            for node in rev_iter:
531
 
                rev_id = node.key[-1]
532
 
                if rev_id not in ancestors:
533
 
                    continue
534
 
                yield (rev_id, node.merge_depth, node.revno,
535
 
                       node.end_of_merge)
536
468
        elif stop_rule == 'with-merges':
537
469
            stop_rev = self.repository.get_revision(stop_revision_id)
538
470
            if stop_rev.parent_ids:
539
471
                left_parent = stop_rev.parent_ids[0]
540
472
            else:
541
473
                left_parent = _mod_revision.NULL_REVISION
542
 
            # left_parent is the actual revision we want to stop logging at,
543
 
            # since we want to show the merged revisions after the stop_rev too
544
 
            reached_stop_revision_id = False
545
 
            revision_id_whitelist = []
546
 
            for node in rev_iter:
547
 
                rev_id = node.key[-1]
 
474
            for rev_id, depth, revno, end_of_merge in rev_iter:
548
475
                if rev_id == left_parent:
549
 
                    # reached the left parent after the stop_revision
550
476
                    return
551
 
                if (not reached_stop_revision_id or
552
 
                        rev_id in revision_id_whitelist):
553
 
                    yield (rev_id, node.merge_depth, node.revno,
554
 
                       node.end_of_merge)
555
 
                    if reached_stop_revision_id or rev_id == stop_revision_id:
556
 
                        # only do the merged revs of rev_id from now on
557
 
                        rev = self.repository.get_revision(rev_id)
558
 
                        if rev.parent_ids:
559
 
                            reached_stop_revision_id = True
560
 
                            revision_id_whitelist.extend(rev.parent_ids)
 
477
                yield rev_id, depth, revno, end_of_merge
561
478
        else:
562
479
            raise ValueError('invalid stop_rule %r' % stop_rule)
563
480
 
564
 
    def _filter_start_non_ancestors(self, rev_iter):
565
 
        # If we started from a dotted revno, we want to consider it as a tip
566
 
        # and don't want to yield revisions that are not part of its
567
 
        # ancestry. Given the order guaranteed by the merge sort, we will see
568
 
        # uninteresting descendants of the first parent of our tip before the
569
 
        # tip itself.
570
 
        first = rev_iter.next()
571
 
        (rev_id, merge_depth, revno, end_of_merge) = first
572
 
        yield first
573
 
        if not merge_depth:
574
 
            # We start at a mainline revision so by definition, all others
575
 
            # revisions in rev_iter are ancestors
576
 
            for node in rev_iter:
577
 
                yield node
578
 
 
579
 
        clean = False
580
 
        whitelist = set()
581
 
        pmap = self.repository.get_parent_map([rev_id])
582
 
        parents = pmap.get(rev_id, [])
583
 
        if parents:
584
 
            whitelist.update(parents)
585
 
        else:
586
 
            # If there is no parents, there is nothing of interest left
587
 
 
588
 
            # FIXME: It's hard to test this scenario here as this code is never
589
 
            # called in that case. -- vila 20100322
590
 
            return
591
 
 
592
 
        for (rev_id, merge_depth, revno, end_of_merge) in rev_iter:
593
 
            if not clean:
594
 
                if rev_id in whitelist:
595
 
                    pmap = self.repository.get_parent_map([rev_id])
596
 
                    parents = pmap.get(rev_id, [])
597
 
                    whitelist.remove(rev_id)
598
 
                    whitelist.update(parents)
599
 
                    if merge_depth == 0:
600
 
                        # We've reached the mainline, there is nothing left to
601
 
                        # filter
602
 
                        clean = True
603
 
                else:
604
 
                    # A revision that is not part of the ancestry of our
605
 
                    # starting revision.
606
 
                    continue
607
 
            yield (rev_id, merge_depth, revno, end_of_merge)
608
 
 
609
481
    def leave_lock_in_place(self):
610
482
        """Tell this branch object not to release the physical lock when this
611
483
        object is unlocked.
628
500
        :param other: The branch to bind to
629
501
        :type other: Branch
630
502
        """
631
 
        raise errors.UpgradeRequired(self.user_url)
632
 
 
633
 
    def set_append_revisions_only(self, enabled):
634
 
        if not self._format.supports_set_append_revisions_only():
635
 
            raise errors.UpgradeRequired(self.user_url)
636
 
        if enabled:
637
 
            value = 'True'
638
 
        else:
639
 
            value = 'False'
640
 
        self.get_config().set_user_option('append_revisions_only', value,
641
 
            warn_masked=True)
 
503
        raise errors.UpgradeRequired(self.base)
642
504
 
643
505
    def set_reference_info(self, file_id, tree_path, branch_location):
644
506
        """Set the branch location to use for a tree reference."""
686
548
    def get_old_bound_location(self):
687
549
        """Return the URL of the branch we used to be bound to
688
550
        """
689
 
        raise errors.UpgradeRequired(self.user_url)
 
551
        raise errors.UpgradeRequired(self.base)
690
552
 
691
553
    def get_commit_builder(self, parents, config=None, timestamp=None,
692
554
                           timezone=None, committer=None, revprops=None,
770
632
            stacking.
771
633
        """
772
634
        if not self._format.supports_stacking():
773
 
            raise errors.UnstackableBranchFormat(self._format, self.user_url)
774
 
        # XXX: Changing from one fallback repository to another does not check
775
 
        # that all the data you need is present in the new fallback.
776
 
        # Possibly it should.
 
635
            raise errors.UnstackableBranchFormat(self._format, self.base)
777
636
        self._check_stackable_repo()
778
637
        if not url:
779
638
            try:
781
640
            except (errors.NotStacked, errors.UnstackableBranchFormat,
782
641
                errors.UnstackableRepositoryFormat):
783
642
                return
784
 
            self._unstack()
 
643
            url = ''
 
644
            # XXX: Lock correctness - should unlock our old repo if we were
 
645
            # locked.
 
646
            # repositories don't offer an interface to remove fallback
 
647
            # repositories today; take the conceptually simpler option and just
 
648
            # reopen it.
 
649
            self.repository = self.bzrdir.find_repository()
 
650
            self.repository.lock_write()
 
651
            # for every revision reference the branch has, ensure it is pulled
 
652
            # in.
 
653
            source_repository = self._get_fallback_repository(old_url)
 
654
            for revision_id in chain([self.last_revision()],
 
655
                self.tags.get_reverse_tag_dict()):
 
656
                self.repository.fetch(source_repository, revision_id,
 
657
                    find_ghosts=True)
785
658
        else:
786
 
            self._activate_fallback_location(url)
 
659
            self._activate_fallback_location(url, 'write')
787
660
        # write this out after the repository is stacked to avoid setting a
788
661
        # stacked config that doesn't work.
789
662
        self._set_config_location('stacked_on_location', url)
790
663
 
791
 
    def _unstack(self):
792
 
        """Change a branch to be unstacked, copying data as needed.
793
 
        
794
 
        Don't call this directly, use set_stacked_on_url(None).
795
 
        """
796
 
        pb = ui.ui_factory.nested_progress_bar()
797
 
        try:
798
 
            pb.update("Unstacking")
799
 
            # The basic approach here is to fetch the tip of the branch,
800
 
            # including all available ghosts, from the existing stacked
801
 
            # repository into a new repository object without the fallbacks. 
802
 
            #
803
 
            # XXX: See <https://launchpad.net/bugs/397286> - this may not be
804
 
            # correct for CHKMap repostiories
805
 
            old_repository = self.repository
806
 
            if len(old_repository._fallback_repositories) != 1:
807
 
                raise AssertionError("can't cope with fallback repositories "
808
 
                    "of %r" % (self.repository,))
809
 
            # Open the new repository object.
810
 
            # Repositories don't offer an interface to remove fallback
811
 
            # repositories today; take the conceptually simpler option and just
812
 
            # reopen it.  We reopen it starting from the URL so that we
813
 
            # get a separate connection for RemoteRepositories and can
814
 
            # stream from one of them to the other.  This does mean doing
815
 
            # separate SSH connection setup, but unstacking is not a
816
 
            # common operation so it's tolerable.
817
 
            new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
818
 
            new_repository = new_bzrdir.find_repository()
819
 
            if new_repository._fallback_repositories:
820
 
                raise AssertionError("didn't expect %r to have "
821
 
                    "fallback_repositories"
822
 
                    % (self.repository,))
823
 
            # Replace self.repository with the new repository.
824
 
            # Do our best to transfer the lock state (i.e. lock-tokens and
825
 
            # lock count) of self.repository to the new repository.
826
 
            lock_token = old_repository.lock_write().repository_token
827
 
            self.repository = new_repository
828
 
            if isinstance(self, remote.RemoteBranch):
829
 
                # Remote branches can have a second reference to the old
830
 
                # repository that need to be replaced.
831
 
                if self._real_branch is not None:
832
 
                    self._real_branch.repository = new_repository
833
 
            self.repository.lock_write(token=lock_token)
834
 
            if lock_token is not None:
835
 
                old_repository.leave_lock_in_place()
836
 
            old_repository.unlock()
837
 
            if lock_token is not None:
838
 
                # XXX: self.repository.leave_lock_in_place() before this
839
 
                # function will not be preserved.  Fortunately that doesn't
840
 
                # affect the current default format (2a), and would be a
841
 
                # corner-case anyway.
842
 
                #  - Andrew Bennetts, 2010/06/30
843
 
                self.repository.dont_leave_lock_in_place()
844
 
            old_lock_count = 0
845
 
            while True:
846
 
                try:
847
 
                    old_repository.unlock()
848
 
                except errors.LockNotHeld:
849
 
                    break
850
 
                old_lock_count += 1
851
 
            if old_lock_count == 0:
852
 
                raise AssertionError(
853
 
                    'old_repository should have been locked at least once.')
854
 
            for i in range(old_lock_count-1):
855
 
                self.repository.lock_write()
856
 
            # Fetch from the old repository into the new.
857
 
            old_repository.lock_read()
858
 
            try:
859
 
                # XXX: If you unstack a branch while it has a working tree
860
 
                # with a pending merge, the pending-merged revisions will no
861
 
                # longer be present.  You can (probably) revert and remerge.
862
 
                #
863
 
                # XXX: This only fetches up to the tip of the repository; it
864
 
                # doesn't bring across any tags.  That's fairly consistent
865
 
                # with how branch works, but perhaps not ideal.
866
 
                self.repository.fetch(old_repository,
867
 
                    revision_id=self.last_revision(),
868
 
                    find_ghosts=True)
869
 
            finally:
870
 
                old_repository.unlock()
871
 
        finally:
872
 
            pb.finished()
873
664
 
874
665
    def _set_tags_bytes(self, bytes):
875
666
        """Mirror method for _get_tags_bytes.
911
702
        self._revision_id_to_revno_cache = None
912
703
        self._last_revision_info_cache = None
913
704
        self._merge_sorted_revisions_cache = None
914
 
        self._partial_revision_history_cache = []
915
 
        self._partial_revision_id_to_revno_cache = {}
916
705
 
917
706
    def _gen_revision_history(self):
918
707
        """Return sequence of revision hashes on to this branch.
955
744
 
956
745
    def unbind(self):
957
746
        """Older format branches cannot bind or unbind."""
958
 
        raise errors.UpgradeRequired(self.user_url)
 
747
        raise errors.UpgradeRequired(self.base)
 
748
 
 
749
    def set_append_revisions_only(self, enabled):
 
750
        """Older format branches are never restricted to append-only"""
 
751
        raise errors.UpgradeRequired(self.base)
959
752
 
960
753
    def last_revision(self):
961
754
        """Return last revision id, or NULL_REVISION."""
1002
795
                raise errors.NoSuchRevision(self, stop_revision)
1003
796
        return other_history[self_len:stop_revision]
1004
797
 
 
798
    @needs_write_lock
1005
799
    def update_revisions(self, other, stop_revision=None, overwrite=False,
1006
800
                         graph=None):
1007
801
        """Pull in new perfect-fit revisions.
1041
835
        except ValueError:
1042
836
            raise errors.NoSuchRevision(self, revision_id)
1043
837
 
1044
 
    @needs_read_lock
1045
838
    def get_rev_id(self, revno, history=None):
1046
839
        """Find the revision id of the specified revno."""
1047
840
        if revno == 0:
1048
841
            return _mod_revision.NULL_REVISION
1049
 
        last_revno, last_revid = self.last_revision_info()
1050
 
        if revno == last_revno:
1051
 
            return last_revid
1052
 
        if revno <= 0 or revno > last_revno:
 
842
        if history is None:
 
843
            history = self.revision_history()
 
844
        if revno <= 0 or revno > len(history):
1053
845
            raise errors.NoSuchRevision(self, revno)
1054
 
        distance_from_last = last_revno - revno
1055
 
        if len(self._partial_revision_history_cache) <= distance_from_last:
1056
 
            self._extend_partial_history(distance_from_last)
1057
 
        return self._partial_revision_history_cache[distance_from_last]
 
846
        return history[revno - 1]
1058
847
 
1059
848
    def pull(self, source, overwrite=False, stop_revision=None,
1060
 
             possible_transports=None, *args, **kwargs):
 
849
             possible_transports=None, _override_hook_target=None):
1061
850
        """Mirror source into this branch.
1062
851
 
1063
852
        This branch is considered to be 'local', having low latency.
1064
853
 
1065
854
        :returns: PullResult instance
1066
855
        """
1067
 
        return InterBranch.get(source, self).pull(overwrite=overwrite,
1068
 
            stop_revision=stop_revision,
1069
 
            possible_transports=possible_transports, *args, **kwargs)
 
856
        raise NotImplementedError(self.pull)
1070
857
 
1071
 
    def push(self, target, overwrite=False, stop_revision=None, *args,
1072
 
        **kwargs):
 
858
    def push(self, target, overwrite=False, stop_revision=None):
1073
859
        """Mirror this branch into target.
1074
860
 
1075
861
        This branch is considered to be 'local', having low latency.
1076
862
        """
1077
 
        return InterBranch.get(self, target).push(overwrite, stop_revision,
1078
 
            *args, **kwargs)
1079
 
 
1080
 
    def lossy_push(self, target, stop_revision=None):
1081
 
        """Push deltas into another branch.
1082
 
 
1083
 
        :note: This does not, like push, retain the revision ids from 
1084
 
            the source branch and will, rather than adding bzr-specific 
1085
 
            metadata, push only those semantics of the revision that can be 
1086
 
            natively represented by this branch' VCS.
1087
 
 
1088
 
        :param target: Target branch
1089
 
        :param stop_revision: Revision to push, defaults to last revision.
1090
 
        :return: BranchPushResult with an extra member revidmap: 
1091
 
            A dictionary mapping revision ids from the target branch 
1092
 
            to new revision ids in the target branch, for each 
1093
 
            revision that was pushed.
1094
 
        """
1095
 
        inter = InterBranch.get(self, target)
1096
 
        lossy_push = getattr(inter, "lossy_push", None)
1097
 
        if lossy_push is None:
1098
 
            raise errors.LossyPushToSameVCS(self, target)
1099
 
        return lossy_push(stop_revision)
 
863
        raise NotImplementedError(self.push)
1100
864
 
1101
865
    def basis_tree(self):
1102
866
        """Return `Tree` object for last revision."""
1119
883
        try:
1120
884
            return urlutils.join(self.base[:-1], parent)
1121
885
        except errors.InvalidURLJoin, e:
1122
 
            raise errors.InaccessibleParent(parent, self.user_url)
 
886
            raise errors.InaccessibleParent(parent, self.base)
1123
887
 
1124
888
    def _get_parent_location(self):
1125
889
        raise NotImplementedError(self._get_parent_location)
1142
906
            location = None
1143
907
        return location
1144
908
 
1145
 
    def get_child_submit_format(self):
1146
 
        """Return the preferred format of submissions to this branch."""
1147
 
        return self.get_config().get_user_option("child_submit_format")
1148
 
 
1149
909
    def get_submit_branch(self):
1150
910
        """Return the submit location of the branch.
1151
911
 
1210
970
        params = ChangeBranchTipParams(
1211
971
            self, old_revno, new_revno, old_revid, new_revid)
1212
972
        for hook in hooks:
1213
 
            hook(params)
 
973
            try:
 
974
                hook(params)
 
975
            except errors.TipChangeRejected:
 
976
                raise
 
977
            except Exception:
 
978
                exc_info = sys.exc_info()
 
979
                hook_name = Branch.hooks.get_hook_name(hook)
 
980
                raise errors.HookFailed(
 
981
                    'pre_change_branch_tip', hook_name, exc_info)
1214
982
 
1215
983
    @needs_write_lock
1216
984
    def update(self):
1265
1033
        revision_id: if not None, the revision history in the new branch will
1266
1034
                     be truncated to end with revision_id.
1267
1035
        """
1268
 
        if (repository_policy is not None and
1269
 
            repository_policy.requires_stacking()):
1270
 
            to_bzrdir._format.require_stacking(_skip_repo=True)
1271
1036
        result = to_bzrdir.create_branch()
1272
1037
        result.lock_write()
1273
1038
        try:
1294
1059
        source_revno, source_revision_id = self.last_revision_info()
1295
1060
        if revision_id is None:
1296
1061
            revno, revision_id = source_revno, source_revision_id
 
1062
        elif source_revision_id == revision_id:
 
1063
            # we know the revno without needing to walk all of history
 
1064
            revno = source_revno
1297
1065
        else:
1298
 
            graph = self.repository.get_graph()
1299
 
            try:
1300
 
                revno = graph.find_distance_to_null(revision_id, 
1301
 
                    [(source_revision_id, source_revno)])
1302
 
            except errors.GhostRevisionsHaveNoRevno:
1303
 
                # Default to 1, if we can't find anything else
1304
 
                revno = 1
 
1066
            # To figure out the revno for a random revision, we need to build
 
1067
            # the revision history, and count its length.
 
1068
            # We don't care about the order, just how long it is.
 
1069
            # Alternatively, we could start at the current location, and count
 
1070
            # backwards. But there is no guarantee that we will find it since
 
1071
            # it may be a merged revision.
 
1072
            revno = len(list(self.repository.iter_reverse_revision_history(
 
1073
                                                                revision_id)))
1305
1074
        destination.set_last_revision_info(revno, revision_id)
1306
1075
 
 
1076
    @needs_read_lock
1307
1077
    def copy_content_into(self, destination, revision_id=None):
1308
1078
        """Copy the content of self into destination.
1309
1079
 
1310
1080
        revision_id: if not None, the revision history in the new branch will
1311
1081
                     be truncated to end with revision_id.
1312
1082
        """
1313
 
        return InterBranch.get(self, destination).copy_content_into(
1314
 
            revision_id=revision_id)
 
1083
        self.update_references(destination)
 
1084
        self._synchronize_history(destination, revision_id)
 
1085
        try:
 
1086
            parent = self.get_parent()
 
1087
        except errors.InaccessibleParent, e:
 
1088
            mutter('parent was not accessible to copy: %s', e)
 
1089
        else:
 
1090
            if parent:
 
1091
                destination.set_parent(parent)
 
1092
        if self._push_should_merge_tags():
 
1093
            self.tags.merge_to(destination.tags)
1315
1094
 
1316
1095
    def update_references(self, target):
1317
1096
        if not getattr(self._format, 'supports_reference_locations', False):
1331
1110
        target._set_all_reference_info(target_reference_dict)
1332
1111
 
1333
1112
    @needs_read_lock
1334
 
    def check(self, refs):
 
1113
    def check(self):
1335
1114
        """Check consistency of the branch.
1336
1115
 
1337
1116
        In particular this checks that revisions given in the revision-history
1340
1119
 
1341
1120
        Callers will typically also want to check the repository.
1342
1121
 
1343
 
        :param refs: Calculated refs for this branch as specified by
1344
 
            branch._get_check_refs()
1345
1122
        :return: A BranchCheckResult.
1346
1123
        """
1347
 
        result = BranchCheckResult(self)
 
1124
        mainline_parent_id = None
1348
1125
        last_revno, last_revision_id = self.last_revision_info()
1349
 
        actual_revno = refs[('lefthand-distance', last_revision_id)]
1350
 
        if actual_revno != last_revno:
1351
 
            result.errors.append(errors.BzrCheckError(
1352
 
                'revno does not match len(mainline) %s != %s' % (
1353
 
                last_revno, actual_revno)))
1354
 
        # TODO: We should probably also check that self.revision_history
1355
 
        # matches the repository for older branch formats.
1356
 
        # If looking for the code that cross-checks repository parents against
1357
 
        # the iter_reverse_revision_history output, that is now a repository
1358
 
        # specific check.
1359
 
        return result
 
1126
        real_rev_history = list(self.repository.iter_reverse_revision_history(
 
1127
                                last_revision_id))
 
1128
        real_rev_history.reverse()
 
1129
        if len(real_rev_history) != last_revno:
 
1130
            raise errors.BzrCheckError('revno does not match len(mainline)'
 
1131
                ' %s != %s' % (last_revno, len(real_rev_history)))
 
1132
        # TODO: We should probably also check that real_rev_history actually
 
1133
        #       matches self.revision_history()
 
1134
        for revision_id in real_rev_history:
 
1135
            try:
 
1136
                revision = self.repository.get_revision(revision_id)
 
1137
            except errors.NoSuchRevision, e:
 
1138
                raise errors.BzrCheckError("mainline revision {%s} not in repository"
 
1139
                            % revision_id)
 
1140
            # In general the first entry on the revision history has no parents.
 
1141
            # But it's not illegal for it to have parents listed; this can happen
 
1142
            # in imports from Arch when the parents weren't reachable.
 
1143
            if mainline_parent_id is not None:
 
1144
                if mainline_parent_id not in revision.parent_ids:
 
1145
                    raise errors.BzrCheckError("previous revision {%s} not listed among "
 
1146
                                        "parents of {%s}"
 
1147
                                        % (mainline_parent_id, revision_id))
 
1148
            mainline_parent_id = revision_id
 
1149
        return BranchCheckResult(self)
1360
1150
 
1361
1151
    def _get_checkout_format(self):
1362
1152
        """Return the most suitable metadir for a checkout of this branch.
1385
1175
        """
1386
1176
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1387
1177
        # clone call. Or something. 20090224 RBC/spiv.
1388
 
        # XXX: Should this perhaps clone colocated branches as well, 
1389
 
        # rather than just the default branch? 20100319 JRV
1390
1178
        if revision_id is None:
1391
1179
            revision_id = self.last_revision()
1392
 
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1393
 
            revision_id=revision_id, stacked_on=stacked_on,
1394
 
            create_prefix=create_prefix, use_existing_dir=use_existing_dir)
 
1180
        try:
 
1181
            dir_to = self.bzrdir.clone_on_transport(to_transport,
 
1182
                revision_id=revision_id, stacked_on=stacked_on,
 
1183
                create_prefix=create_prefix, use_existing_dir=use_existing_dir)
 
1184
        except errors.FileExists:
 
1185
            if not use_existing_dir:
 
1186
                raise
 
1187
        except errors.NoSuchFile:
 
1188
            if not create_prefix:
 
1189
                raise
1395
1190
        return dir_to.open_branch()
1396
1191
 
1397
1192
    def create_checkout(self, to_location, revision_id=None,
1416
1211
        if lightweight:
1417
1212
            format = self._get_checkout_format()
1418
1213
            checkout = format.initialize_on_transport(t)
1419
 
            from_branch = BranchReferenceFormat().initialize(checkout, 
1420
 
                target_branch=self)
 
1214
            from_branch = BranchReferenceFormat().initialize(checkout, self)
1421
1215
        else:
1422
1216
            format = self._get_checkout_format()
1423
1217
            checkout_branch = bzrdir.BzrDir.create_branch_convenience(
1465
1259
    def supports_tags(self):
1466
1260
        return self._format.supports_tags()
1467
1261
 
1468
 
    def automatic_tag_name(self, revision_id):
1469
 
        """Try to automatically find the tag name for a revision.
1470
 
 
1471
 
        :param revision_id: Revision id of the revision.
1472
 
        :return: A tag name or None if no tag name could be determined.
1473
 
        """
1474
 
        for hook in Branch.hooks['automatic_tag_name']:
1475
 
            ret = hook(self, revision_id)
1476
 
            if ret is not None:
1477
 
                return ret
1478
 
        return None
1479
 
 
1480
1262
    def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
1481
1263
                                         other_branch):
1482
1264
        """Ensure that revision_b is a descendant of revision_a.
1522
1304
     * an open routine.
1523
1305
 
1524
1306
    Formats are placed in an dict by their format string for reference
1525
 
    during branch opening. It's not required that these be instances, they
 
1307
    during branch opening. Its not required that these be instances, they
1526
1308
    can be classes themselves with class methods - it simply depends on
1527
1309
    whether state is needed for a given format or not.
1528
1310
 
1537
1319
    _formats = {}
1538
1320
    """The known formats."""
1539
1321
 
1540
 
    can_set_append_revisions_only = True
1541
 
 
1542
1322
    def __eq__(self, other):
1543
1323
        return self.__class__ is other.__class__
1544
1324
 
1546
1326
        return not (self == other)
1547
1327
 
1548
1328
    @classmethod
1549
 
    def find_format(klass, a_bzrdir, name=None):
 
1329
    def find_format(klass, a_bzrdir):
1550
1330
        """Return the format for the branch object in a_bzrdir."""
1551
1331
        try:
1552
 
            transport = a_bzrdir.get_branch_transport(None, name=name)
1553
 
            format_string = transport.get_bytes("format")
1554
 
            format = klass._formats[format_string]
1555
 
            if isinstance(format, MetaDirBranchFormatFactory):
1556
 
                return format()
1557
 
            return format
 
1332
            transport = a_bzrdir.get_branch_transport(None)
 
1333
            format_string = transport.get("format").read()
 
1334
            return klass._formats[format_string]
1558
1335
        except errors.NoSuchFile:
1559
 
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
 
1336
            raise errors.NotBranchError(path=transport.base)
1560
1337
        except KeyError:
1561
1338
            raise errors.UnknownFormatError(format=format_string, kind='branch')
1562
1339
 
1565
1342
        """Return the current default format."""
1566
1343
        return klass._default_format
1567
1344
 
1568
 
    @classmethod
1569
 
    def get_formats(klass):
1570
 
        """Get all the known formats.
1571
 
 
1572
 
        Warning: This triggers a load of all lazy registered formats: do not
1573
 
        use except when that is desireed.
1574
 
        """
1575
 
        result = []
1576
 
        for fmt in klass._formats.values():
1577
 
            if isinstance(fmt, MetaDirBranchFormatFactory):
1578
 
                fmt = fmt()
1579
 
            result.append(fmt)
1580
 
        return result
1581
 
 
1582
 
    def get_reference(self, a_bzrdir, name=None):
 
1345
    def get_reference(self, a_bzrdir):
1583
1346
        """Get the target reference of the branch in a_bzrdir.
1584
1347
 
1585
1348
        format probing must have been completed before calling
1587
1350
        in a_bzrdir is correct.
1588
1351
 
1589
1352
        :param a_bzrdir: The bzrdir to get the branch data from.
1590
 
        :param name: Name of the colocated branch to fetch
1591
1353
        :return: None if the branch is not a reference branch.
1592
1354
        """
1593
1355
        return None
1594
1356
 
1595
1357
    @classmethod
1596
 
    def set_reference(self, a_bzrdir, name, to_branch):
 
1358
    def set_reference(self, a_bzrdir, to_branch):
1597
1359
        """Set the target reference of the branch in a_bzrdir.
1598
1360
 
1599
1361
        format probing must have been completed before calling
1601
1363
        in a_bzrdir is correct.
1602
1364
 
1603
1365
        :param a_bzrdir: The bzrdir to set the branch reference for.
1604
 
        :param name: Name of colocated branch to set, None for default
1605
1366
        :param to_branch: branch that the checkout is to reference
1606
1367
        """
1607
1368
        raise NotImplementedError(self.set_reference)
1614
1375
        """Return the short format description for this format."""
1615
1376
        raise NotImplementedError(self.get_format_description)
1616
1377
 
1617
 
    def _run_post_branch_init_hooks(self, a_bzrdir, name, branch):
1618
 
        hooks = Branch.hooks['post_branch_init']
1619
 
        if not hooks:
1620
 
            return
1621
 
        params = BranchInitHookParams(self, a_bzrdir, name, branch)
1622
 
        for hook in hooks:
1623
 
            hook(params)
1624
 
 
1625
 
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
1626
 
                           lock_type='metadir', set_format=True):
 
1378
    def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
 
1379
                           set_format=True):
1627
1380
        """Initialize a branch in a bzrdir, with specified files
1628
1381
 
1629
1382
        :param a_bzrdir: The bzrdir to initialize the branch in
1630
1383
        :param utf8_files: The files to create as a list of
1631
1384
            (filename, content) tuples
1632
 
        :param name: Name of colocated branch to create, if any
1633
1385
        :param set_format: If True, set the format with
1634
1386
            self.get_format_string.  (BzrBranch4 has its format set
1635
1387
            elsewhere)
1636
1388
        :return: a branch in this format
1637
1389
        """
1638
 
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
1639
 
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
1390
        mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
 
1391
        branch_transport = a_bzrdir.get_branch_transport(self)
1640
1392
        lock_map = {
1641
1393
            'metadir': ('lock', lockdir.LockDir),
1642
1394
            'branch4': ('branch-lock', lockable_files.TransportLock),
1645
1397
        control_files = lockable_files.LockableFiles(branch_transport,
1646
1398
            lock_name, lock_class)
1647
1399
        control_files.create_lock()
1648
 
        try:
1649
 
            control_files.lock_write()
1650
 
        except errors.LockContention:
1651
 
            if lock_type != 'branch4':
1652
 
                raise
1653
 
            lock_taken = False
1654
 
        else:
1655
 
            lock_taken = True
 
1400
        control_files.lock_write()
1656
1401
        if set_format:
1657
1402
            utf8_files += [('format', self.get_format_string())]
1658
1403
        try:
1661
1406
                    filename, content,
1662
1407
                    mode=a_bzrdir._get_file_mode())
1663
1408
        finally:
1664
 
            if lock_taken:
1665
 
                control_files.unlock()
1666
 
        branch = self.open(a_bzrdir, name, _found=True)
1667
 
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
1668
 
        return branch
 
1409
            control_files.unlock()
 
1410
        return self.open(a_bzrdir, _found=True)
1669
1411
 
1670
 
    def initialize(self, a_bzrdir, name=None):
1671
 
        """Create a branch of this format in a_bzrdir.
1672
 
        
1673
 
        :param name: Name of the colocated branch to create.
1674
 
        """
 
1412
    def initialize(self, a_bzrdir):
 
1413
        """Create a branch of this format in a_bzrdir."""
1675
1414
        raise NotImplementedError(self.initialize)
1676
1415
 
1677
1416
    def is_supported(self):
1707
1446
        """
1708
1447
        raise NotImplementedError(self.network_name)
1709
1448
 
1710
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1449
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
1711
1450
        """Return the branch object for a_bzrdir
1712
1451
 
1713
1452
        :param a_bzrdir: A BzrDir that contains a branch.
1714
 
        :param name: Name of colocated branch to open
1715
1453
        :param _found: a private parameter, do not use it. It is used to
1716
1454
            indicate if format probing has already be done.
1717
1455
        :param ignore_fallbacks: when set, no fallback branches will be opened
1721
1459
 
1722
1460
    @classmethod
1723
1461
    def register_format(klass, format):
1724
 
        """Register a metadir format.
1725
 
        
1726
 
        See MetaDirBranchFormatFactory for the ability to register a format
1727
 
        without loading the code the format needs until it is actually used.
1728
 
        """
 
1462
        """Register a metadir format."""
1729
1463
        klass._formats[format.get_format_string()] = format
1730
1464
        # Metadir formats have a network name of their format string, and get
1731
 
        # registered as factories.
1732
 
        if isinstance(format, MetaDirBranchFormatFactory):
1733
 
            network_format_registry.register(format.get_format_string(), format)
1734
 
        else:
1735
 
            network_format_registry.register(format.get_format_string(),
1736
 
                format.__class__)
 
1465
        # registered as class factories.
 
1466
        network_format_registry.register(format.get_format_string(), format.__class__)
1737
1467
 
1738
1468
    @classmethod
1739
1469
    def set_default_format(klass, format):
1740
1470
        klass._default_format = format
1741
1471
 
1742
 
    def supports_set_append_revisions_only(self):
1743
 
        """True if this format supports set_append_revisions_only."""
1744
 
        return False
1745
 
 
1746
1472
    def supports_stacking(self):
1747
1473
        """True if this format records a stacked-on branch."""
1748
1474
        return False
1759
1485
        return False  # by default
1760
1486
 
1761
1487
 
1762
 
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
1763
 
    """A factory for a BranchFormat object, permitting simple lazy registration.
1764
 
    
1765
 
    While none of the built in BranchFormats are lazy registered yet,
1766
 
    bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
1767
 
    use it, and the bzr-loom plugin uses it as well (see
1768
 
    bzrlib.plugins.loom.formats).
1769
 
    """
1770
 
 
1771
 
    def __init__(self, format_string, module_name, member_name):
1772
 
        """Create a MetaDirBranchFormatFactory.
1773
 
 
1774
 
        :param format_string: The format string the format has.
1775
 
        :param module_name: Module to load the format class from.
1776
 
        :param member_name: Attribute name within the module for the format class.
1777
 
        """
1778
 
        registry._LazyObjectGetter.__init__(self, module_name, member_name)
1779
 
        self._format_string = format_string
1780
 
        
1781
 
    def get_format_string(self):
1782
 
        """See BranchFormat.get_format_string."""
1783
 
        return self._format_string
1784
 
 
1785
 
    def __call__(self):
1786
 
        """Used for network_format_registry support."""
1787
 
        return self.get_obj()()
1788
 
 
1789
 
 
1790
1488
class BranchHooks(Hooks):
1791
1489
    """A dictionary mapping hook name to a list of callables for branch hooks.
1792
1490
 
1819
1517
            "with a bzrlib.branch.PullResult object and only runs in the "
1820
1518
            "bzr client.", (0, 15), None))
1821
1519
        self.create_hook(HookPoint('pre_commit',
1822
 
            "Called after a commit is calculated but before it is "
 
1520
            "Called after a commit is calculated but before it is is "
1823
1521
            "completed. pre_commit is called with (local, master, old_revno, "
1824
1522
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
1825
1523
            "). old_revid is NULL_REVISION for the first commit to a branch, "
1861
1559
            "multiple hooks installed for transform_fallback_location, "
1862
1560
            "all are called with the url returned from the previous hook."
1863
1561
            "The order is however undefined.", (1, 9), None))
1864
 
        self.create_hook(HookPoint('automatic_tag_name',
1865
 
            "Called to determine an automatic tag name for a revision. "
1866
 
            "automatic_tag_name is called with (branch, revision_id) and "
1867
 
            "should return a tag name or None if no tag name could be "
1868
 
            "determined. The first non-None tag name returned will be used.",
1869
 
            (2, 2), None))
1870
 
        self.create_hook(HookPoint('post_branch_init',
1871
 
            "Called after new branch initialization completes. "
1872
 
            "post_branch_init is called with a "
1873
 
            "bzrlib.branch.BranchInitHookParams. "
1874
 
            "Note that init, branch and checkout (both heavyweight and "
1875
 
            "lightweight) will all trigger this hook.", (2, 2), None))
1876
 
        self.create_hook(HookPoint('post_switch',
1877
 
            "Called after a checkout switches branch. "
1878
 
            "post_switch is called with a "
1879
 
            "bzrlib.branch.SwitchHookParams.", (2, 2), None))
1880
 
 
1881
1562
 
1882
1563
 
1883
1564
# install the default hooks into the Branch class.
1922
1603
            self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1923
1604
 
1924
1605
 
1925
 
class BranchInitHookParams(object):
1926
 
    """Object holding parameters passed to *_branch_init hooks.
1927
 
 
1928
 
    There are 4 fields that hooks may wish to access:
1929
 
 
1930
 
    :ivar format: the branch format
1931
 
    :ivar bzrdir: the BzrDir where the branch will be/has been initialized
1932
 
    :ivar name: name of colocated branch, if any (or None)
1933
 
    :ivar branch: the branch created
1934
 
 
1935
 
    Note that for lightweight checkouts, the bzrdir and format fields refer to
1936
 
    the checkout, hence they are different from the corresponding fields in
1937
 
    branch, which refer to the original branch.
1938
 
    """
1939
 
 
1940
 
    def __init__(self, format, a_bzrdir, name, branch):
1941
 
        """Create a group of BranchInitHook parameters.
1942
 
 
1943
 
        :param format: the branch format
1944
 
        :param a_bzrdir: the BzrDir where the branch will be/has been
1945
 
            initialized
1946
 
        :param name: name of colocated branch, if any (or None)
1947
 
        :param branch: the branch created
1948
 
 
1949
 
        Note that for lightweight checkouts, the bzrdir and format fields refer
1950
 
        to the checkout, hence they are different from the corresponding fields
1951
 
        in branch, which refer to the original branch.
1952
 
        """
1953
 
        self.format = format
1954
 
        self.bzrdir = a_bzrdir
1955
 
        self.name = name
1956
 
        self.branch = branch
1957
 
 
1958
 
    def __eq__(self, other):
1959
 
        return self.__dict__ == other.__dict__
1960
 
 
1961
 
    def __repr__(self):
1962
 
        return "<%s of %s>" % (self.__class__.__name__, self.branch)
1963
 
 
1964
 
 
1965
 
class SwitchHookParams(object):
1966
 
    """Object holding parameters passed to *_switch hooks.
1967
 
 
1968
 
    There are 4 fields that hooks may wish to access:
1969
 
 
1970
 
    :ivar control_dir: BzrDir of the checkout to change
1971
 
    :ivar to_branch: branch that the checkout is to reference
1972
 
    :ivar force: skip the check for local commits in a heavy checkout
1973
 
    :ivar revision_id: revision ID to switch to (or None)
1974
 
    """
1975
 
 
1976
 
    def __init__(self, control_dir, to_branch, force, revision_id):
1977
 
        """Create a group of SwitchHook parameters.
1978
 
 
1979
 
        :param control_dir: BzrDir of the checkout to change
1980
 
        :param to_branch: branch that the checkout is to reference
1981
 
        :param force: skip the check for local commits in a heavy checkout
1982
 
        :param revision_id: revision ID to switch to (or None)
1983
 
        """
1984
 
        self.control_dir = control_dir
1985
 
        self.to_branch = to_branch
1986
 
        self.force = force
1987
 
        self.revision_id = revision_id
1988
 
 
1989
 
    def __eq__(self, other):
1990
 
        return self.__dict__ == other.__dict__
1991
 
 
1992
 
    def __repr__(self):
1993
 
        return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
1994
 
            self.control_dir, self.to_branch,
1995
 
            self.revision_id)
1996
 
 
1997
 
 
1998
1606
class BzrBranchFormat4(BranchFormat):
1999
1607
    """Bzr branch format 4.
2000
1608
 
2007
1615
        """See BranchFormat.get_format_description()."""
2008
1616
        return "Branch format 4"
2009
1617
 
2010
 
    def initialize(self, a_bzrdir, name=None):
 
1618
    def initialize(self, a_bzrdir):
2011
1619
        """Create a branch of this format in a_bzrdir."""
2012
1620
        utf8_files = [('revision-history', ''),
2013
1621
                      ('branch-name', ''),
2014
1622
                      ]
2015
 
        return self._initialize_helper(a_bzrdir, utf8_files, name=name,
 
1623
        return self._initialize_helper(a_bzrdir, utf8_files,
2016
1624
                                       lock_type='branch4', set_format=False)
2017
1625
 
2018
1626
    def __init__(self):
2023
1631
        """The network name for this format is the control dirs disk label."""
2024
1632
        return self._matchingbzrdir.get_format_string()
2025
1633
 
2026
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1634
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
2027
1635
        """See BranchFormat.open()."""
2028
1636
        if not _found:
2029
1637
            # we are being called directly and must probe.
2031
1639
        return BzrBranch(_format=self,
2032
1640
                         _control_files=a_bzrdir._control_files,
2033
1641
                         a_bzrdir=a_bzrdir,
2034
 
                         name=name,
2035
1642
                         _repository=a_bzrdir.open_repository())
2036
1643
 
2037
1644
    def __str__(self):
2052
1659
        """
2053
1660
        return self.get_format_string()
2054
1661
 
2055
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1662
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
2056
1663
        """See BranchFormat.open()."""
2057
1664
        if not _found:
2058
 
            format = BranchFormat.find_format(a_bzrdir, name=name)
 
1665
            format = BranchFormat.find_format(a_bzrdir)
2059
1666
            if format.__class__ != self.__class__:
2060
1667
                raise AssertionError("wrong format %r found for %r" %
2061
1668
                    (format, self))
2062
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
2063
1669
        try:
 
1670
            transport = a_bzrdir.get_branch_transport(None)
2064
1671
            control_files = lockable_files.LockableFiles(transport, 'lock',
2065
1672
                                                         lockdir.LockDir)
2066
1673
            return self._branch_class()(_format=self,
2067
1674
                              _control_files=control_files,
2068
 
                              name=name,
2069
1675
                              a_bzrdir=a_bzrdir,
2070
1676
                              _repository=a_bzrdir.find_repository(),
2071
1677
                              ignore_fallbacks=ignore_fallbacks)
2072
1678
        except errors.NoSuchFile:
2073
 
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
 
1679
            raise errors.NotBranchError(path=transport.base)
2074
1680
 
2075
1681
    def __init__(self):
2076
1682
        super(BranchFormatMetadir, self).__init__()
2105
1711
        """See BranchFormat.get_format_description()."""
2106
1712
        return "Branch format 5"
2107
1713
 
2108
 
    def initialize(self, a_bzrdir, name=None):
 
1714
    def initialize(self, a_bzrdir):
2109
1715
        """Create a branch of this format in a_bzrdir."""
2110
1716
        utf8_files = [('revision-history', ''),
2111
1717
                      ('branch-name', ''),
2112
1718
                      ]
2113
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
1719
        return self._initialize_helper(a_bzrdir, utf8_files)
2114
1720
 
2115
1721
    def supports_tags(self):
2116
1722
        return False
2138
1744
        """See BranchFormat.get_format_description()."""
2139
1745
        return "Branch format 6"
2140
1746
 
2141
 
    def initialize(self, a_bzrdir, name=None):
 
1747
    def initialize(self, a_bzrdir):
2142
1748
        """Create a branch of this format in a_bzrdir."""
2143
1749
        utf8_files = [('last-revision', '0 null:\n'),
2144
1750
                      ('branch.conf', ''),
2145
1751
                      ('tags', ''),
2146
1752
                      ]
2147
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
1753
        return self._initialize_helper(a_bzrdir, utf8_files)
2148
1754
 
2149
1755
    def make_tags(self, branch):
2150
1756
        """See bzrlib.branch.BranchFormat.make_tags()."""
2151
1757
        return BasicTags(branch)
2152
1758
 
2153
 
    def supports_set_append_revisions_only(self):
2154
 
        return True
2155
1759
 
2156
1760
 
2157
1761
class BzrBranchFormat8(BranchFormatMetadir):
2168
1772
        """See BranchFormat.get_format_description()."""
2169
1773
        return "Branch format 8"
2170
1774
 
2171
 
    def initialize(self, a_bzrdir, name=None):
 
1775
    def initialize(self, a_bzrdir):
2172
1776
        """Create a branch of this format in a_bzrdir."""
2173
1777
        utf8_files = [('last-revision', '0 null:\n'),
2174
1778
                      ('branch.conf', ''),
2175
1779
                      ('tags', ''),
2176
1780
                      ('references', '')
2177
1781
                      ]
2178
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
1782
        return self._initialize_helper(a_bzrdir, utf8_files)
2179
1783
 
2180
1784
    def __init__(self):
2181
1785
        super(BzrBranchFormat8, self).__init__()
2186
1790
        """See bzrlib.branch.BranchFormat.make_tags()."""
2187
1791
        return BasicTags(branch)
2188
1792
 
2189
 
    def supports_set_append_revisions_only(self):
2190
 
        return True
2191
 
 
2192
1793
    def supports_stacking(self):
2193
1794
        return True
2194
1795
 
2204
1805
    This format was introduced in bzr 1.6.
2205
1806
    """
2206
1807
 
2207
 
    def initialize(self, a_bzrdir, name=None):
 
1808
    def initialize(self, a_bzrdir):
2208
1809
        """Create a branch of this format in a_bzrdir."""
2209
1810
        utf8_files = [('last-revision', '0 null:\n'),
2210
1811
                      ('branch.conf', ''),
2211
1812
                      ('tags', ''),
2212
1813
                      ]
2213
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
1814
        return self._initialize_helper(a_bzrdir, utf8_files)
2214
1815
 
2215
1816
    def _branch_class(self):
2216
1817
        return BzrBranch7
2223
1824
        """See BranchFormat.get_format_description()."""
2224
1825
        return "Branch format 7"
2225
1826
 
2226
 
    def supports_set_append_revisions_only(self):
2227
 
        return True
2228
 
 
2229
1827
    supports_reference_locations = False
2230
1828
 
2231
1829
 
2248
1846
        """See BranchFormat.get_format_description()."""
2249
1847
        return "Checkout reference format 1"
2250
1848
 
2251
 
    def get_reference(self, a_bzrdir, name=None):
 
1849
    def get_reference(self, a_bzrdir):
2252
1850
        """See BranchFormat.get_reference()."""
2253
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
2254
 
        return transport.get_bytes('location')
 
1851
        transport = a_bzrdir.get_branch_transport(None)
 
1852
        return transport.get('location').read()
2255
1853
 
2256
 
    def set_reference(self, a_bzrdir, name, to_branch):
 
1854
    def set_reference(self, a_bzrdir, to_branch):
2257
1855
        """See BranchFormat.set_reference()."""
2258
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
1856
        transport = a_bzrdir.get_branch_transport(None)
2259
1857
        location = transport.put_bytes('location', to_branch.base)
2260
1858
 
2261
 
    def initialize(self, a_bzrdir, name=None, target_branch=None):
 
1859
    def initialize(self, a_bzrdir, target_branch=None):
2262
1860
        """Create a branch of this format in a_bzrdir."""
2263
1861
        if target_branch is None:
2264
1862
            # this format does not implement branch itself, thus the implicit
2265
1863
            # creation contract must see it as uninitializable
2266
1864
            raise errors.UninitializableFormat(self)
2267
 
        mutter('creating branch reference in %s', a_bzrdir.user_url)
2268
 
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
1865
        mutter('creating branch reference in %s', a_bzrdir.transport.base)
 
1866
        branch_transport = a_bzrdir.get_branch_transport(self)
2269
1867
        branch_transport.put_bytes('location',
2270
 
            target_branch.bzrdir.user_url)
 
1868
            target_branch.bzrdir.root_transport.base)
2271
1869
        branch_transport.put_bytes('format', self.get_format_string())
2272
 
        branch = self.open(
2273
 
            a_bzrdir, name, _found=True,
 
1870
        return self.open(
 
1871
            a_bzrdir, _found=True,
2274
1872
            possible_transports=[target_branch.bzrdir.root_transport])
2275
 
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2276
 
        return branch
2277
1873
 
2278
1874
    def __init__(self):
2279
1875
        super(BranchReferenceFormat, self).__init__()
2285
1881
        def clone(to_bzrdir, revision_id=None,
2286
1882
            repository_policy=None):
2287
1883
            """See Branch.clone()."""
2288
 
            return format.initialize(to_bzrdir, target_branch=a_branch)
 
1884
            return format.initialize(to_bzrdir, a_branch)
2289
1885
            # cannot obey revision_id limits when cloning a reference ...
2290
1886
            # FIXME RBC 20060210 either nuke revision_id for clone, or
2291
1887
            # emit some sort of warning/error to the caller ?!
2292
1888
        return clone
2293
1889
 
2294
 
    def open(self, a_bzrdir, name=None, _found=False, location=None,
 
1890
    def open(self, a_bzrdir, _found=False, location=None,
2295
1891
             possible_transports=None, ignore_fallbacks=False):
2296
1892
        """Return the branch that the branch reference in a_bzrdir points at.
2297
1893
 
2298
1894
        :param a_bzrdir: A BzrDir that contains a branch.
2299
 
        :param name: Name of colocated branch to open, if any
2300
1895
        :param _found: a private parameter, do not use it. It is used to
2301
1896
            indicate if format probing has already be done.
2302
1897
        :param ignore_fallbacks: when set, no fallback branches will be opened
2307
1902
        :param possible_transports: An optional reusable transports list.
2308
1903
        """
2309
1904
        if not _found:
2310
 
            format = BranchFormat.find_format(a_bzrdir, name=name)
 
1905
            format = BranchFormat.find_format(a_bzrdir)
2311
1906
            if format.__class__ != self.__class__:
2312
1907
                raise AssertionError("wrong format %r found for %r" %
2313
1908
                    (format, self))
2314
1909
        if location is None:
2315
 
            location = self.get_reference(a_bzrdir, name)
 
1910
            location = self.get_reference(a_bzrdir)
2316
1911
        real_bzrdir = bzrdir.BzrDir.open(
2317
1912
            location, possible_transports=possible_transports)
2318
 
        result = real_bzrdir.open_branch(name=name, 
2319
 
            ignore_fallbacks=ignore_fallbacks)
 
1913
        result = real_bzrdir.open_branch(ignore_fallbacks=ignore_fallbacks)
2320
1914
        # this changes the behaviour of result.clone to create a new reference
2321
1915
        # rather than a copy of the content of the branch.
2322
1916
        # I did not use a proxy object because that needs much more extensive
2349
1943
BranchFormat.register_format(__format6)
2350
1944
BranchFormat.register_format(__format7)
2351
1945
BranchFormat.register_format(__format8)
2352
 
BranchFormat.set_default_format(__format7)
 
1946
BranchFormat.set_default_format(__format6)
2353
1947
_legacy_formats = [BzrBranchFormat4(),
2354
1948
    ]
2355
1949
network_format_registry.register(
2356
1950
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
2357
1951
 
2358
1952
 
2359
 
class BranchWriteLockResult(LogicalLockResult):
2360
 
    """The result of write locking a branch.
2361
 
 
2362
 
    :ivar branch_token: The token obtained from the underlying branch lock, or
2363
 
        None.
2364
 
    :ivar unlock: A callable which will unlock the lock.
2365
 
    """
2366
 
 
2367
 
    def __init__(self, unlock, branch_token):
2368
 
        LogicalLockResult.__init__(self, unlock)
2369
 
        self.branch_token = branch_token
2370
 
 
2371
 
    def __repr__(self):
2372
 
        return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
2373
 
            self.unlock)
2374
 
 
2375
 
 
2376
 
class BzrBranch(Branch, _RelockDebugMixin):
 
1953
class BzrBranch(Branch):
2377
1954
    """A branch stored in the actual filesystem.
2378
1955
 
2379
1956
    Note that it's "local" in the context of the filesystem; it doesn't
2385
1962
    :ivar repository: Repository for this branch.
2386
1963
    :ivar base: The url of the base directory for this branch; the one
2387
1964
        containing the .bzr directory.
2388
 
    :ivar name: Optional colocated branch name as it exists in the control
2389
 
        directory.
2390
1965
    """
2391
1966
 
2392
1967
    def __init__(self, _format=None,
2393
 
                 _control_files=None, a_bzrdir=None, name=None,
2394
 
                 _repository=None, ignore_fallbacks=False):
 
1968
                 _control_files=None, a_bzrdir=None, _repository=None,
 
1969
                 ignore_fallbacks=False):
2395
1970
        """Create new branch object at a particular location."""
2396
1971
        if a_bzrdir is None:
2397
1972
            raise ValueError('a_bzrdir must be supplied')
2398
1973
        else:
2399
1974
            self.bzrdir = a_bzrdir
2400
1975
        self._base = self.bzrdir.transport.clone('..').base
2401
 
        self.name = name
2402
1976
        # XXX: We should be able to just do
2403
1977
        #   self.base = self.bzrdir.root_transport.base
2404
1978
        # but this does not quite work yet -- mbp 20080522
2411
1985
        Branch.__init__(self)
2412
1986
 
2413
1987
    def __str__(self):
2414
 
        if self.name is None:
2415
 
            return '%s(%s)' % (self.__class__.__name__, self.user_url)
2416
 
        else:
2417
 
            return '%s(%s,%s)' % (self.__class__.__name__, self.user_url,
2418
 
                self.name)
 
1988
        return '%s(%r)' % (self.__class__.__name__, self.base)
2419
1989
 
2420
1990
    __repr__ = __str__
2421
1991
 
2432
2002
        return self.control_files.is_locked()
2433
2003
 
2434
2004
    def lock_write(self, token=None):
2435
 
        """Lock the branch for write operations.
2436
 
 
2437
 
        :param token: A token to permit reacquiring a previously held and
2438
 
            preserved lock.
2439
 
        :return: A BranchWriteLockResult.
2440
 
        """
2441
 
        if not self.is_locked():
2442
 
            self._note_lock('w')
2443
2005
        # All-in-one needs to always unlock/lock.
2444
2006
        repo_control = getattr(self.repository, 'control_files', None)
2445
2007
        if self.control_files == repo_control or not self.is_locked():
2446
 
            self.repository._warn_if_deprecated(self)
2447
2008
            self.repository.lock_write()
2448
2009
            took_lock = True
2449
2010
        else:
2450
2011
            took_lock = False
2451
2012
        try:
2452
 
            return BranchWriteLockResult(self.unlock,
2453
 
                self.control_files.lock_write(token=token))
 
2013
            return self.control_files.lock_write(token=token)
2454
2014
        except:
2455
2015
            if took_lock:
2456
2016
                self.repository.unlock()
2457
2017
            raise
2458
2018
 
2459
2019
    def lock_read(self):
2460
 
        """Lock the branch for read operations.
2461
 
 
2462
 
        :return: A bzrlib.lock.LogicalLockResult.
2463
 
        """
2464
 
        if not self.is_locked():
2465
 
            self._note_lock('r')
2466
2020
        # All-in-one needs to always unlock/lock.
2467
2021
        repo_control = getattr(self.repository, 'control_files', None)
2468
2022
        if self.control_files == repo_control or not self.is_locked():
2469
 
            self.repository._warn_if_deprecated(self)
2470
2023
            self.repository.lock_read()
2471
2024
            took_lock = True
2472
2025
        else:
2473
2026
            took_lock = False
2474
2027
        try:
2475
2028
            self.control_files.lock_read()
2476
 
            return LogicalLockResult(self.unlock)
2477
2029
        except:
2478
2030
            if took_lock:
2479
2031
                self.repository.unlock()
2480
2032
            raise
2481
2033
 
2482
 
    @only_raises(errors.LockNotHeld, errors.LockBroken)
2483
2034
    def unlock(self):
2484
2035
        try:
2485
2036
            self.control_files.unlock()
2616
2167
        """See Branch.basis_tree."""
2617
2168
        return self.repository.revision_tree(self.last_revision())
2618
2169
 
 
2170
    @needs_write_lock
 
2171
    def pull(self, source, overwrite=False, stop_revision=None,
 
2172
             _hook_master=None, run_hooks=True, possible_transports=None,
 
2173
             _override_hook_target=None):
 
2174
        """See Branch.pull.
 
2175
 
 
2176
        :param _hook_master: Private parameter - set the branch to
 
2177
            be supplied as the master to pull hooks.
 
2178
        :param run_hooks: Private parameter - if false, this branch
 
2179
            is being called because it's the master of the primary branch,
 
2180
            so it should not run its hooks.
 
2181
        :param _override_hook_target: Private parameter - set the branch to be
 
2182
            supplied as the target_branch to pull hooks.
 
2183
        """
 
2184
        result = PullResult()
 
2185
        result.source_branch = source
 
2186
        if _override_hook_target is None:
 
2187
            result.target_branch = self
 
2188
        else:
 
2189
            result.target_branch = _override_hook_target
 
2190
        source.lock_read()
 
2191
        try:
 
2192
            # We assume that during 'pull' the local repository is closer than
 
2193
            # the remote one.
 
2194
            source.update_references(self)
 
2195
            graph = self.repository.get_graph(source.repository)
 
2196
            result.old_revno, result.old_revid = self.last_revision_info()
 
2197
            self.update_revisions(source, stop_revision, overwrite=overwrite,
 
2198
                                  graph=graph)
 
2199
            result.tag_conflicts = source.tags.merge_to(self.tags, overwrite)
 
2200
            result.new_revno, result.new_revid = self.last_revision_info()
 
2201
            if _hook_master:
 
2202
                result.master_branch = _hook_master
 
2203
                result.local_branch = result.target_branch
 
2204
            else:
 
2205
                result.master_branch = result.target_branch
 
2206
                result.local_branch = None
 
2207
            if run_hooks:
 
2208
                for hook in Branch.hooks['post_pull']:
 
2209
                    hook(result)
 
2210
        finally:
 
2211
            source.unlock()
 
2212
        return result
 
2213
 
2619
2214
    def _get_parent_location(self):
2620
2215
        _locs = ['parent', 'pull', 'x-pull']
2621
2216
        for l in _locs:
2625
2220
                pass
2626
2221
        return None
2627
2222
 
 
2223
    @needs_read_lock
 
2224
    def push(self, target, overwrite=False, stop_revision=None,
 
2225
             _override_hook_source_branch=None):
 
2226
        """See Branch.push.
 
2227
 
 
2228
        This is the basic concrete implementation of push()
 
2229
 
 
2230
        :param _override_hook_source_branch: If specified, run
 
2231
        the hooks passing this Branch as the source, rather than self.
 
2232
        This is for use of RemoteBranch, where push is delegated to the
 
2233
        underlying vfs-based Branch.
 
2234
        """
 
2235
        # TODO: Public option to disable running hooks - should be trivial but
 
2236
        # needs tests.
 
2237
        return _run_with_write_locked_target(
 
2238
            target, self._push_with_bound_branches, target, overwrite,
 
2239
            stop_revision,
 
2240
            _override_hook_source_branch=_override_hook_source_branch)
 
2241
 
 
2242
    def _push_with_bound_branches(self, target, overwrite,
 
2243
            stop_revision,
 
2244
            _override_hook_source_branch=None):
 
2245
        """Push from self into target, and into target's master if any.
 
2246
 
 
2247
        This is on the base BzrBranch class even though it doesn't support
 
2248
        bound branches because the *target* might be bound.
 
2249
        """
 
2250
        def _run_hooks():
 
2251
            if _override_hook_source_branch:
 
2252
                result.source_branch = _override_hook_source_branch
 
2253
            for hook in Branch.hooks['post_push']:
 
2254
                hook(result)
 
2255
 
 
2256
        bound_location = target.get_bound_location()
 
2257
        if bound_location and target.base != bound_location:
 
2258
            # there is a master branch.
 
2259
            #
 
2260
            # XXX: Why the second check?  Is it even supported for a branch to
 
2261
            # be bound to itself? -- mbp 20070507
 
2262
            master_branch = target.get_master_branch()
 
2263
            master_branch.lock_write()
 
2264
            try:
 
2265
                # push into the master from this branch.
 
2266
                self._basic_push(master_branch, overwrite, stop_revision)
 
2267
                # and push into the target branch from this. Note that we push from
 
2268
                # this branch again, because its considered the highest bandwidth
 
2269
                # repository.
 
2270
                result = self._basic_push(target, overwrite, stop_revision)
 
2271
                result.master_branch = master_branch
 
2272
                result.local_branch = target
 
2273
                _run_hooks()
 
2274
                return result
 
2275
            finally:
 
2276
                master_branch.unlock()
 
2277
        else:
 
2278
            # no master branch
 
2279
            result = self._basic_push(target, overwrite, stop_revision)
 
2280
            # TODO: Why set master_branch and local_branch if there's no
 
2281
            # binding?  Maybe cleaner to just leave them unset? -- mbp
 
2282
            # 20070504
 
2283
            result.master_branch = target
 
2284
            result.local_branch = None
 
2285
            _run_hooks()
 
2286
            return result
 
2287
 
2628
2288
    def _basic_push(self, target, overwrite, stop_revision):
2629
2289
        """Basic implementation of push without bound branches or hooks.
2630
2290
 
2631
 
        Must be called with source read locked and target write locked.
 
2291
        Must be called with self read locked and target write locked.
2632
2292
        """
2633
2293
        result = BranchPushResult()
2634
2294
        result.source_branch = self
2639
2299
            # We assume that during 'push' this repository is closer than
2640
2300
            # the target.
2641
2301
            graph = self.repository.get_graph(target.repository)
2642
 
            target.update_revisions(self, stop_revision,
2643
 
                overwrite=overwrite, graph=graph)
 
2302
            target.update_revisions(self, stop_revision, overwrite=overwrite,
 
2303
                                    graph=graph)
2644
2304
        if self._push_should_merge_tags():
2645
 
            result.tag_conflicts = self.tags.merge_to(target.tags,
2646
 
                overwrite)
 
2305
            result.tag_conflicts = self.tags.merge_to(target.tags, overwrite)
2647
2306
        result.new_revno, result.new_revid = target.last_revision_info()
2648
2307
        return result
2649
2308
 
2650
2309
    def get_stacked_on_url(self):
2651
 
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
2310
        raise errors.UnstackableBranchFormat(self._format, self.base)
2652
2311
 
2653
2312
    def set_push_location(self, location):
2654
2313
        """See Branch.set_push_location."""
2670
2329
    It has support for a master_branch which is the data for bound branches.
2671
2330
    """
2672
2331
 
 
2332
    @needs_write_lock
 
2333
    def pull(self, source, overwrite=False, stop_revision=None,
 
2334
             run_hooks=True, possible_transports=None,
 
2335
             _override_hook_target=None):
 
2336
        """Pull from source into self, updating my master if any.
 
2337
 
 
2338
        :param run_hooks: Private parameter - if false, this branch
 
2339
            is being called because it's the master of the primary branch,
 
2340
            so it should not run its hooks.
 
2341
        """
 
2342
        bound_location = self.get_bound_location()
 
2343
        master_branch = None
 
2344
        if bound_location and source.base != bound_location:
 
2345
            # not pulling from master, so we need to update master.
 
2346
            master_branch = self.get_master_branch(possible_transports)
 
2347
            master_branch.lock_write()
 
2348
        try:
 
2349
            if master_branch:
 
2350
                # pull from source into master.
 
2351
                master_branch.pull(source, overwrite, stop_revision,
 
2352
                    run_hooks=False)
 
2353
            return super(BzrBranch5, self).pull(source, overwrite,
 
2354
                stop_revision, _hook_master=master_branch,
 
2355
                run_hooks=run_hooks,
 
2356
                _override_hook_target=_override_hook_target)
 
2357
        finally:
 
2358
            if master_branch:
 
2359
                master_branch.unlock()
 
2360
 
2673
2361
    def get_bound_location(self):
2674
2362
        try:
2675
2363
            return self._transport.get_bytes('bound')[:-1]
2781
2469
                    raise AssertionError(
2782
2470
                        "'transform_fallback_location' hook %s returned "
2783
2471
                        "None, not a URL." % hook_name)
2784
 
            self._activate_fallback_location(url)
 
2472
            self._activate_fallback_location(url, None)
2785
2473
 
2786
2474
    def __init__(self, *args, **kwargs):
2787
2475
        self._ignore_fallbacks = kwargs.get('ignore_fallbacks', False)
2788
2476
        super(BzrBranch8, self).__init__(*args, **kwargs)
2789
2477
        self._last_revision_info_cache = None
 
2478
        self._partial_revision_history_cache = []
2790
2479
        self._reference_info = None
2791
2480
 
2792
2481
    def _clear_cached_state(self):
2793
2482
        super(BzrBranch8, self)._clear_cached_state()
2794
2483
        self._last_revision_info_cache = None
 
2484
        self._partial_revision_history_cache = []
2795
2485
        self._reference_info = None
2796
2486
 
2797
2487
    def _last_revision_info(self):
2844
2534
        if _mod_revision.is_null(last_revision):
2845
2535
            return
2846
2536
        if last_revision not in self._lefthand_history(revision_id):
2847
 
            raise errors.AppendRevisionsOnlyViolation(self.user_url)
 
2537
            raise errors.AppendRevisionsOnlyViolation(self.base)
2848
2538
 
2849
2539
    def _gen_revision_history(self):
2850
2540
        """Generate the revision history from last revision
2853
2543
        self._extend_partial_history(stop_index=last_revno-1)
2854
2544
        return list(reversed(self._partial_revision_history_cache))
2855
2545
 
 
2546
    def _extend_partial_history(self, stop_index=None, stop_revision=None):
 
2547
        """Extend the partial history to include a given index
 
2548
 
 
2549
        If a stop_index is supplied, stop when that index has been reached.
 
2550
        If a stop_revision is supplied, stop when that revision is
 
2551
        encountered.  Otherwise, stop when the beginning of history is
 
2552
        reached.
 
2553
 
 
2554
        :param stop_index: The index which should be present.  When it is
 
2555
            present, history extension will stop.
 
2556
        :param revision_id: The revision id which should be present.  When
 
2557
            it is encountered, history extension will stop.
 
2558
        """
 
2559
        repo = self.repository
 
2560
        if len(self._partial_revision_history_cache) == 0:
 
2561
            iterator = repo.iter_reverse_revision_history(self.last_revision())
 
2562
        else:
 
2563
            start_revision = self._partial_revision_history_cache[-1]
 
2564
            iterator = repo.iter_reverse_revision_history(start_revision)
 
2565
            #skip the last revision in the list
 
2566
            next_revision = iterator.next()
 
2567
        for revision_id in iterator:
 
2568
            self._partial_revision_history_cache.append(revision_id)
 
2569
            if (stop_index is not None and
 
2570
                len(self._partial_revision_history_cache) > stop_index):
 
2571
                break
 
2572
            if revision_id == stop_revision:
 
2573
                break
 
2574
 
2856
2575
    def _write_revision_history(self, history):
2857
2576
        """Factored out of set_revision_history.
2858
2577
 
2950
2669
        if branch_location is None:
2951
2670
            return Branch.reference_parent(self, file_id, path,
2952
2671
                                           possible_transports)
2953
 
        branch_location = urlutils.join(self.user_url, branch_location)
 
2672
        branch_location = urlutils.join(self.base, branch_location)
2954
2673
        return Branch.open(branch_location,
2955
2674
                           possible_transports=possible_transports)
2956
2675
 
3001
2720
            raise errors.NotStacked(self)
3002
2721
        return stacked_url
3003
2722
 
 
2723
    def set_append_revisions_only(self, enabled):
 
2724
        if enabled:
 
2725
            value = 'True'
 
2726
        else:
 
2727
            value = 'False'
 
2728
        self.get_config().set_user_option('append_revisions_only', value,
 
2729
            warn_masked=True)
 
2730
 
3004
2731
    def _get_append_revisions_only(self):
3005
 
        return self.get_config(
3006
 
            ).get_user_option_as_bool('append_revisions_only')
 
2732
        value = self.get_config().get_user_option('append_revisions_only')
 
2733
        return value == 'True'
3007
2734
 
3008
2735
    @needs_write_lock
3009
2736
    def generate_revision_history(self, revision_id, last_rev=None,
3071
2798
    """
3072
2799
 
3073
2800
    def get_stacked_on_url(self):
3074
 
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
2801
        raise errors.UnstackableBranchFormat(self._format, self.base)
3075
2802
 
3076
2803
 
3077
2804
######################################################################
3103
2830
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
3104
2831
    """
3105
2832
 
3106
 
    @deprecated_method(deprecated_in((2, 3, 0)))
3107
2833
    def __int__(self):
3108
 
        """Return the relative change in revno.
3109
 
 
3110
 
        :deprecated: Use `new_revno` and `old_revno` instead.
3111
 
        """
 
2834
        # DEPRECATED: pull used to return the change in revno
3112
2835
        return self.new_revno - self.old_revno
3113
2836
 
3114
2837
    def report(self, to_file):
3139
2862
        target, otherwise it will be None.
3140
2863
    """
3141
2864
 
3142
 
    @deprecated_method(deprecated_in((2, 3, 0)))
3143
2865
    def __int__(self):
3144
 
        """Return the relative change in revno.
3145
 
 
3146
 
        :deprecated: Use `new_revno` and `old_revno` instead.
3147
 
        """
 
2866
        # DEPRECATED: push used to return the change in revno
3148
2867
        return self.new_revno - self.old_revno
3149
2868
 
3150
2869
    def report(self, to_file):
3164
2883
 
3165
2884
    def __init__(self, branch):
3166
2885
        self.branch = branch
3167
 
        self.errors = []
3168
2886
 
3169
2887
    def report_results(self, verbose):
3170
2888
        """Report the check results via trace.note.
3172
2890
        :param verbose: Requests more detailed display of what was checked,
3173
2891
            if any.
3174
2892
        """
3175
 
        note('checked branch %s format %s', self.branch.user_url,
3176
 
            self.branch._format)
3177
 
        for error in self.errors:
3178
 
            note('found error:%s', error)
 
2893
        note('checked branch %s format %s',
 
2894
             self.branch.base,
 
2895
             self.branch._format)
3179
2896
 
3180
2897
 
3181
2898
class Converter5to6(object):
3273
2990
    _optimisers = []
3274
2991
    """The available optimised InterBranch types."""
3275
2992
 
3276
 
    @classmethod
3277
 
    def _get_branch_formats_to_test(klass):
3278
 
        """Return an iterable of format tuples for testing.
3279
 
        
3280
 
        :return: An iterable of (from_format, to_format) to use when testing
3281
 
            this InterBranch class. Each InterBranch class should define this
3282
 
            method itself.
3283
 
        """
3284
 
        raise NotImplementedError(klass._get_branch_formats_to_test)
3285
 
 
3286
 
    @needs_write_lock
3287
 
    def pull(self, overwrite=False, stop_revision=None,
3288
 
             possible_transports=None, local=False):
3289
 
        """Mirror source into target branch.
3290
 
 
3291
 
        The target branch is considered to be 'local', having low latency.
3292
 
 
3293
 
        :returns: PullResult instance
3294
 
        """
3295
 
        raise NotImplementedError(self.pull)
3296
 
 
3297
 
    @needs_write_lock
 
2993
    @staticmethod
 
2994
    def _get_branch_formats_to_test():
 
2995
        """Return a tuple with the Branch formats to use when testing."""
 
2996
        raise NotImplementedError(self._get_branch_formats_to_test)
 
2997
 
3298
2998
    def update_revisions(self, stop_revision=None, overwrite=False,
3299
2999
                         graph=None):
3300
3000
        """Pull in new perfect-fit revisions.
3308
3008
        """
3309
3009
        raise NotImplementedError(self.update_revisions)
3310
3010
 
3311
 
    @needs_write_lock
3312
 
    def push(self, overwrite=False, stop_revision=None,
3313
 
             _override_hook_source_branch=None):
3314
 
        """Mirror the source branch into the target branch.
3315
 
 
3316
 
        The source branch is considered to be 'local', having low latency.
3317
 
        """
3318
 
        raise NotImplementedError(self.push)
3319
 
 
3320
 
    @needs_write_lock
3321
 
    def copy_content_into(self, revision_id=None):
3322
 
        """Copy the content of source into target
3323
 
 
3324
 
        revision_id: if not None, the revision history in the new branch will
3325
 
                     be truncated to end with revision_id.
3326
 
        """
3327
 
        raise NotImplementedError(self.copy_content_into)
3328
 
 
3329
3011
 
3330
3012
class GenericInterBranch(InterBranch):
3331
 
    """InterBranch implementation that uses public Branch functions."""
3332
 
 
3333
 
    @classmethod
3334
 
    def is_compatible(klass, source, target):
3335
 
        # GenericBranch uses the public API, so always compatible
3336
 
        return True
3337
 
 
3338
 
    @classmethod
3339
 
    def _get_branch_formats_to_test(klass):
3340
 
        return [(BranchFormat._default_format, BranchFormat._default_format)]
3341
 
 
3342
 
    @classmethod
3343
 
    def unwrap_format(klass, format):
3344
 
        if isinstance(format, remote.RemoteBranchFormat):
3345
 
            format._ensure_real()
3346
 
            return format._custom_format
3347
 
        return format                                                                                                  
3348
 
 
3349
 
    @needs_write_lock
3350
 
    def copy_content_into(self, revision_id=None):
3351
 
        """Copy the content of source into target
3352
 
 
3353
 
        revision_id: if not None, the revision history in the new branch will
3354
 
                     be truncated to end with revision_id.
3355
 
        """
3356
 
        self.source.update_references(self.target)
3357
 
        self.source._synchronize_history(self.target, revision_id)
3358
 
        try:
3359
 
            parent = self.source.get_parent()
3360
 
        except errors.InaccessibleParent, e:
3361
 
            mutter('parent was not accessible to copy: %s', e)
3362
 
        else:
3363
 
            if parent:
3364
 
                self.target.set_parent(parent)
3365
 
        if self.source._push_should_merge_tags():
3366
 
            self.source.tags.merge_to(self.target.tags)
3367
 
 
3368
 
    @needs_write_lock
 
3013
    """InterBranch implementation that uses public Branch functions.
 
3014
    """
 
3015
 
 
3016
    @staticmethod
 
3017
    def _get_branch_formats_to_test():
 
3018
        return BranchFormat._default_format, BranchFormat._default_format
 
3019
 
3369
3020
    def update_revisions(self, stop_revision=None, overwrite=False,
3370
3021
        graph=None):
3371
3022
        """See InterBranch.update_revisions()."""
3372
 
        other_revno, other_last_revision = self.source.last_revision_info()
3373
 
        stop_revno = None # unknown
3374
 
        if stop_revision is None:
3375
 
            stop_revision = other_last_revision
3376
 
            if _mod_revision.is_null(stop_revision):
3377
 
                # if there are no commits, we're done.
3378
 
                return
3379
 
            stop_revno = other_revno
3380
 
 
3381
 
        # what's the current last revision, before we fetch [and change it
3382
 
        # possibly]
3383
 
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
3384
 
        # we fetch here so that we don't process data twice in the common
3385
 
        # case of having something to pull, and so that the check for
3386
 
        # already merged can operate on the just fetched graph, which will
3387
 
        # be cached in memory.
3388
 
        self.target.fetch(self.source, stop_revision)
3389
 
        # Check to see if one is an ancestor of the other
3390
 
        if not overwrite:
3391
 
            if graph is None:
3392
 
                graph = self.target.repository.get_graph()
3393
 
            if self.target._check_if_descendant_or_diverged(
3394
 
                    stop_revision, last_rev, graph, self.source):
3395
 
                # stop_revision is a descendant of last_rev, but we aren't
3396
 
                # overwriting, so we're done.
3397
 
                return
3398
 
        if stop_revno is None:
3399
 
            if graph is None:
3400
 
                graph = self.target.repository.get_graph()
3401
 
            this_revno, this_last_revision = \
3402
 
                    self.target.last_revision_info()
3403
 
            stop_revno = graph.find_distance_to_null(stop_revision,
3404
 
                            [(other_last_revision, other_revno),
3405
 
                             (this_last_revision, this_revno)])
3406
 
        self.target.set_last_revision_info(stop_revno, stop_revision)
3407
 
 
3408
 
    @needs_write_lock
3409
 
    def pull(self, overwrite=False, stop_revision=None,
3410
 
             possible_transports=None, run_hooks=True,
3411
 
             _override_hook_target=None, local=False):
3412
 
        """Pull from source into self, updating my master if any.
3413
 
 
3414
 
        :param run_hooks: Private parameter - if false, this branch
3415
 
            is being called because it's the master of the primary branch,
3416
 
            so it should not run its hooks.
3417
 
        """
3418
 
        bound_location = self.target.get_bound_location()
3419
 
        if local and not bound_location:
3420
 
            raise errors.LocalRequiresBoundBranch()
3421
 
        master_branch = None
3422
 
        if not local and bound_location and self.source.user_url != bound_location:
3423
 
            # not pulling from master, so we need to update master.
3424
 
            master_branch = self.target.get_master_branch(possible_transports)
3425
 
            master_branch.lock_write()
3426
 
        try:
3427
 
            if master_branch:
3428
 
                # pull from source into master.
3429
 
                master_branch.pull(self.source, overwrite, stop_revision,
3430
 
                    run_hooks=False)
3431
 
            return self._pull(overwrite,
3432
 
                stop_revision, _hook_master=master_branch,
3433
 
                run_hooks=run_hooks,
3434
 
                _override_hook_target=_override_hook_target)
3435
 
        finally:
3436
 
            if master_branch:
3437
 
                master_branch.unlock()
3438
 
 
3439
 
    def push(self, overwrite=False, stop_revision=None,
3440
 
             _override_hook_source_branch=None):
3441
 
        """See InterBranch.push.
3442
 
 
3443
 
        This is the basic concrete implementation of push()
3444
 
 
3445
 
        :param _override_hook_source_branch: If specified, run
3446
 
        the hooks passing this Branch as the source, rather than self.
3447
 
        This is for use of RemoteBranch, where push is delegated to the
3448
 
        underlying vfs-based Branch.
3449
 
        """
3450
 
        # TODO: Public option to disable running hooks - should be trivial but
3451
 
        # needs tests.
3452
 
        self.source.lock_read()
3453
 
        try:
3454
 
            return _run_with_write_locked_target(
3455
 
                self.target, self._push_with_bound_branches, overwrite,
3456
 
                stop_revision,
3457
 
                _override_hook_source_branch=_override_hook_source_branch)
3458
 
        finally:
3459
 
            self.source.unlock()
3460
 
 
3461
 
    def _push_with_bound_branches(self, overwrite, stop_revision,
3462
 
            _override_hook_source_branch=None):
3463
 
        """Push from source into target, and into target's master if any.
3464
 
        """
3465
 
        def _run_hooks():
3466
 
            if _override_hook_source_branch:
3467
 
                result.source_branch = _override_hook_source_branch
3468
 
            for hook in Branch.hooks['post_push']:
3469
 
                hook(result)
3470
 
 
3471
 
        bound_location = self.target.get_bound_location()
3472
 
        if bound_location and self.target.base != bound_location:
3473
 
            # there is a master branch.
3474
 
            #
3475
 
            # XXX: Why the second check?  Is it even supported for a branch to
3476
 
            # be bound to itself? -- mbp 20070507
3477
 
            master_branch = self.target.get_master_branch()
3478
 
            master_branch.lock_write()
3479
 
            try:
3480
 
                # push into the master from the source branch.
3481
 
                self.source._basic_push(master_branch, overwrite, stop_revision)
3482
 
                # and push into the target branch from the source. Note that we
3483
 
                # push from the source branch again, because it's considered the
3484
 
                # highest bandwidth repository.
3485
 
                result = self.source._basic_push(self.target, overwrite,
3486
 
                    stop_revision)
3487
 
                result.master_branch = master_branch
3488
 
                result.local_branch = self.target
3489
 
                _run_hooks()
3490
 
                return result
3491
 
            finally:
3492
 
                master_branch.unlock()
3493
 
        else:
3494
 
            # no master branch
3495
 
            result = self.source._basic_push(self.target, overwrite,
3496
 
                stop_revision)
3497
 
            # TODO: Why set master_branch and local_branch if there's no
3498
 
            # binding?  Maybe cleaner to just leave them unset? -- mbp
3499
 
            # 20070504
3500
 
            result.master_branch = self.target
3501
 
            result.local_branch = None
3502
 
            _run_hooks()
3503
 
            return result
3504
 
 
3505
 
    def _pull(self, overwrite=False, stop_revision=None,
3506
 
             possible_transports=None, _hook_master=None, run_hooks=True,
3507
 
             _override_hook_target=None, local=False):
3508
 
        """See Branch.pull.
3509
 
 
3510
 
        This function is the core worker, used by GenericInterBranch.pull to
3511
 
        avoid duplication when pulling source->master and source->local.
3512
 
 
3513
 
        :param _hook_master: Private parameter - set the branch to
3514
 
            be supplied as the master to pull hooks.
3515
 
        :param run_hooks: Private parameter - if false, this branch
3516
 
            is being called because it's the master of the primary branch,
3517
 
            so it should not run its hooks.
3518
 
        :param _override_hook_target: Private parameter - set the branch to be
3519
 
            supplied as the target_branch to pull hooks.
3520
 
        :param local: Only update the local branch, and not the bound branch.
3521
 
        """
3522
 
        # This type of branch can't be bound.
3523
 
        if local:
3524
 
            raise errors.LocalRequiresBoundBranch()
3525
 
        result = PullResult()
3526
 
        result.source_branch = self.source
3527
 
        if _override_hook_target is None:
3528
 
            result.target_branch = self.target
3529
 
        else:
3530
 
            result.target_branch = _override_hook_target
3531
 
        self.source.lock_read()
3532
 
        try:
3533
 
            # We assume that during 'pull' the target repository is closer than
3534
 
            # the source one.
3535
 
            self.source.update_references(self.target)
3536
 
            graph = self.target.repository.get_graph(self.source.repository)
3537
 
            # TODO: Branch formats should have a flag that indicates 
3538
 
            # that revno's are expensive, and pull() should honor that flag.
3539
 
            # -- JRV20090506
3540
 
            result.old_revno, result.old_revid = \
3541
 
                self.target.last_revision_info()
3542
 
            self.target.update_revisions(self.source, stop_revision,
3543
 
                overwrite=overwrite, graph=graph)
3544
 
            # TODO: The old revid should be specified when merging tags, 
3545
 
            # so a tags implementation that versions tags can only 
3546
 
            # pull in the most recent changes. -- JRV20090506
3547
 
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3548
 
                overwrite)
3549
 
            result.new_revno, result.new_revid = self.target.last_revision_info()
3550
 
            if _hook_master:
3551
 
                result.master_branch = _hook_master
3552
 
                result.local_branch = result.target_branch
3553
 
            else:
3554
 
                result.master_branch = result.target_branch
3555
 
                result.local_branch = None
3556
 
            if run_hooks:
3557
 
                for hook in Branch.hooks['post_pull']:
3558
 
                    hook(result)
3559
 
        finally:
3560
 
            self.source.unlock()
3561
 
        return result
 
3023
        self.source.lock_read()
 
3024
        try:
 
3025
            other_revno, other_last_revision = self.source.last_revision_info()
 
3026
            stop_revno = None # unknown
 
3027
            if stop_revision is None:
 
3028
                stop_revision = other_last_revision
 
3029
                if _mod_revision.is_null(stop_revision):
 
3030
                    # if there are no commits, we're done.
 
3031
                    return
 
3032
                stop_revno = other_revno
 
3033
 
 
3034
            # what's the current last revision, before we fetch [and change it
 
3035
            # possibly]
 
3036
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
3037
            # we fetch here so that we don't process data twice in the common
 
3038
            # case of having something to pull, and so that the check for
 
3039
            # already merged can operate on the just fetched graph, which will
 
3040
            # be cached in memory.
 
3041
            self.target.fetch(self.source, stop_revision)
 
3042
            # Check to see if one is an ancestor of the other
 
3043
            if not overwrite:
 
3044
                if graph is None:
 
3045
                    graph = self.target.repository.get_graph()
 
3046
                if self.target._check_if_descendant_or_diverged(
 
3047
                        stop_revision, last_rev, graph, self.source):
 
3048
                    # stop_revision is a descendant of last_rev, but we aren't
 
3049
                    # overwriting, so we're done.
 
3050
                    return
 
3051
            if stop_revno is None:
 
3052
                if graph is None:
 
3053
                    graph = self.target.repository.get_graph()
 
3054
                this_revno, this_last_revision = \
 
3055
                        self.target.last_revision_info()
 
3056
                stop_revno = graph.find_distance_to_null(stop_revision,
 
3057
                                [(other_last_revision, other_revno),
 
3058
                                 (this_last_revision, this_revno)])
 
3059
            self.target.set_last_revision_info(stop_revno, stop_revision)
 
3060
        finally:
 
3061
            self.source.unlock()
 
3062
 
 
3063
    @classmethod
 
3064
    def is_compatible(self, source, target):
 
3065
        # GenericBranch uses the public API, so always compatible
 
3066
        return True
3562
3067
 
3563
3068
 
3564
3069
InterBranch.register_optimiser(GenericInterBranch)