~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: INADA Naoki
  • Date: 2011-05-05 09:15:34 UTC
  • mto: (5830.3.3 i18n-msgfmt)
  • mto: This revision was merged to the branch mainline in revision 5873.
  • Revision ID: songofacandy@gmail.com-20110505091534-7sv835xpofwrmpt4
Add update-pot command to Makefile and tools/bzrgettext script that
extracts help text from bzr commands.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
 
1
# Copyright (C) 2005-2011 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
27
27
        config as _mod_config,
28
28
        debug,
29
29
        errors,
 
30
        fetch,
 
31
        graph as _mod_graph,
30
32
        lockdir,
31
33
        lockable_files,
 
34
        remote,
32
35
        repository,
33
36
        revision as _mod_revision,
34
37
        rio,
39
42
        urlutils,
40
43
        )
41
44
from bzrlib.config import BranchConfig, TransportConfig
42
 
from bzrlib.repofmt.pack_repo import RepositoryFormatKnitPack5RichRoot
43
45
from bzrlib.tag import (
44
46
    BasicTags,
45
47
    DisabledTags,
46
48
    )
47
49
""")
48
50
 
49
 
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
50
 
from bzrlib.hooks import HookPoint, Hooks
 
51
from bzrlib import (
 
52
    controldir,
 
53
    )
 
54
from bzrlib.decorators import (
 
55
    needs_read_lock,
 
56
    needs_write_lock,
 
57
    only_raises,
 
58
    )
 
59
from bzrlib.hooks import Hooks
51
60
from bzrlib.inter import InterObject
52
 
from bzrlib.lock import _RelockDebugMixin
 
61
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
53
62
from bzrlib import registry
54
63
from bzrlib.symbol_versioning import (
55
64
    deprecated_in,
63
72
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
64
73
 
65
74
 
66
 
# TODO: Maybe include checks for common corruption of newlines, etc?
67
 
 
68
 
# TODO: Some operations like log might retrieve the same revisions
69
 
# repeatedly to calculate deltas.  We could perhaps have a weakref
70
 
# cache in memory to make this faster.  In general anything can be
71
 
# cached in memory between lock and unlock operations. .. nb thats
72
 
# what the transaction identity map provides
73
 
 
74
 
 
75
 
######################################################################
76
 
# branch objects
77
 
 
78
 
class Branch(object):
 
75
class Branch(controldir.ControlComponent):
79
76
    """Branch holding a history of revisions.
80
77
 
81
 
    base
82
 
        Base directory/url of the branch.
83
 
 
84
 
    hooks: An instance of BranchHooks.
 
78
    :ivar base:
 
79
        Base directory/url of the branch; using control_url and
 
80
        control_transport is more standardized.
 
81
    :ivar hooks: An instance of BranchHooks.
 
82
    :ivar _master_branch_cache: cached result of get_master_branch, see
 
83
        _clear_cached_state.
85
84
    """
86
85
    # this is really an instance variable - FIXME move it there
87
86
    # - RBC 20060112
88
87
    base = None
89
88
 
 
89
    @property
 
90
    def control_transport(self):
 
91
        return self._transport
 
92
 
 
93
    @property
 
94
    def user_transport(self):
 
95
        return self.bzrdir.user_transport
 
96
 
90
97
    def __init__(self, *ignored, **ignored_too):
91
98
        self.tags = self._format.make_tags(self)
92
99
        self._revision_history_cache = None
93
100
        self._revision_id_to_revno_cache = None
94
101
        self._partial_revision_id_to_revno_cache = {}
95
102
        self._partial_revision_history_cache = []
 
103
        self._tags_bytes = None
96
104
        self._last_revision_info_cache = None
 
105
        self._master_branch_cache = None
97
106
        self._merge_sorted_revisions_cache = None
98
107
        self._open_hook()
99
108
        hooks = Branch.hooks['open']
105
114
 
106
115
    def _activate_fallback_location(self, url):
107
116
        """Activate the branch/repository from url as a fallback repository."""
 
117
        for existing_fallback_repo in self.repository._fallback_repositories:
 
118
            if existing_fallback_repo.user_url == url:
 
119
                # This fallback is already configured.  This probably only
 
120
                # happens because BzrDir.sprout is a horrible mess.  To avoid
 
121
                # confusing _unstack we don't add this a second time.
 
122
                mutter('duplicate activation of fallback %r on %r', url, self)
 
123
                return
108
124
        repo = self._get_fallback_repository(url)
109
125
        if repo.has_same_location(self.repository):
110
 
            raise errors.UnstackableLocationError(self.base, url)
 
126
            raise errors.UnstackableLocationError(self.user_url, url)
111
127
        self.repository.add_fallback_repository(repo)
112
128
 
113
129
    def break_lock(self):
167
183
        """
168
184
        control = bzrdir.BzrDir.open(base, _unsupported,
169
185
                                     possible_transports=possible_transports)
170
 
        return control.open_branch(_unsupported)
 
186
        return control.open_branch(unsupported=_unsupported)
171
187
 
172
188
    @staticmethod
173
 
    def open_from_transport(transport, _unsupported=False):
 
189
    def open_from_transport(transport, name=None, _unsupported=False):
174
190
        """Open the branch rooted at transport"""
175
191
        control = bzrdir.BzrDir.open_from_transport(transport, _unsupported)
176
 
        return control.open_branch(_unsupported)
 
192
        return control.open_branch(name=name, unsupported=_unsupported)
177
193
 
178
194
    @staticmethod
179
195
    def open_containing(url, possible_transports=None):
200
216
        return self.supports_tags() and self.tags.get_tag_dict()
201
217
 
202
218
    def get_config(self):
 
219
        """Get a bzrlib.config.BranchConfig for this Branch.
 
220
 
 
221
        This can then be used to get and set configuration options for the
 
222
        branch.
 
223
 
 
224
        :return: A bzrlib.config.BranchConfig.
 
225
        """
203
226
        return BranchConfig(self)
204
227
 
205
228
    def _get_config(self):
217
240
    def _get_fallback_repository(self, url):
218
241
        """Get the repository we fallback to at url."""
219
242
        url = urlutils.join(self.base, url)
220
 
        a_bzrdir = bzrdir.BzrDir.open(url,
 
243
        a_branch = Branch.open(url,
221
244
            possible_transports=[self.bzrdir.root_transport])
222
 
        return a_bzrdir.open_branch().repository
 
245
        return a_branch.repository
223
246
 
 
247
    @needs_read_lock
224
248
    def _get_tags_bytes(self):
225
249
        """Get the bytes of a serialised tags dict.
226
250
 
233
257
        :return: The bytes of the tags file.
234
258
        :seealso: Branch._set_tags_bytes.
235
259
        """
236
 
        return self._transport.get_bytes('tags')
 
260
        if self._tags_bytes is None:
 
261
            self._tags_bytes = self._transport.get_bytes('tags')
 
262
        return self._tags_bytes
237
263
 
238
264
    def _get_nick(self, local=False, possible_transports=None):
239
265
        config = self.get_config()
241
267
        if not local and not config.has_explicit_nickname():
242
268
            try:
243
269
                master = self.get_master_branch(possible_transports)
 
270
                if master and self.user_url == master.user_url:
 
271
                    raise errors.RecursiveBind(self.user_url)
244
272
                if master is not None:
245
273
                    # return the master branch value
246
274
                    return master.nick
 
275
            except errors.RecursiveBind, e:
 
276
                raise e
247
277
            except errors.BzrError, e:
248
278
                # Silently fall back to local implicit nick if the master is
249
279
                # unavailable
286
316
        new_history.reverse()
287
317
        return new_history
288
318
 
289
 
    def lock_write(self):
 
319
    def lock_write(self, token=None):
 
320
        """Lock the branch for write operations.
 
321
 
 
322
        :param token: A token to permit reacquiring a previously held and
 
323
            preserved lock.
 
324
        :return: A BranchWriteLockResult.
 
325
        """
290
326
        raise NotImplementedError(self.lock_write)
291
327
 
292
328
    def lock_read(self):
 
329
        """Lock the branch for read operations.
 
330
 
 
331
        :return: A bzrlib.lock.LogicalLockResult.
 
332
        """
293
333
        raise NotImplementedError(self.lock_read)
294
334
 
295
335
    def unlock(self):
420
460
            * 'include' - the stop revision is the last item in the result
421
461
            * 'with-merges' - include the stop revision and all of its
422
462
              merged revisions in the result
 
463
            * 'with-merges-without-common-ancestry' - filter out revisions 
 
464
              that are in both ancestries
423
465
        :param direction: either 'reverse' or 'forward':
424
466
            * reverse means return the start_revision_id first, i.e.
425
467
              start at the most recent revision and go backwards in history
447
489
        # start_revision_id.
448
490
        if self._merge_sorted_revisions_cache is None:
449
491
            last_revision = self.last_revision()
450
 
            last_key = (last_revision,)
451
 
            known_graph = self.repository.revisions.get_known_graph_ancestry(
452
 
                [last_key])
 
492
            known_graph = self.repository.get_known_graph_ancestry(
 
493
                [last_revision])
453
494
            self._merge_sorted_revisions_cache = known_graph.merge_sort(
454
 
                last_key)
 
495
                last_revision)
455
496
        filtered = self._filter_merge_sorted_revisions(
456
497
            self._merge_sorted_revisions_cache, start_revision_id,
457
498
            stop_revision_id, stop_rule)
 
499
        # Make sure we don't return revisions that are not part of the
 
500
        # start_revision_id ancestry.
 
501
        filtered = self._filter_start_non_ancestors(filtered)
458
502
        if direction == 'reverse':
459
503
            return filtered
460
504
        if direction == 'forward':
497
541
                       node.end_of_merge)
498
542
                if rev_id == stop_revision_id:
499
543
                    return
 
544
        elif stop_rule == 'with-merges-without-common-ancestry':
 
545
            # We want to exclude all revisions that are already part of the
 
546
            # stop_revision_id ancestry.
 
547
            graph = self.repository.get_graph()
 
548
            ancestors = graph.find_unique_ancestors(start_revision_id,
 
549
                                                    [stop_revision_id])
 
550
            for node in rev_iter:
 
551
                rev_id = node.key[-1]
 
552
                if rev_id not in ancestors:
 
553
                    continue
 
554
                yield (rev_id, node.merge_depth, node.revno,
 
555
                       node.end_of_merge)
500
556
        elif stop_rule == 'with-merges':
501
557
            stop_rev = self.repository.get_revision(stop_revision_id)
502
558
            if stop_rev.parent_ids:
525
581
        else:
526
582
            raise ValueError('invalid stop_rule %r' % stop_rule)
527
583
 
 
584
    def _filter_start_non_ancestors(self, rev_iter):
 
585
        # If we started from a dotted revno, we want to consider it as a tip
 
586
        # and don't want to yield revisions that are not part of its
 
587
        # ancestry. Given the order guaranteed by the merge sort, we will see
 
588
        # uninteresting descendants of the first parent of our tip before the
 
589
        # tip itself.
 
590
        first = rev_iter.next()
 
591
        (rev_id, merge_depth, revno, end_of_merge) = first
 
592
        yield first
 
593
        if not merge_depth:
 
594
            # We start at a mainline revision so by definition, all others
 
595
            # revisions in rev_iter are ancestors
 
596
            for node in rev_iter:
 
597
                yield node
 
598
 
 
599
        clean = False
 
600
        whitelist = set()
 
601
        pmap = self.repository.get_parent_map([rev_id])
 
602
        parents = pmap.get(rev_id, [])
 
603
        if parents:
 
604
            whitelist.update(parents)
 
605
        else:
 
606
            # If there is no parents, there is nothing of interest left
 
607
 
 
608
            # FIXME: It's hard to test this scenario here as this code is never
 
609
            # called in that case. -- vila 20100322
 
610
            return
 
611
 
 
612
        for (rev_id, merge_depth, revno, end_of_merge) in rev_iter:
 
613
            if not clean:
 
614
                if rev_id in whitelist:
 
615
                    pmap = self.repository.get_parent_map([rev_id])
 
616
                    parents = pmap.get(rev_id, [])
 
617
                    whitelist.remove(rev_id)
 
618
                    whitelist.update(parents)
 
619
                    if merge_depth == 0:
 
620
                        # We've reached the mainline, there is nothing left to
 
621
                        # filter
 
622
                        clean = True
 
623
                else:
 
624
                    # A revision that is not part of the ancestry of our
 
625
                    # starting revision.
 
626
                    continue
 
627
            yield (rev_id, merge_depth, revno, end_of_merge)
 
628
 
528
629
    def leave_lock_in_place(self):
529
630
        """Tell this branch object not to release the physical lock when this
530
631
        object is unlocked.
547
648
        :param other: The branch to bind to
548
649
        :type other: Branch
549
650
        """
550
 
        raise errors.UpgradeRequired(self.base)
 
651
        raise errors.UpgradeRequired(self.user_url)
551
652
 
552
653
    def set_append_revisions_only(self, enabled):
553
654
        if not self._format.supports_set_append_revisions_only():
554
 
            raise errors.UpgradeRequired(self.base)
 
655
            raise errors.UpgradeRequired(self.user_url)
555
656
        if enabled:
556
657
            value = 'True'
557
658
        else:
568
669
        raise errors.UnsupportedOperation(self.get_reference_info, self)
569
670
 
570
671
    @needs_write_lock
571
 
    def fetch(self, from_branch, last_revision=None, pb=None):
 
672
    def fetch(self, from_branch, last_revision=None):
572
673
        """Copy revisions from from_branch into this branch.
573
674
 
574
675
        :param from_branch: Where to copy from.
575
676
        :param last_revision: What revision to stop at (None for at the end
576
677
                              of the branch.
577
 
        :param pb: An optional progress bar to use.
578
678
        :return: None
579
679
        """
580
 
        if self.base == from_branch.base:
581
 
            return (0, [])
582
 
        if pb is not None:
583
 
            symbol_versioning.warn(
584
 
                symbol_versioning.deprecated_in((1, 14, 0))
585
 
                % "pb parameter to fetch()")
586
 
        from_branch.lock_read()
587
 
        try:
588
 
            if last_revision is None:
589
 
                last_revision = from_branch.last_revision()
590
 
                last_revision = _mod_revision.ensure_null(last_revision)
591
 
            return self.repository.fetch(from_branch.repository,
592
 
                                         revision_id=last_revision,
593
 
                                         pb=pb)
594
 
        finally:
595
 
            from_branch.unlock()
 
680
        return InterBranch.get(from_branch, self).fetch(last_revision)
596
681
 
597
682
    def get_bound_location(self):
598
683
        """Return the URL of the branch we are bound to.
605
690
    def get_old_bound_location(self):
606
691
        """Return the URL of the branch we used to be bound to
607
692
        """
608
 
        raise errors.UpgradeRequired(self.base)
 
693
        raise errors.UpgradeRequired(self.user_url)
609
694
 
610
695
    def get_commit_builder(self, parents, config=None, timestamp=None,
611
696
                           timezone=None, committer=None, revprops=None,
612
 
                           revision_id=None):
 
697
                           revision_id=None, lossy=False):
613
698
        """Obtain a CommitBuilder for this branch.
614
699
 
615
700
        :param parents: Revision ids of the parents of the new revision.
619
704
        :param committer: Optional committer to set for commit.
620
705
        :param revprops: Optional dictionary of revision properties.
621
706
        :param revision_id: Optional revision id.
 
707
        :param lossy: Whether to discard data that can not be natively
 
708
            represented, when pushing to a foreign VCS 
622
709
        """
623
710
 
624
711
        if config is None:
625
712
            config = self.get_config()
626
713
 
627
714
        return self.repository.get_commit_builder(self, parents, config,
628
 
            timestamp, timezone, committer, revprops, revision_id)
 
715
            timestamp, timezone, committer, revprops, revision_id,
 
716
            lossy)
629
717
 
630
718
    def get_master_branch(self, possible_transports=None):
631
719
        """Return the branch we are bound to.
689
777
            stacking.
690
778
        """
691
779
        if not self._format.supports_stacking():
692
 
            raise errors.UnstackableBranchFormat(self._format, self.base)
 
780
            raise errors.UnstackableBranchFormat(self._format, self.user_url)
693
781
        # XXX: Changing from one fallback repository to another does not check
694
782
        # that all the data you need is present in the new fallback.
695
783
        # Possibly it should.
709
797
 
710
798
    def _unstack(self):
711
799
        """Change a branch to be unstacked, copying data as needed.
712
 
        
 
800
 
713
801
        Don't call this directly, use set_stacked_on_url(None).
714
802
        """
715
803
        pb = ui.ui_factory.nested_progress_bar()
724
812
            old_repository = self.repository
725
813
            if len(old_repository._fallback_repositories) != 1:
726
814
                raise AssertionError("can't cope with fallback repositories "
727
 
                    "of %r" % (self.repository,))
728
 
            # unlock it, including unlocking the fallback
 
815
                    "of %r (fallbacks: %r)" % (old_repository,
 
816
                        old_repository._fallback_repositories))
 
817
            # Open the new repository object.
 
818
            # Repositories don't offer an interface to remove fallback
 
819
            # repositories today; take the conceptually simpler option and just
 
820
            # reopen it.  We reopen it starting from the URL so that we
 
821
            # get a separate connection for RemoteRepositories and can
 
822
            # stream from one of them to the other.  This does mean doing
 
823
            # separate SSH connection setup, but unstacking is not a
 
824
            # common operation so it's tolerable.
 
825
            new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
 
826
            new_repository = new_bzrdir.find_repository()
 
827
            if new_repository._fallback_repositories:
 
828
                raise AssertionError("didn't expect %r to have "
 
829
                    "fallback_repositories"
 
830
                    % (self.repository,))
 
831
            # Replace self.repository with the new repository.
 
832
            # Do our best to transfer the lock state (i.e. lock-tokens and
 
833
            # lock count) of self.repository to the new repository.
 
834
            lock_token = old_repository.lock_write().repository_token
 
835
            self.repository = new_repository
 
836
            if isinstance(self, remote.RemoteBranch):
 
837
                # Remote branches can have a second reference to the old
 
838
                # repository that need to be replaced.
 
839
                if self._real_branch is not None:
 
840
                    self._real_branch.repository = new_repository
 
841
            self.repository.lock_write(token=lock_token)
 
842
            if lock_token is not None:
 
843
                old_repository.leave_lock_in_place()
729
844
            old_repository.unlock()
 
845
            if lock_token is not None:
 
846
                # XXX: self.repository.leave_lock_in_place() before this
 
847
                # function will not be preserved.  Fortunately that doesn't
 
848
                # affect the current default format (2a), and would be a
 
849
                # corner-case anyway.
 
850
                #  - Andrew Bennetts, 2010/06/30
 
851
                self.repository.dont_leave_lock_in_place()
 
852
            old_lock_count = 0
 
853
            while True:
 
854
                try:
 
855
                    old_repository.unlock()
 
856
                except errors.LockNotHeld:
 
857
                    break
 
858
                old_lock_count += 1
 
859
            if old_lock_count == 0:
 
860
                raise AssertionError(
 
861
                    'old_repository should have been locked at least once.')
 
862
            for i in range(old_lock_count-1):
 
863
                self.repository.lock_write()
 
864
            # Fetch from the old repository into the new.
730
865
            old_repository.lock_read()
731
866
            try:
732
 
                # Repositories don't offer an interface to remove fallback
733
 
                # repositories today; take the conceptually simpler option and just
734
 
                # reopen it.  We reopen it starting from the URL so that we
735
 
                # get a separate connection for RemoteRepositories and can
736
 
                # stream from one of them to the other.  This does mean doing
737
 
                # separate SSH connection setup, but unstacking is not a
738
 
                # common operation so it's tolerable.
739
 
                new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
740
 
                new_repository = new_bzrdir.find_repository()
741
 
                self.repository = new_repository
742
 
                if self.repository._fallback_repositories:
743
 
                    raise AssertionError("didn't expect %r to have "
744
 
                        "fallback_repositories"
745
 
                        % (self.repository,))
746
 
                # this is not paired with an unlock because it's just restoring
747
 
                # the previous state; the lock's released when set_stacked_on_url
748
 
                # returns
749
 
                self.repository.lock_write()
750
867
                # XXX: If you unstack a branch while it has a working tree
751
868
                # with a pending merge, the pending-merged revisions will no
752
869
                # longer be present.  You can (probably) revert and remerge.
753
 
                #
754
 
                # XXX: This only fetches up to the tip of the repository; it
755
 
                # doesn't bring across any tags.  That's fairly consistent
756
 
                # with how branch works, but perhaps not ideal.
757
 
                self.repository.fetch(old_repository,
758
 
                    revision_id=self.last_revision(),
759
 
                    find_ghosts=True)
 
870
                try:
 
871
                    tags_to_fetch = set(self.tags.get_reverse_tag_dict())
 
872
                except errors.TagsNotSupported:
 
873
                    tags_to_fetch = set()
 
874
                fetch_spec = _mod_graph.NotInOtherForRevs(self.repository,
 
875
                    old_repository, required_ids=[self.last_revision()],
 
876
                    if_present_ids=tags_to_fetch, find_ghosts=True).execute()
 
877
                self.repository.fetch(old_repository, fetch_spec=fetch_spec)
760
878
            finally:
761
879
                old_repository.unlock()
762
880
        finally:
767
885
 
768
886
        :seealso: Branch._get_tags_bytes.
769
887
        """
770
 
        return _run_with_write_locked_target(self, self._transport.put_bytes,
771
 
            'tags', bytes)
 
888
        return _run_with_write_locked_target(self, self._set_tags_bytes_locked,
 
889
                bytes)
 
890
 
 
891
    def _set_tags_bytes_locked(self, bytes):
 
892
        self._tags_bytes = bytes
 
893
        return self._transport.put_bytes('tags', bytes)
772
894
 
773
895
    def _cache_revision_history(self, rev_history):
774
896
        """Set the cached revision history to rev_history.
801
923
        self._revision_history_cache = None
802
924
        self._revision_id_to_revno_cache = None
803
925
        self._last_revision_info_cache = None
 
926
        self._master_branch_cache = None
804
927
        self._merge_sorted_revisions_cache = None
805
928
        self._partial_revision_history_cache = []
806
929
        self._partial_revision_id_to_revno_cache = {}
 
930
        self._tags_bytes = None
807
931
 
808
932
    def _gen_revision_history(self):
809
933
        """Return sequence of revision hashes on to this branch.
846
970
 
847
971
    def unbind(self):
848
972
        """Older format branches cannot bind or unbind."""
849
 
        raise errors.UpgradeRequired(self.base)
 
973
        raise errors.UpgradeRequired(self.user_url)
850
974
 
851
975
    def last_revision(self):
852
976
        """Return last revision id, or NULL_REVISION."""
870
994
        else:
871
995
            return (0, _mod_revision.NULL_REVISION)
872
996
 
873
 
    @deprecated_method(deprecated_in((1, 6, 0)))
874
 
    def missing_revisions(self, other, stop_revision=None):
875
 
        """Return a list of new revisions that would perfectly fit.
876
 
 
877
 
        If self and other have not diverged, return a list of the revisions
878
 
        present in other, but missing from self.
879
 
        """
880
 
        self_history = self.revision_history()
881
 
        self_len = len(self_history)
882
 
        other_history = other.revision_history()
883
 
        other_len = len(other_history)
884
 
        common_index = min(self_len, other_len) -1
885
 
        if common_index >= 0 and \
886
 
            self_history[common_index] != other_history[common_index]:
887
 
            raise errors.DivergedBranches(self, other)
888
 
 
889
 
        if stop_revision is None:
890
 
            stop_revision = other_len
891
 
        else:
892
 
            if stop_revision > other_len:
893
 
                raise errors.NoSuchRevision(self, stop_revision)
894
 
        return other_history[self_len:stop_revision]
895
 
 
896
 
    @needs_write_lock
897
 
    def update_revisions(self, other, stop_revision=None, overwrite=False,
898
 
                         graph=None):
899
 
        """Pull in new perfect-fit revisions.
900
 
 
901
 
        :param other: Another Branch to pull from
902
 
        :param stop_revision: Updated until the given revision
903
 
        :param overwrite: Always set the branch pointer, rather than checking
904
 
            to see if it is a proper descendant.
905
 
        :param graph: A Graph object that can be used to query history
906
 
            information. This can be None.
907
 
        :return: None
908
 
        """
909
 
        return InterBranch.get(other, self).update_revisions(stop_revision,
910
 
            overwrite, graph)
911
 
 
 
997
    @deprecated_method(deprecated_in((2, 4, 0)))
912
998
    def import_last_revision_info(self, source_repo, revno, revid):
913
999
        """Set the last revision info, importing from another repo if necessary.
914
1000
 
915
 
        This is used by the bound branch code to upload a revision to
916
 
        the master branch first before updating the tip of the local branch.
917
 
 
918
1001
        :param source_repo: Source repository to optionally fetch from
919
1002
        :param revno: Revision number of the new tip
920
1003
        :param revid: Revision id of the new tip
923
1006
            self.repository.fetch(source_repo, revision_id=revid)
924
1007
        self.set_last_revision_info(revno, revid)
925
1008
 
 
1009
    def import_last_revision_info_and_tags(self, source, revno, revid,
 
1010
                                           lossy=False):
 
1011
        """Set the last revision info, importing from another repo if necessary.
 
1012
 
 
1013
        This is used by the bound branch code to upload a revision to
 
1014
        the master branch first before updating the tip of the local branch.
 
1015
        Revisions referenced by source's tags are also transferred.
 
1016
 
 
1017
        :param source: Source branch to optionally fetch from
 
1018
        :param revno: Revision number of the new tip
 
1019
        :param revid: Revision id of the new tip
 
1020
        :param lossy: Whether to discard metadata that can not be
 
1021
            natively represented
 
1022
        :return: Tuple with the new revision number and revision id
 
1023
            (should only be different from the arguments when lossy=True)
 
1024
        """
 
1025
        if not self.repository.has_same_location(source.repository):
 
1026
            self.fetch(source, revid)
 
1027
        self.set_last_revision_info(revno, revid)
 
1028
        return (revno, revid)
 
1029
 
926
1030
    def revision_id_to_revno(self, revision_id):
927
1031
        """Given a revision id, return its revno"""
928
1032
        if _mod_revision.is_null(revision_id):
948
1052
            self._extend_partial_history(distance_from_last)
949
1053
        return self._partial_revision_history_cache[distance_from_last]
950
1054
 
951
 
    @needs_write_lock
952
1055
    def pull(self, source, overwrite=False, stop_revision=None,
953
1056
             possible_transports=None, *args, **kwargs):
954
1057
        """Mirror source into this branch.
1012
1115
        try:
1013
1116
            return urlutils.join(self.base[:-1], parent)
1014
1117
        except errors.InvalidURLJoin, e:
1015
 
            raise errors.InaccessibleParent(parent, self.base)
 
1118
            raise errors.InaccessibleParent(parent, self.user_url)
1016
1119
 
1017
1120
    def _get_parent_location(self):
1018
1121
        raise NotImplementedError(self._get_parent_location)
1150
1253
        return result
1151
1254
 
1152
1255
    @needs_read_lock
1153
 
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None):
 
1256
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None,
 
1257
            repository=None):
1154
1258
        """Create a new line of development from the branch, into to_bzrdir.
1155
1259
 
1156
1260
        to_bzrdir controls the branch format.
1161
1265
        if (repository_policy is not None and
1162
1266
            repository_policy.requires_stacking()):
1163
1267
            to_bzrdir._format.require_stacking(_skip_repo=True)
1164
 
        result = to_bzrdir.create_branch()
 
1268
        result = to_bzrdir.create_branch(repository=repository)
1165
1269
        result.lock_write()
1166
1270
        try:
1167
1271
            if repository_policy is not None:
1197
1301
                revno = 1
1198
1302
        destination.set_last_revision_info(revno, revision_id)
1199
1303
 
1200
 
    @needs_read_lock
1201
1304
    def copy_content_into(self, destination, revision_id=None):
1202
1305
        """Copy the content of self into destination.
1203
1306
 
1204
1307
        revision_id: if not None, the revision history in the new branch will
1205
1308
                     be truncated to end with revision_id.
1206
1309
        """
1207
 
        self.update_references(destination)
1208
 
        self._synchronize_history(destination, revision_id)
1209
 
        try:
1210
 
            parent = self.get_parent()
1211
 
        except errors.InaccessibleParent, e:
1212
 
            mutter('parent was not accessible to copy: %s', e)
1213
 
        else:
1214
 
            if parent:
1215
 
                destination.set_parent(parent)
1216
 
        if self._push_should_merge_tags():
1217
 
            self.tags.merge_to(destination.tags)
 
1310
        return InterBranch.get(self, destination).copy_content_into(
 
1311
            revision_id=revision_id)
1218
1312
 
1219
1313
    def update_references(self, target):
1220
1314
        if not getattr(self._format, 'supports_reference_locations', False):
1265
1359
        """Return the most suitable metadir for a checkout of this branch.
1266
1360
        Weaves are used if this branch's repository uses weaves.
1267
1361
        """
1268
 
        if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
1269
 
            from bzrlib.repofmt import weaverepo
1270
 
            format = bzrdir.BzrDirMetaFormat1()
1271
 
            format.repository_format = weaverepo.RepositoryFormat7()
1272
 
        else:
1273
 
            format = self.repository.bzrdir.checkout_metadir()
1274
 
            format.set_branch_format(self._format)
 
1362
        format = self.repository.bzrdir.checkout_metadir()
 
1363
        format.set_branch_format(self._format)
1275
1364
        return format
1276
1365
 
1277
1366
    def create_clone_on_transport(self, to_transport, revision_id=None,
1278
 
        stacked_on=None, create_prefix=False, use_existing_dir=False):
 
1367
        stacked_on=None, create_prefix=False, use_existing_dir=False,
 
1368
        no_tree=None):
1279
1369
        """Create a clone of this branch and its bzrdir.
1280
1370
 
1281
1371
        :param to_transport: The transport to clone onto.
1288
1378
        """
1289
1379
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1290
1380
        # clone call. Or something. 20090224 RBC/spiv.
 
1381
        # XXX: Should this perhaps clone colocated branches as well, 
 
1382
        # rather than just the default branch? 20100319 JRV
1291
1383
        if revision_id is None:
1292
1384
            revision_id = self.last_revision()
1293
1385
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1294
1386
            revision_id=revision_id, stacked_on=stacked_on,
1295
 
            create_prefix=create_prefix, use_existing_dir=use_existing_dir)
 
1387
            create_prefix=create_prefix, use_existing_dir=use_existing_dir,
 
1388
            no_tree=no_tree)
1296
1389
        return dir_to.open_branch()
1297
1390
 
1298
1391
    def create_checkout(self, to_location, revision_id=None,
1317
1410
        if lightweight:
1318
1411
            format = self._get_checkout_format()
1319
1412
            checkout = format.initialize_on_transport(t)
1320
 
            from_branch = BranchReferenceFormat().initialize(checkout, self)
 
1413
            from_branch = BranchReferenceFormat().initialize(checkout, 
 
1414
                target_branch=self)
1321
1415
        else:
1322
1416
            format = self._get_checkout_format()
1323
1417
            checkout_branch = bzrdir.BzrDir.create_branch_convenience(
1365
1459
    def supports_tags(self):
1366
1460
        return self._format.supports_tags()
1367
1461
 
 
1462
    def automatic_tag_name(self, revision_id):
 
1463
        """Try to automatically find the tag name for a revision.
 
1464
 
 
1465
        :param revision_id: Revision id of the revision.
 
1466
        :return: A tag name or None if no tag name could be determined.
 
1467
        """
 
1468
        for hook in Branch.hooks['automatic_tag_name']:
 
1469
            ret = hook(self, revision_id)
 
1470
            if ret is not None:
 
1471
                return ret
 
1472
        return None
 
1473
 
1368
1474
    def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
1369
1475
                                         other_branch):
1370
1476
        """Ensure that revision_b is a descendant of revision_a.
1400
1506
        else:
1401
1507
            raise AssertionError("invalid heads: %r" % (heads,))
1402
1508
 
1403
 
 
1404
 
class BranchFormat(object):
 
1509
    def heads_to_fetch(self):
 
1510
        """Return the heads that must and that should be fetched to copy this
 
1511
        branch into another repo.
 
1512
 
 
1513
        :returns: a 2-tuple of (must_fetch, if_present_fetch).  must_fetch is a
 
1514
            set of heads that must be fetched.  if_present_fetch is a set of
 
1515
            heads that must be fetched if present, but no error is necessary if
 
1516
            they are not present.
 
1517
        """
 
1518
        # For bzr native formats must_fetch is just the tip, and if_present_fetch
 
1519
        # are the tags.
 
1520
        must_fetch = set([self.last_revision()])
 
1521
        try:
 
1522
            if_present_fetch = set(self.tags.get_reverse_tag_dict())
 
1523
        except errors.TagsNotSupported:
 
1524
            if_present_fetch = set()
 
1525
        must_fetch.discard(_mod_revision.NULL_REVISION)
 
1526
        if_present_fetch.discard(_mod_revision.NULL_REVISION)
 
1527
        return must_fetch, if_present_fetch
 
1528
 
 
1529
 
 
1530
class BranchFormat(controldir.ControlComponentFormat):
1405
1531
    """An encapsulation of the initialization and open routines for a format.
1406
1532
 
1407
1533
    Formats provide three things:
1410
1536
     * an open routine.
1411
1537
 
1412
1538
    Formats are placed in an dict by their format string for reference
1413
 
    during branch opening. Its not required that these be instances, they
 
1539
    during branch opening. It's not required that these be instances, they
1414
1540
    can be classes themselves with class methods - it simply depends on
1415
1541
    whether state is needed for a given format or not.
1416
1542
 
1419
1545
    object will be created every time regardless.
1420
1546
    """
1421
1547
 
1422
 
    _default_format = None
1423
 
    """The default format used for new branches."""
1424
 
 
1425
 
    _formats = {}
1426
 
    """The known formats."""
1427
 
 
1428
1548
    can_set_append_revisions_only = True
1429
1549
 
1430
1550
    def __eq__(self, other):
1434
1554
        return not (self == other)
1435
1555
 
1436
1556
    @classmethod
1437
 
    def find_format(klass, a_bzrdir):
 
1557
    def find_format(klass, a_bzrdir, name=None):
1438
1558
        """Return the format for the branch object in a_bzrdir."""
1439
1559
        try:
1440
 
            transport = a_bzrdir.get_branch_transport(None)
 
1560
            transport = a_bzrdir.get_branch_transport(None, name=name)
1441
1561
            format_string = transport.get_bytes("format")
1442
 
            return klass._formats[format_string]
 
1562
            return format_registry.get(format_string)
1443
1563
        except errors.NoSuchFile:
1444
1564
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1445
1565
        except KeyError:
1446
1566
            raise errors.UnknownFormatError(format=format_string, kind='branch')
1447
1567
 
1448
1568
    @classmethod
 
1569
    @deprecated_method(deprecated_in((2, 4, 0)))
1449
1570
    def get_default_format(klass):
1450
1571
        """Return the current default format."""
1451
 
        return klass._default_format
1452
 
 
1453
 
    def get_reference(self, a_bzrdir):
 
1572
        return format_registry.get_default()
 
1573
 
 
1574
    @classmethod
 
1575
    @deprecated_method(deprecated_in((2, 4, 0)))
 
1576
    def get_formats(klass):
 
1577
        """Get all the known formats.
 
1578
 
 
1579
        Warning: This triggers a load of all lazy registered formats: do not
 
1580
        use except when that is desireed.
 
1581
        """
 
1582
        return format_registry._get_all()
 
1583
 
 
1584
    def get_reference(self, a_bzrdir, name=None):
1454
1585
        """Get the target reference of the branch in a_bzrdir.
1455
1586
 
1456
1587
        format probing must have been completed before calling
1458
1589
        in a_bzrdir is correct.
1459
1590
 
1460
1591
        :param a_bzrdir: The bzrdir to get the branch data from.
 
1592
        :param name: Name of the colocated branch to fetch
1461
1593
        :return: None if the branch is not a reference branch.
1462
1594
        """
1463
1595
        return None
1464
1596
 
1465
1597
    @classmethod
1466
 
    def set_reference(self, a_bzrdir, to_branch):
 
1598
    def set_reference(self, a_bzrdir, name, to_branch):
1467
1599
        """Set the target reference of the branch in a_bzrdir.
1468
1600
 
1469
1601
        format probing must have been completed before calling
1471
1603
        in a_bzrdir is correct.
1472
1604
 
1473
1605
        :param a_bzrdir: The bzrdir to set the branch reference for.
 
1606
        :param name: Name of colocated branch to set, None for default
1474
1607
        :param to_branch: branch that the checkout is to reference
1475
1608
        """
1476
1609
        raise NotImplementedError(self.set_reference)
1483
1616
        """Return the short format description for this format."""
1484
1617
        raise NotImplementedError(self.get_format_description)
1485
1618
 
1486
 
    def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
1487
 
                           set_format=True):
1488
 
        """Initialize a branch in a bzrdir, with specified files
 
1619
    def _run_post_branch_init_hooks(self, a_bzrdir, name, branch):
 
1620
        hooks = Branch.hooks['post_branch_init']
 
1621
        if not hooks:
 
1622
            return
 
1623
        params = BranchInitHookParams(self, a_bzrdir, name, branch)
 
1624
        for hook in hooks:
 
1625
            hook(params)
1489
1626
 
1490
 
        :param a_bzrdir: The bzrdir to initialize the branch in
1491
 
        :param utf8_files: The files to create as a list of
1492
 
            (filename, content) tuples
1493
 
        :param set_format: If True, set the format with
1494
 
            self.get_format_string.  (BzrBranch4 has its format set
1495
 
            elsewhere)
1496
 
        :return: a branch in this format
 
1627
    def initialize(self, a_bzrdir, name=None, repository=None):
 
1628
        """Create a branch of this format in a_bzrdir.
 
1629
        
 
1630
        :param name: Name of the colocated branch to create.
1497
1631
        """
1498
 
        mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
1499
 
        branch_transport = a_bzrdir.get_branch_transport(self)
1500
 
        lock_map = {
1501
 
            'metadir': ('lock', lockdir.LockDir),
1502
 
            'branch4': ('branch-lock', lockable_files.TransportLock),
1503
 
        }
1504
 
        lock_name, lock_class = lock_map[lock_type]
1505
 
        control_files = lockable_files.LockableFiles(branch_transport,
1506
 
            lock_name, lock_class)
1507
 
        control_files.create_lock()
1508
 
        try:
1509
 
            control_files.lock_write()
1510
 
        except errors.LockContention:
1511
 
            if lock_type != 'branch4':
1512
 
                raise
1513
 
            lock_taken = False
1514
 
        else:
1515
 
            lock_taken = True
1516
 
        if set_format:
1517
 
            utf8_files += [('format', self.get_format_string())]
1518
 
        try:
1519
 
            for (filename, content) in utf8_files:
1520
 
                branch_transport.put_bytes(
1521
 
                    filename, content,
1522
 
                    mode=a_bzrdir._get_file_mode())
1523
 
        finally:
1524
 
            if lock_taken:
1525
 
                control_files.unlock()
1526
 
        return self.open(a_bzrdir, _found=True)
1527
 
 
1528
 
    def initialize(self, a_bzrdir):
1529
 
        """Create a branch of this format in a_bzrdir."""
1530
1632
        raise NotImplementedError(self.initialize)
1531
1633
 
1532
1634
    def is_supported(self):
1562
1664
        """
1563
1665
        raise NotImplementedError(self.network_name)
1564
1666
 
1565
 
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
 
1667
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
 
1668
            found_repository=None):
1566
1669
        """Return the branch object for a_bzrdir
1567
1670
 
1568
1671
        :param a_bzrdir: A BzrDir that contains a branch.
 
1672
        :param name: Name of colocated branch to open
1569
1673
        :param _found: a private parameter, do not use it. It is used to
1570
1674
            indicate if format probing has already be done.
1571
1675
        :param ignore_fallbacks: when set, no fallback branches will be opened
1574
1678
        raise NotImplementedError(self.open)
1575
1679
 
1576
1680
    @classmethod
 
1681
    @deprecated_method(deprecated_in((2, 4, 0)))
1577
1682
    def register_format(klass, format):
1578
 
        """Register a metadir format."""
1579
 
        klass._formats[format.get_format_string()] = format
1580
 
        # Metadir formats have a network name of their format string, and get
1581
 
        # registered as class factories.
1582
 
        network_format_registry.register(format.get_format_string(), format.__class__)
 
1683
        """Register a metadir format.
 
1684
 
 
1685
        See MetaDirBranchFormatFactory for the ability to register a format
 
1686
        without loading the code the format needs until it is actually used.
 
1687
        """
 
1688
        format_registry.register(format)
1583
1689
 
1584
1690
    @classmethod
 
1691
    @deprecated_method(deprecated_in((2, 4, 0)))
1585
1692
    def set_default_format(klass, format):
1586
 
        klass._default_format = format
 
1693
        format_registry.set_default(format)
1587
1694
 
1588
1695
    def supports_set_append_revisions_only(self):
1589
1696
        """True if this format supports set_append_revisions_only."""
1593
1700
        """True if this format records a stacked-on branch."""
1594
1701
        return False
1595
1702
 
 
1703
    def supports_leaving_lock(self):
 
1704
        """True if this format supports leaving locks in place."""
 
1705
        return False # by default
 
1706
 
1596
1707
    @classmethod
 
1708
    @deprecated_method(deprecated_in((2, 4, 0)))
1597
1709
    def unregister_format(klass, format):
1598
 
        del klass._formats[format.get_format_string()]
 
1710
        format_registry.remove(format)
1599
1711
 
1600
1712
    def __str__(self):
1601
1713
        return self.get_format_description().rstrip()
1605
1717
        return False  # by default
1606
1718
 
1607
1719
 
 
1720
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
 
1721
    """A factory for a BranchFormat object, permitting simple lazy registration.
 
1722
    
 
1723
    While none of the built in BranchFormats are lazy registered yet,
 
1724
    bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
 
1725
    use it, and the bzr-loom plugin uses it as well (see
 
1726
    bzrlib.plugins.loom.formats).
 
1727
    """
 
1728
 
 
1729
    def __init__(self, format_string, module_name, member_name):
 
1730
        """Create a MetaDirBranchFormatFactory.
 
1731
 
 
1732
        :param format_string: The format string the format has.
 
1733
        :param module_name: Module to load the format class from.
 
1734
        :param member_name: Attribute name within the module for the format class.
 
1735
        """
 
1736
        registry._LazyObjectGetter.__init__(self, module_name, member_name)
 
1737
        self._format_string = format_string
 
1738
        
 
1739
    def get_format_string(self):
 
1740
        """See BranchFormat.get_format_string."""
 
1741
        return self._format_string
 
1742
 
 
1743
    def __call__(self):
 
1744
        """Used for network_format_registry support."""
 
1745
        return self.get_obj()()
 
1746
 
 
1747
 
1608
1748
class BranchHooks(Hooks):
1609
1749
    """A dictionary mapping hook name to a list of callables for branch hooks.
1610
1750
 
1618
1758
        These are all empty initially, because by default nothing should get
1619
1759
        notified.
1620
1760
        """
1621
 
        Hooks.__init__(self)
1622
 
        self.create_hook(HookPoint('set_rh',
 
1761
        Hooks.__init__(self, "bzrlib.branch", "Branch.hooks")
 
1762
        self.add_hook('set_rh',
1623
1763
            "Invoked whenever the revision history has been set via "
1624
1764
            "set_revision_history. The api signature is (branch, "
1625
1765
            "revision_history), and the branch will be write-locked. "
1626
1766
            "The set_rh hook can be expensive for bzr to trigger, a better "
1627
 
            "hook to use is Branch.post_change_branch_tip.", (0, 15), None))
1628
 
        self.create_hook(HookPoint('open',
 
1767
            "hook to use is Branch.post_change_branch_tip.", (0, 15))
 
1768
        self.add_hook('open',
1629
1769
            "Called with the Branch object that has been opened after a "
1630
 
            "branch is opened.", (1, 8), None))
1631
 
        self.create_hook(HookPoint('post_push',
 
1770
            "branch is opened.", (1, 8))
 
1771
        self.add_hook('post_push',
1632
1772
            "Called after a push operation completes. post_push is called "
1633
1773
            "with a bzrlib.branch.BranchPushResult object and only runs in the "
1634
 
            "bzr client.", (0, 15), None))
1635
 
        self.create_hook(HookPoint('post_pull',
 
1774
            "bzr client.", (0, 15))
 
1775
        self.add_hook('post_pull',
1636
1776
            "Called after a pull operation completes. post_pull is called "
1637
1777
            "with a bzrlib.branch.PullResult object and only runs in the "
1638
 
            "bzr client.", (0, 15), None))
1639
 
        self.create_hook(HookPoint('pre_commit',
1640
 
            "Called after a commit is calculated but before it is is "
 
1778
            "bzr client.", (0, 15))
 
1779
        self.add_hook('pre_commit',
 
1780
            "Called after a commit is calculated but before it is "
1641
1781
            "completed. pre_commit is called with (local, master, old_revno, "
1642
1782
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
1643
1783
            "). old_revid is NULL_REVISION for the first commit to a branch, "
1645
1785
            "basis revision. hooks MUST NOT modify this delta. "
1646
1786
            " future_tree is an in-memory tree obtained from "
1647
1787
            "CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1648
 
            "tree.", (0,91), None))
1649
 
        self.create_hook(HookPoint('post_commit',
 
1788
            "tree.", (0,91))
 
1789
        self.add_hook('post_commit',
1650
1790
            "Called in the bzr client after a commit has completed. "
1651
1791
            "post_commit is called with (local, master, old_revno, old_revid, "
1652
1792
            "new_revno, new_revid). old_revid is NULL_REVISION for the first "
1653
 
            "commit to a branch.", (0, 15), None))
1654
 
        self.create_hook(HookPoint('post_uncommit',
 
1793
            "commit to a branch.", (0, 15))
 
1794
        self.add_hook('post_uncommit',
1655
1795
            "Called in the bzr client after an uncommit completes. "
1656
1796
            "post_uncommit is called with (local, master, old_revno, "
1657
1797
            "old_revid, new_revno, new_revid) where local is the local branch "
1658
1798
            "or None, master is the target branch, and an empty branch "
1659
 
            "receives new_revno of 0, new_revid of None.", (0, 15), None))
1660
 
        self.create_hook(HookPoint('pre_change_branch_tip',
 
1799
            "receives new_revno of 0, new_revid of None.", (0, 15))
 
1800
        self.add_hook('pre_change_branch_tip',
1661
1801
            "Called in bzr client and server before a change to the tip of a "
1662
1802
            "branch is made. pre_change_branch_tip is called with a "
1663
1803
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1664
 
            "commit, uncommit will all trigger this hook.", (1, 6), None))
1665
 
        self.create_hook(HookPoint('post_change_branch_tip',
 
1804
            "commit, uncommit will all trigger this hook.", (1, 6))
 
1805
        self.add_hook('post_change_branch_tip',
1666
1806
            "Called in bzr client and server after a change to the tip of a "
1667
1807
            "branch is made. post_change_branch_tip is called with a "
1668
1808
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1669
 
            "commit, uncommit will all trigger this hook.", (1, 4), None))
1670
 
        self.create_hook(HookPoint('transform_fallback_location',
 
1809
            "commit, uncommit will all trigger this hook.", (1, 4))
 
1810
        self.add_hook('transform_fallback_location',
1671
1811
            "Called when a stacked branch is activating its fallback "
1672
1812
            "locations. transform_fallback_location is called with (branch, "
1673
1813
            "url), and should return a new url. Returning the same url "
1678
1818
            "fallback locations have not been activated. When there are "
1679
1819
            "multiple hooks installed for transform_fallback_location, "
1680
1820
            "all are called with the url returned from the previous hook."
1681
 
            "The order is however undefined.", (1, 9), None))
 
1821
            "The order is however undefined.", (1, 9))
 
1822
        self.add_hook('automatic_tag_name',
 
1823
            "Called to determine an automatic tag name for a revision. "
 
1824
            "automatic_tag_name is called with (branch, revision_id) and "
 
1825
            "should return a tag name or None if no tag name could be "
 
1826
            "determined. The first non-None tag name returned will be used.",
 
1827
            (2, 2))
 
1828
        self.add_hook('post_branch_init',
 
1829
            "Called after new branch initialization completes. "
 
1830
            "post_branch_init is called with a "
 
1831
            "bzrlib.branch.BranchInitHookParams. "
 
1832
            "Note that init, branch and checkout (both heavyweight and "
 
1833
            "lightweight) will all trigger this hook.", (2, 2))
 
1834
        self.add_hook('post_switch',
 
1835
            "Called after a checkout switches branch. "
 
1836
            "post_switch is called with a "
 
1837
            "bzrlib.branch.SwitchHookParams.", (2, 2))
 
1838
 
1682
1839
 
1683
1840
 
1684
1841
# install the default hooks into the Branch class.
1723
1880
            self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1724
1881
 
1725
1882
 
1726
 
class BzrBranchFormat4(BranchFormat):
1727
 
    """Bzr branch format 4.
1728
 
 
1729
 
    This format has:
1730
 
     - a revision-history file.
1731
 
     - a branch-lock lock file [ to be shared with the bzrdir ]
1732
 
    """
1733
 
 
1734
 
    def get_format_description(self):
1735
 
        """See BranchFormat.get_format_description()."""
1736
 
        return "Branch format 4"
1737
 
 
1738
 
    def initialize(self, a_bzrdir):
1739
 
        """Create a branch of this format in a_bzrdir."""
1740
 
        utf8_files = [('revision-history', ''),
1741
 
                      ('branch-name', ''),
1742
 
                      ]
1743
 
        return self._initialize_helper(a_bzrdir, utf8_files,
1744
 
                                       lock_type='branch4', set_format=False)
1745
 
 
1746
 
    def __init__(self):
1747
 
        super(BzrBranchFormat4, self).__init__()
1748
 
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
1749
 
 
1750
 
    def network_name(self):
1751
 
        """The network name for this format is the control dirs disk label."""
1752
 
        return self._matchingbzrdir.get_format_string()
1753
 
 
1754
 
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
1755
 
        """See BranchFormat.open()."""
1756
 
        if not _found:
1757
 
            # we are being called directly and must probe.
1758
 
            raise NotImplementedError
1759
 
        return BzrBranch(_format=self,
1760
 
                         _control_files=a_bzrdir._control_files,
1761
 
                         a_bzrdir=a_bzrdir,
1762
 
                         _repository=a_bzrdir.open_repository())
1763
 
 
1764
 
    def __str__(self):
1765
 
        return "Bazaar-NG branch format 4"
 
1883
class BranchInitHookParams(object):
 
1884
    """Object holding parameters passed to *_branch_init hooks.
 
1885
 
 
1886
    There are 4 fields that hooks may wish to access:
 
1887
 
 
1888
    :ivar format: the branch format
 
1889
    :ivar bzrdir: the BzrDir where the branch will be/has been initialized
 
1890
    :ivar name: name of colocated branch, if any (or None)
 
1891
    :ivar branch: the branch created
 
1892
 
 
1893
    Note that for lightweight checkouts, the bzrdir and format fields refer to
 
1894
    the checkout, hence they are different from the corresponding fields in
 
1895
    branch, which refer to the original branch.
 
1896
    """
 
1897
 
 
1898
    def __init__(self, format, a_bzrdir, name, branch):
 
1899
        """Create a group of BranchInitHook parameters.
 
1900
 
 
1901
        :param format: the branch format
 
1902
        :param a_bzrdir: the BzrDir where the branch will be/has been
 
1903
            initialized
 
1904
        :param name: name of colocated branch, if any (or None)
 
1905
        :param branch: the branch created
 
1906
 
 
1907
        Note that for lightweight checkouts, the bzrdir and format fields refer
 
1908
        to the checkout, hence they are different from the corresponding fields
 
1909
        in branch, which refer to the original branch.
 
1910
        """
 
1911
        self.format = format
 
1912
        self.bzrdir = a_bzrdir
 
1913
        self.name = name
 
1914
        self.branch = branch
 
1915
 
 
1916
    def __eq__(self, other):
 
1917
        return self.__dict__ == other.__dict__
 
1918
 
 
1919
    def __repr__(self):
 
1920
        return "<%s of %s>" % (self.__class__.__name__, self.branch)
 
1921
 
 
1922
 
 
1923
class SwitchHookParams(object):
 
1924
    """Object holding parameters passed to *_switch hooks.
 
1925
 
 
1926
    There are 4 fields that hooks may wish to access:
 
1927
 
 
1928
    :ivar control_dir: BzrDir of the checkout to change
 
1929
    :ivar to_branch: branch that the checkout is to reference
 
1930
    :ivar force: skip the check for local commits in a heavy checkout
 
1931
    :ivar revision_id: revision ID to switch to (or None)
 
1932
    """
 
1933
 
 
1934
    def __init__(self, control_dir, to_branch, force, revision_id):
 
1935
        """Create a group of SwitchHook parameters.
 
1936
 
 
1937
        :param control_dir: BzrDir of the checkout to change
 
1938
        :param to_branch: branch that the checkout is to reference
 
1939
        :param force: skip the check for local commits in a heavy checkout
 
1940
        :param revision_id: revision ID to switch to (or None)
 
1941
        """
 
1942
        self.control_dir = control_dir
 
1943
        self.to_branch = to_branch
 
1944
        self.force = force
 
1945
        self.revision_id = revision_id
 
1946
 
 
1947
    def __eq__(self, other):
 
1948
        return self.__dict__ == other.__dict__
 
1949
 
 
1950
    def __repr__(self):
 
1951
        return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
 
1952
            self.control_dir, self.to_branch,
 
1953
            self.revision_id)
1766
1954
 
1767
1955
 
1768
1956
class BranchFormatMetadir(BranchFormat):
1772
1960
        """What class to instantiate on open calls."""
1773
1961
        raise NotImplementedError(self._branch_class)
1774
1962
 
 
1963
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
 
1964
                           repository=None):
 
1965
        """Initialize a branch in a bzrdir, with specified files
 
1966
 
 
1967
        :param a_bzrdir: The bzrdir to initialize the branch in
 
1968
        :param utf8_files: The files to create as a list of
 
1969
            (filename, content) tuples
 
1970
        :param name: Name of colocated branch to create, if any
 
1971
        :return: a branch in this format
 
1972
        """
 
1973
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
 
1974
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
1975
        control_files = lockable_files.LockableFiles(branch_transport,
 
1976
            'lock', lockdir.LockDir)
 
1977
        control_files.create_lock()
 
1978
        control_files.lock_write()
 
1979
        try:
 
1980
            utf8_files += [('format', self.get_format_string())]
 
1981
            for (filename, content) in utf8_files:
 
1982
                branch_transport.put_bytes(
 
1983
                    filename, content,
 
1984
                    mode=a_bzrdir._get_file_mode())
 
1985
        finally:
 
1986
            control_files.unlock()
 
1987
        branch = self.open(a_bzrdir, name, _found=True,
 
1988
                found_repository=repository)
 
1989
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
 
1990
        return branch
 
1991
 
1775
1992
    def network_name(self):
1776
1993
        """A simple byte string uniquely identifying this format for RPC calls.
1777
1994
 
1779
1996
        """
1780
1997
        return self.get_format_string()
1781
1998
 
1782
 
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
 
1999
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
 
2000
            found_repository=None):
1783
2001
        """See BranchFormat.open()."""
1784
2002
        if not _found:
1785
 
            format = BranchFormat.find_format(a_bzrdir)
 
2003
            format = BranchFormat.find_format(a_bzrdir, name=name)
1786
2004
            if format.__class__ != self.__class__:
1787
2005
                raise AssertionError("wrong format %r found for %r" %
1788
2006
                    (format, self))
 
2007
        transport = a_bzrdir.get_branch_transport(None, name=name)
1789
2008
        try:
1790
 
            transport = a_bzrdir.get_branch_transport(None)
1791
2009
            control_files = lockable_files.LockableFiles(transport, 'lock',
1792
2010
                                                         lockdir.LockDir)
 
2011
            if found_repository is None:
 
2012
                found_repository = a_bzrdir.find_repository()
1793
2013
            return self._branch_class()(_format=self,
1794
2014
                              _control_files=control_files,
 
2015
                              name=name,
1795
2016
                              a_bzrdir=a_bzrdir,
1796
 
                              _repository=a_bzrdir.find_repository(),
 
2017
                              _repository=found_repository,
1797
2018
                              ignore_fallbacks=ignore_fallbacks)
1798
2019
        except errors.NoSuchFile:
1799
2020
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1806
2027
    def supports_tags(self):
1807
2028
        return True
1808
2029
 
 
2030
    def supports_leaving_lock(self):
 
2031
        return True
 
2032
 
1809
2033
 
1810
2034
class BzrBranchFormat5(BranchFormatMetadir):
1811
2035
    """Bzr branch format 5.
1831
2055
        """See BranchFormat.get_format_description()."""
1832
2056
        return "Branch format 5"
1833
2057
 
1834
 
    def initialize(self, a_bzrdir):
 
2058
    def initialize(self, a_bzrdir, name=None, repository=None):
1835
2059
        """Create a branch of this format in a_bzrdir."""
1836
2060
        utf8_files = [('revision-history', ''),
1837
2061
                      ('branch-name', ''),
1838
2062
                      ]
1839
 
        return self._initialize_helper(a_bzrdir, utf8_files)
 
2063
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
1840
2064
 
1841
2065
    def supports_tags(self):
1842
2066
        return False
1864
2088
        """See BranchFormat.get_format_description()."""
1865
2089
        return "Branch format 6"
1866
2090
 
1867
 
    def initialize(self, a_bzrdir):
 
2091
    def initialize(self, a_bzrdir, name=None, repository=None):
1868
2092
        """Create a branch of this format in a_bzrdir."""
1869
2093
        utf8_files = [('last-revision', '0 null:\n'),
1870
2094
                      ('branch.conf', ''),
1871
2095
                      ('tags', ''),
1872
2096
                      ]
1873
 
        return self._initialize_helper(a_bzrdir, utf8_files)
 
2097
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
1874
2098
 
1875
2099
    def make_tags(self, branch):
1876
2100
        """See bzrlib.branch.BranchFormat.make_tags()."""
1894
2118
        """See BranchFormat.get_format_description()."""
1895
2119
        return "Branch format 8"
1896
2120
 
1897
 
    def initialize(self, a_bzrdir):
 
2121
    def initialize(self, a_bzrdir, name=None, repository=None):
1898
2122
        """Create a branch of this format in a_bzrdir."""
1899
2123
        utf8_files = [('last-revision', '0 null:\n'),
1900
2124
                      ('branch.conf', ''),
1901
2125
                      ('tags', ''),
1902
2126
                      ('references', '')
1903
2127
                      ]
1904
 
        return self._initialize_helper(a_bzrdir, utf8_files)
1905
 
 
1906
 
    def __init__(self):
1907
 
        super(BzrBranchFormat8, self).__init__()
1908
 
        self._matchingbzrdir.repository_format = \
1909
 
            RepositoryFormatKnitPack5RichRoot()
 
2128
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
1910
2129
 
1911
2130
    def make_tags(self, branch):
1912
2131
        """See bzrlib.branch.BranchFormat.make_tags()."""
1921
2140
    supports_reference_locations = True
1922
2141
 
1923
2142
 
1924
 
class BzrBranchFormat7(BzrBranchFormat8):
 
2143
class BzrBranchFormat7(BranchFormatMetadir):
1925
2144
    """Branch format with last-revision, tags, and a stacked location pointer.
1926
2145
 
1927
2146
    The stacked location pointer is passed down to the repository and requires
1930
2149
    This format was introduced in bzr 1.6.
1931
2150
    """
1932
2151
 
1933
 
    def initialize(self, a_bzrdir):
 
2152
    def initialize(self, a_bzrdir, name=None, repository=None):
1934
2153
        """Create a branch of this format in a_bzrdir."""
1935
2154
        utf8_files = [('last-revision', '0 null:\n'),
1936
2155
                      ('branch.conf', ''),
1937
2156
                      ('tags', ''),
1938
2157
                      ]
1939
 
        return self._initialize_helper(a_bzrdir, utf8_files)
 
2158
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
1940
2159
 
1941
2160
    def _branch_class(self):
1942
2161
        return BzrBranch7
1952
2171
    def supports_set_append_revisions_only(self):
1953
2172
        return True
1954
2173
 
 
2174
    def supports_stacking(self):
 
2175
        return True
 
2176
 
 
2177
    def make_tags(self, branch):
 
2178
        """See bzrlib.branch.BranchFormat.make_tags()."""
 
2179
        return BasicTags(branch)
 
2180
 
1955
2181
    supports_reference_locations = False
1956
2182
 
1957
2183
 
1974
2200
        """See BranchFormat.get_format_description()."""
1975
2201
        return "Checkout reference format 1"
1976
2202
 
1977
 
    def get_reference(self, a_bzrdir):
 
2203
    def get_reference(self, a_bzrdir, name=None):
1978
2204
        """See BranchFormat.get_reference()."""
1979
 
        transport = a_bzrdir.get_branch_transport(None)
 
2205
        transport = a_bzrdir.get_branch_transport(None, name=name)
1980
2206
        return transport.get_bytes('location')
1981
2207
 
1982
 
    def set_reference(self, a_bzrdir, to_branch):
 
2208
    def set_reference(self, a_bzrdir, name, to_branch):
1983
2209
        """See BranchFormat.set_reference()."""
1984
 
        transport = a_bzrdir.get_branch_transport(None)
 
2210
        transport = a_bzrdir.get_branch_transport(None, name=name)
1985
2211
        location = transport.put_bytes('location', to_branch.base)
1986
2212
 
1987
 
    def initialize(self, a_bzrdir, target_branch=None):
 
2213
    def initialize(self, a_bzrdir, name=None, target_branch=None,
 
2214
            repository=None):
1988
2215
        """Create a branch of this format in a_bzrdir."""
1989
2216
        if target_branch is None:
1990
2217
            # this format does not implement branch itself, thus the implicit
1991
2218
            # creation contract must see it as uninitializable
1992
2219
            raise errors.UninitializableFormat(self)
1993
 
        mutter('creating branch reference in %s', a_bzrdir.transport.base)
1994
 
        branch_transport = a_bzrdir.get_branch_transport(self)
 
2220
        mutter('creating branch reference in %s', a_bzrdir.user_url)
 
2221
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
1995
2222
        branch_transport.put_bytes('location',
1996
 
            target_branch.bzrdir.root_transport.base)
 
2223
            target_branch.bzrdir.user_url)
1997
2224
        branch_transport.put_bytes('format', self.get_format_string())
1998
 
        return self.open(
1999
 
            a_bzrdir, _found=True,
 
2225
        branch = self.open(
 
2226
            a_bzrdir, name, _found=True,
2000
2227
            possible_transports=[target_branch.bzrdir.root_transport])
 
2228
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
 
2229
        return branch
2001
2230
 
2002
2231
    def __init__(self):
2003
2232
        super(BranchReferenceFormat, self).__init__()
2009
2238
        def clone(to_bzrdir, revision_id=None,
2010
2239
            repository_policy=None):
2011
2240
            """See Branch.clone()."""
2012
 
            return format.initialize(to_bzrdir, a_branch)
 
2241
            return format.initialize(to_bzrdir, target_branch=a_branch)
2013
2242
            # cannot obey revision_id limits when cloning a reference ...
2014
2243
            # FIXME RBC 20060210 either nuke revision_id for clone, or
2015
2244
            # emit some sort of warning/error to the caller ?!
2016
2245
        return clone
2017
2246
 
2018
 
    def open(self, a_bzrdir, _found=False, location=None,
2019
 
             possible_transports=None, ignore_fallbacks=False):
 
2247
    def open(self, a_bzrdir, name=None, _found=False, location=None,
 
2248
             possible_transports=None, ignore_fallbacks=False,
 
2249
             found_repository=None):
2020
2250
        """Return the branch that the branch reference in a_bzrdir points at.
2021
2251
 
2022
2252
        :param a_bzrdir: A BzrDir that contains a branch.
 
2253
        :param name: Name of colocated branch to open, if any
2023
2254
        :param _found: a private parameter, do not use it. It is used to
2024
2255
            indicate if format probing has already be done.
2025
2256
        :param ignore_fallbacks: when set, no fallback branches will be opened
2030
2261
        :param possible_transports: An optional reusable transports list.
2031
2262
        """
2032
2263
        if not _found:
2033
 
            format = BranchFormat.find_format(a_bzrdir)
 
2264
            format = BranchFormat.find_format(a_bzrdir, name=name)
2034
2265
            if format.__class__ != self.__class__:
2035
2266
                raise AssertionError("wrong format %r found for %r" %
2036
2267
                    (format, self))
2037
2268
        if location is None:
2038
 
            location = self.get_reference(a_bzrdir)
 
2269
            location = self.get_reference(a_bzrdir, name)
2039
2270
        real_bzrdir = bzrdir.BzrDir.open(
2040
2271
            location, possible_transports=possible_transports)
2041
 
        result = real_bzrdir.open_branch(ignore_fallbacks=ignore_fallbacks)
 
2272
        result = real_bzrdir.open_branch(name=name, 
 
2273
            ignore_fallbacks=ignore_fallbacks)
2042
2274
        # this changes the behaviour of result.clone to create a new reference
2043
2275
        # rather than a copy of the content of the branch.
2044
2276
        # I did not use a proxy object because that needs much more extensive
2051
2283
        return result
2052
2284
 
2053
2285
 
 
2286
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
 
2287
    """Branch format registry."""
 
2288
 
 
2289
    def __init__(self, other_registry=None):
 
2290
        super(BranchFormatRegistry, self).__init__(other_registry)
 
2291
        self._default_format = None
 
2292
 
 
2293
    def set_default(self, format):
 
2294
        self._default_format = format
 
2295
 
 
2296
    def get_default(self):
 
2297
        return self._default_format
 
2298
 
 
2299
 
2054
2300
network_format_registry = registry.FormatRegistry()
2055
2301
"""Registry of formats indexed by their network name.
2056
2302
 
2059
2305
BranchFormat.network_name() for more detail.
2060
2306
"""
2061
2307
 
 
2308
format_registry = BranchFormatRegistry(network_format_registry)
 
2309
 
2062
2310
 
2063
2311
# formats which have no format string are not discoverable
2064
2312
# and not independently creatable, so are not registered.
2066
2314
__format6 = BzrBranchFormat6()
2067
2315
__format7 = BzrBranchFormat7()
2068
2316
__format8 = BzrBranchFormat8()
2069
 
BranchFormat.register_format(__format5)
2070
 
BranchFormat.register_format(BranchReferenceFormat())
2071
 
BranchFormat.register_format(__format6)
2072
 
BranchFormat.register_format(__format7)
2073
 
BranchFormat.register_format(__format8)
2074
 
BranchFormat.set_default_format(__format7)
2075
 
_legacy_formats = [BzrBranchFormat4(),
2076
 
    ]
2077
 
network_format_registry.register(
2078
 
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
 
2317
format_registry.register(__format5)
 
2318
format_registry.register(BranchReferenceFormat())
 
2319
format_registry.register(__format6)
 
2320
format_registry.register(__format7)
 
2321
format_registry.register(__format8)
 
2322
format_registry.set_default(__format7)
 
2323
 
 
2324
 
 
2325
class BranchWriteLockResult(LogicalLockResult):
 
2326
    """The result of write locking a branch.
 
2327
 
 
2328
    :ivar branch_token: The token obtained from the underlying branch lock, or
 
2329
        None.
 
2330
    :ivar unlock: A callable which will unlock the lock.
 
2331
    """
 
2332
 
 
2333
    def __init__(self, unlock, branch_token):
 
2334
        LogicalLockResult.__init__(self, unlock)
 
2335
        self.branch_token = branch_token
 
2336
 
 
2337
    def __repr__(self):
 
2338
        return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
 
2339
            self.unlock)
2079
2340
 
2080
2341
 
2081
2342
class BzrBranch(Branch, _RelockDebugMixin):
2090
2351
    :ivar repository: Repository for this branch.
2091
2352
    :ivar base: The url of the base directory for this branch; the one
2092
2353
        containing the .bzr directory.
 
2354
    :ivar name: Optional colocated branch name as it exists in the control
 
2355
        directory.
2093
2356
    """
2094
2357
 
2095
2358
    def __init__(self, _format=None,
2096
 
                 _control_files=None, a_bzrdir=None, _repository=None,
2097
 
                 ignore_fallbacks=False):
 
2359
                 _control_files=None, a_bzrdir=None, name=None,
 
2360
                 _repository=None, ignore_fallbacks=False):
2098
2361
        """Create new branch object at a particular location."""
2099
2362
        if a_bzrdir is None:
2100
2363
            raise ValueError('a_bzrdir must be supplied')
2101
2364
        else:
2102
2365
            self.bzrdir = a_bzrdir
2103
2366
        self._base = self.bzrdir.transport.clone('..').base
 
2367
        self.name = name
2104
2368
        # XXX: We should be able to just do
2105
2369
        #   self.base = self.bzrdir.root_transport.base
2106
2370
        # but this does not quite work yet -- mbp 20080522
2113
2377
        Branch.__init__(self)
2114
2378
 
2115
2379
    def __str__(self):
2116
 
        return '%s(%r)' % (self.__class__.__name__, self.base)
 
2380
        if self.name is None:
 
2381
            return '%s(%s)' % (self.__class__.__name__, self.user_url)
 
2382
        else:
 
2383
            return '%s(%s,%s)' % (self.__class__.__name__, self.user_url,
 
2384
                self.name)
2117
2385
 
2118
2386
    __repr__ = __str__
2119
2387
 
2130
2398
        return self.control_files.is_locked()
2131
2399
 
2132
2400
    def lock_write(self, token=None):
 
2401
        """Lock the branch for write operations.
 
2402
 
 
2403
        :param token: A token to permit reacquiring a previously held and
 
2404
            preserved lock.
 
2405
        :return: A BranchWriteLockResult.
 
2406
        """
2133
2407
        if not self.is_locked():
2134
2408
            self._note_lock('w')
2135
2409
        # All-in-one needs to always unlock/lock.
2141
2415
        else:
2142
2416
            took_lock = False
2143
2417
        try:
2144
 
            return self.control_files.lock_write(token=token)
 
2418
            return BranchWriteLockResult(self.unlock,
 
2419
                self.control_files.lock_write(token=token))
2145
2420
        except:
2146
2421
            if took_lock:
2147
2422
                self.repository.unlock()
2148
2423
            raise
2149
2424
 
2150
2425
    def lock_read(self):
 
2426
        """Lock the branch for read operations.
 
2427
 
 
2428
        :return: A bzrlib.lock.LogicalLockResult.
 
2429
        """
2151
2430
        if not self.is_locked():
2152
2431
            self._note_lock('r')
2153
2432
        # All-in-one needs to always unlock/lock.
2160
2439
            took_lock = False
2161
2440
        try:
2162
2441
            self.control_files.lock_read()
 
2442
            return LogicalLockResult(self.unlock)
2163
2443
        except:
2164
2444
            if took_lock:
2165
2445
                self.repository.unlock()
2202
2482
            'revision-history', '\n'.join(history),
2203
2483
            mode=self.bzrdir._get_file_mode())
2204
2484
 
2205
 
    @needs_write_lock
 
2485
    @deprecated_method(deprecated_in((2, 4, 0)))
2206
2486
    def set_revision_history(self, rev_history):
2207
2487
        """See Branch.set_revision_history."""
 
2488
        self._set_revision_history(rev_history)
 
2489
 
 
2490
    @needs_write_lock
 
2491
    def _set_revision_history(self, rev_history):
2208
2492
        if 'evil' in debug.debug_flags:
2209
2493
            mutter_callsite(3, "set_revision_history scales with history.")
2210
2494
        check_not_reserved_id = _mod_revision.check_not_reserved_id
2254
2538
            except ValueError:
2255
2539
                rev = self.repository.get_revision(revision_id)
2256
2540
                new_history = rev.get_history(self.repository)[1:]
2257
 
        destination.set_revision_history(new_history)
 
2541
        destination._set_revision_history(new_history)
2258
2542
 
2259
2543
    @needs_write_lock
2260
2544
    def set_last_revision_info(self, revno, revision_id):
2268
2552
        configured to check constraints on history, in which case this may not
2269
2553
        be permitted.
2270
2554
        """
2271
 
        revision_id = _mod_revision.ensure_null(revision_id)
 
2555
        if not revision_id or not isinstance(revision_id, basestring):
 
2556
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2272
2557
        # this old format stores the full history, but this api doesn't
2273
2558
        # provide it, so we must generate, and might as well check it's
2274
2559
        # correct
2275
2560
        history = self._lefthand_history(revision_id)
2276
2561
        if len(history) != revno:
2277
2562
            raise AssertionError('%d != %d' % (len(history), revno))
2278
 
        self.set_revision_history(history)
 
2563
        self._set_revision_history(history)
2279
2564
 
2280
2565
    def _gen_revision_history(self):
2281
2566
        history = self._transport.get_bytes('revision-history').split('\n')
2295
2580
        :param other_branch: The other branch that DivergedBranches should
2296
2581
            raise with respect to.
2297
2582
        """
2298
 
        self.set_revision_history(self._lefthand_history(revision_id,
 
2583
        self._set_revision_history(self._lefthand_history(revision_id,
2299
2584
            last_rev, other_branch))
2300
2585
 
2301
2586
    def basis_tree(self):
2311
2596
                pass
2312
2597
        return None
2313
2598
 
2314
 
    def _basic_push(self, target, overwrite, stop_revision):
2315
 
        """Basic implementation of push without bound branches or hooks.
2316
 
 
2317
 
        Must be called with source read locked and target write locked.
2318
 
        """
2319
 
        result = BranchPushResult()
2320
 
        result.source_branch = self
2321
 
        result.target_branch = target
2322
 
        result.old_revno, result.old_revid = target.last_revision_info()
2323
 
        self.update_references(target)
2324
 
        if result.old_revid != self.last_revision():
2325
 
            # We assume that during 'push' this repository is closer than
2326
 
            # the target.
2327
 
            graph = self.repository.get_graph(target.repository)
2328
 
            target.update_revisions(self, stop_revision,
2329
 
                overwrite=overwrite, graph=graph)
2330
 
        if self._push_should_merge_tags():
2331
 
            result.tag_conflicts = self.tags.merge_to(target.tags,
2332
 
                overwrite)
2333
 
        result.new_revno, result.new_revid = target.last_revision_info()
2334
 
        return result
2335
 
 
2336
2599
    def get_stacked_on_url(self):
2337
 
        raise errors.UnstackableBranchFormat(self._format, self.base)
 
2600
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
2338
2601
 
2339
2602
    def set_push_location(self, location):
2340
2603
        """See Branch.set_push_location."""
2367
2630
        """Return the branch we are bound to.
2368
2631
 
2369
2632
        :return: Either a Branch, or None
2370
 
 
2371
 
        This could memoise the branch, but if thats done
2372
 
        it must be revalidated on each new lock.
2373
 
        So for now we just don't memoise it.
2374
 
        # RBC 20060304 review this decision.
2375
2633
        """
 
2634
        if self._master_branch_cache is None:
 
2635
            self._master_branch_cache = self._get_master_branch(
 
2636
                possible_transports)
 
2637
        return self._master_branch_cache
 
2638
 
 
2639
    def _get_master_branch(self, possible_transports):
2376
2640
        bound_loc = self.get_bound_location()
2377
2641
        if not bound_loc:
2378
2642
            return None
2389
2653
 
2390
2654
        :param location: URL to the target branch
2391
2655
        """
 
2656
        self._master_branch_cache = None
2392
2657
        if location:
2393
2658
            self._transport.put_bytes('bound', location+'\n',
2394
2659
                mode=self.bzrdir._get_file_mode())
2503
2768
 
2504
2769
    @needs_write_lock
2505
2770
    def set_last_revision_info(self, revno, revision_id):
2506
 
        revision_id = _mod_revision.ensure_null(revision_id)
 
2771
        if not revision_id or not isinstance(revision_id, basestring):
 
2772
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2507
2773
        old_revno, old_revid = self.last_revision_info()
2508
2774
        if self._get_append_revisions_only():
2509
2775
            self._check_history_violation(revision_id)
2530
2796
        if _mod_revision.is_null(last_revision):
2531
2797
            return
2532
2798
        if last_revision not in self._lefthand_history(revision_id):
2533
 
            raise errors.AppendRevisionsOnlyViolation(self.base)
 
2799
            raise errors.AppendRevisionsOnlyViolation(self.user_url)
2534
2800
 
2535
2801
    def _gen_revision_history(self):
2536
2802
        """Generate the revision history from last revision
2636
2902
        if branch_location is None:
2637
2903
            return Branch.reference_parent(self, file_id, path,
2638
2904
                                           possible_transports)
2639
 
        branch_location = urlutils.join(self.base, branch_location)
 
2905
        branch_location = urlutils.join(self.user_url, branch_location)
2640
2906
        return Branch.open(branch_location,
2641
2907
                           possible_transports=possible_transports)
2642
2908
 
2646
2912
 
2647
2913
    def set_bound_location(self, location):
2648
2914
        """See Branch.set_push_location."""
 
2915
        self._master_branch_cache = None
2649
2916
        result = None
2650
2917
        config = self.get_config()
2651
2918
        if location is None:
2688
2955
        return stacked_url
2689
2956
 
2690
2957
    def _get_append_revisions_only(self):
2691
 
        value = self.get_config().get_user_option('append_revisions_only')
2692
 
        return value == 'True'
 
2958
        return self.get_config(
 
2959
            ).get_user_option_as_bool('append_revisions_only')
2693
2960
 
2694
2961
    @needs_write_lock
2695
2962
    def generate_revision_history(self, revision_id, last_rev=None,
2728
2995
        try:
2729
2996
            index = self._partial_revision_history_cache.index(revision_id)
2730
2997
        except ValueError:
2731
 
            self._extend_partial_history(stop_revision=revision_id)
 
2998
            try:
 
2999
                self._extend_partial_history(stop_revision=revision_id)
 
3000
            except errors.RevisionNotPresent, e:
 
3001
                raise errors.GhostRevisionsHaveNoRevno(revision_id, e.revision_id)
2732
3002
            index = len(self._partial_revision_history_cache) - 1
2733
3003
            if self._partial_revision_history_cache[index] != revision_id:
2734
3004
                raise errors.NoSuchRevision(self, revision_id)
2757
3027
    """
2758
3028
 
2759
3029
    def get_stacked_on_url(self):
2760
 
        raise errors.UnstackableBranchFormat(self._format, self.base)
 
3030
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
2761
3031
 
2762
3032
 
2763
3033
######################################################################
2789
3059
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
2790
3060
    """
2791
3061
 
 
3062
    @deprecated_method(deprecated_in((2, 3, 0)))
2792
3063
    def __int__(self):
2793
 
        # DEPRECATED: pull used to return the change in revno
 
3064
        """Return the relative change in revno.
 
3065
 
 
3066
        :deprecated: Use `new_revno` and `old_revno` instead.
 
3067
        """
2794
3068
        return self.new_revno - self.old_revno
2795
3069
 
2796
3070
    def report(self, to_file):
2821
3095
        target, otherwise it will be None.
2822
3096
    """
2823
3097
 
 
3098
    @deprecated_method(deprecated_in((2, 3, 0)))
2824
3099
    def __int__(self):
2825
 
        # DEPRECATED: push used to return the change in revno
 
3100
        """Return the relative change in revno.
 
3101
 
 
3102
        :deprecated: Use `new_revno` and `old_revno` instead.
 
3103
        """
2826
3104
        return self.new_revno - self.old_revno
2827
3105
 
2828
3106
    def report(self, to_file):
2850
3128
        :param verbose: Requests more detailed display of what was checked,
2851
3129
            if any.
2852
3130
        """
2853
 
        note('checked branch %s format %s', self.branch.base,
 
3131
        note('checked branch %s format %s', self.branch.user_url,
2854
3132
            self.branch._format)
2855
3133
        for error in self.errors:
2856
3134
            note('found error:%s', error)
2951
3229
    _optimisers = []
2952
3230
    """The available optimised InterBranch types."""
2953
3231
 
2954
 
    @staticmethod
2955
 
    def _get_branch_formats_to_test():
2956
 
        """Return a tuple with the Branch formats to use when testing."""
2957
 
        raise NotImplementedError(InterBranch._get_branch_formats_to_test)
 
3232
    @classmethod
 
3233
    def _get_branch_formats_to_test(klass):
 
3234
        """Return an iterable of format tuples for testing.
 
3235
        
 
3236
        :return: An iterable of (from_format, to_format) to use when testing
 
3237
            this InterBranch class. Each InterBranch class should define this
 
3238
            method itself.
 
3239
        """
 
3240
        raise NotImplementedError(klass._get_branch_formats_to_test)
2958
3241
 
 
3242
    @needs_write_lock
2959
3243
    def pull(self, overwrite=False, stop_revision=None,
2960
3244
             possible_transports=None, local=False):
2961
3245
        """Mirror source into target branch.
2966
3250
        """
2967
3251
        raise NotImplementedError(self.pull)
2968
3252
 
2969
 
    def update_revisions(self, stop_revision=None, overwrite=False,
2970
 
                         graph=None):
2971
 
        """Pull in new perfect-fit revisions.
2972
 
 
2973
 
        :param stop_revision: Updated until the given revision
2974
 
        :param overwrite: Always set the branch pointer, rather than checking
2975
 
            to see if it is a proper descendant.
2976
 
        :param graph: A Graph object that can be used to query history
2977
 
            information. This can be None.
2978
 
        :return: None
2979
 
        """
2980
 
        raise NotImplementedError(self.update_revisions)
2981
 
 
 
3253
    @needs_write_lock
2982
3254
    def push(self, overwrite=False, stop_revision=None,
2983
3255
             _override_hook_source_branch=None):
2984
3256
        """Mirror the source branch into the target branch.
2987
3259
        """
2988
3260
        raise NotImplementedError(self.push)
2989
3261
 
 
3262
    @needs_write_lock
 
3263
    def copy_content_into(self, revision_id=None):
 
3264
        """Copy the content of source into target
 
3265
 
 
3266
        revision_id: if not None, the revision history in the new branch will
 
3267
                     be truncated to end with revision_id.
 
3268
        """
 
3269
        raise NotImplementedError(self.copy_content_into)
 
3270
 
 
3271
    @needs_write_lock
 
3272
    def fetch(self, stop_revision=None):
 
3273
        """Fetch revisions.
 
3274
 
 
3275
        :param stop_revision: Last revision to fetch
 
3276
        """
 
3277
        raise NotImplementedError(self.fetch)
 
3278
 
2990
3279
 
2991
3280
class GenericInterBranch(InterBranch):
2992
 
    """InterBranch implementation that uses public Branch functions.
2993
 
    """
2994
 
 
2995
 
    @staticmethod
2996
 
    def _get_branch_formats_to_test():
2997
 
        return BranchFormat._default_format, BranchFormat._default_format
2998
 
 
2999
 
    def update_revisions(self, stop_revision=None, overwrite=False,
3000
 
        graph=None):
3001
 
        """See InterBranch.update_revisions()."""
 
3281
    """InterBranch implementation that uses public Branch functions."""
 
3282
 
 
3283
    @classmethod
 
3284
    def is_compatible(klass, source, target):
 
3285
        # GenericBranch uses the public API, so always compatible
 
3286
        return True
 
3287
 
 
3288
    @classmethod
 
3289
    def _get_branch_formats_to_test(klass):
 
3290
        return [(format_registry.get_default(), format_registry.get_default())]
 
3291
 
 
3292
    @classmethod
 
3293
    def unwrap_format(klass, format):
 
3294
        if isinstance(format, remote.RemoteBranchFormat):
 
3295
            format._ensure_real()
 
3296
            return format._custom_format
 
3297
        return format
 
3298
 
 
3299
    @needs_write_lock
 
3300
    def copy_content_into(self, revision_id=None):
 
3301
        """Copy the content of source into target
 
3302
 
 
3303
        revision_id: if not None, the revision history in the new branch will
 
3304
                     be truncated to end with revision_id.
 
3305
        """
 
3306
        self.source.update_references(self.target)
 
3307
        self.source._synchronize_history(self.target, revision_id)
 
3308
        try:
 
3309
            parent = self.source.get_parent()
 
3310
        except errors.InaccessibleParent, e:
 
3311
            mutter('parent was not accessible to copy: %s', e)
 
3312
        else:
 
3313
            if parent:
 
3314
                self.target.set_parent(parent)
 
3315
        if self.source._push_should_merge_tags():
 
3316
            self.source.tags.merge_to(self.target.tags)
 
3317
 
 
3318
    @needs_write_lock
 
3319
    def fetch(self, stop_revision=None):
 
3320
        if self.target.base == self.source.base:
 
3321
            return (0, [])
3002
3322
        self.source.lock_read()
3003
3323
        try:
3004
 
            other_revno, other_last_revision = self.source.last_revision_info()
3005
 
            stop_revno = None # unknown
3006
 
            if stop_revision is None:
3007
 
                stop_revision = other_last_revision
3008
 
                if _mod_revision.is_null(stop_revision):
3009
 
                    # if there are no commits, we're done.
3010
 
                    return
3011
 
                stop_revno = other_revno
3012
 
 
3013
 
            # what's the current last revision, before we fetch [and change it
3014
 
            # possibly]
3015
 
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
3016
 
            # we fetch here so that we don't process data twice in the common
3017
 
            # case of having something to pull, and so that the check for
3018
 
            # already merged can operate on the just fetched graph, which will
3019
 
            # be cached in memory.
3020
 
            self.target.fetch(self.source, stop_revision)
3021
 
            # Check to see if one is an ancestor of the other
3022
 
            if not overwrite:
3023
 
                if graph is None:
3024
 
                    graph = self.target.repository.get_graph()
3025
 
                if self.target._check_if_descendant_or_diverged(
3026
 
                        stop_revision, last_rev, graph, self.source):
3027
 
                    # stop_revision is a descendant of last_rev, but we aren't
3028
 
                    # overwriting, so we're done.
3029
 
                    return
3030
 
            if stop_revno is None:
3031
 
                if graph is None:
3032
 
                    graph = self.target.repository.get_graph()
3033
 
                this_revno, this_last_revision = \
3034
 
                        self.target.last_revision_info()
3035
 
                stop_revno = graph.find_distance_to_null(stop_revision,
3036
 
                                [(other_last_revision, other_revno),
3037
 
                                 (this_last_revision, this_revno)])
3038
 
            self.target.set_last_revision_info(stop_revno, stop_revision)
 
3324
            fetch_spec_factory = fetch.FetchSpecFactory()
 
3325
            fetch_spec_factory.source_branch = self.source
 
3326
            fetch_spec_factory.source_branch_stop_revision_id = stop_revision
 
3327
            fetch_spec_factory.source_repo = self.source.repository
 
3328
            fetch_spec_factory.target_repo = self.target.repository
 
3329
            fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
 
3330
            fetch_spec = fetch_spec_factory.make_fetch_spec()
 
3331
            return self.target.repository.fetch(self.source.repository,
 
3332
                fetch_spec=fetch_spec)
3039
3333
        finally:
3040
3334
            self.source.unlock()
3041
3335
 
 
3336
    @needs_write_lock
 
3337
    def _update_revisions(self, stop_revision=None, overwrite=False,
 
3338
            graph=None):
 
3339
        other_revno, other_last_revision = self.source.last_revision_info()
 
3340
        stop_revno = None # unknown
 
3341
        if stop_revision is None:
 
3342
            stop_revision = other_last_revision
 
3343
            if _mod_revision.is_null(stop_revision):
 
3344
                # if there are no commits, we're done.
 
3345
                return
 
3346
            stop_revno = other_revno
 
3347
 
 
3348
        # what's the current last revision, before we fetch [and change it
 
3349
        # possibly]
 
3350
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
3351
        # we fetch here so that we don't process data twice in the common
 
3352
        # case of having something to pull, and so that the check for
 
3353
        # already merged can operate on the just fetched graph, which will
 
3354
        # be cached in memory.
 
3355
        self.fetch(stop_revision=stop_revision)
 
3356
        # Check to see if one is an ancestor of the other
 
3357
        if not overwrite:
 
3358
            if graph is None:
 
3359
                graph = self.target.repository.get_graph()
 
3360
            if self.target._check_if_descendant_or_diverged(
 
3361
                    stop_revision, last_rev, graph, self.source):
 
3362
                # stop_revision is a descendant of last_rev, but we aren't
 
3363
                # overwriting, so we're done.
 
3364
                return
 
3365
        if stop_revno is None:
 
3366
            if graph is None:
 
3367
                graph = self.target.repository.get_graph()
 
3368
            this_revno, this_last_revision = \
 
3369
                    self.target.last_revision_info()
 
3370
            stop_revno = graph.find_distance_to_null(stop_revision,
 
3371
                            [(other_last_revision, other_revno),
 
3372
                             (this_last_revision, this_revno)])
 
3373
        self.target.set_last_revision_info(stop_revno, stop_revision)
 
3374
 
 
3375
    @needs_write_lock
3042
3376
    def pull(self, overwrite=False, stop_revision=None,
3043
 
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3377
             possible_transports=None, run_hooks=True,
3044
3378
             _override_hook_target=None, local=False):
3045
 
        """See Branch.pull.
 
3379
        """Pull from source into self, updating my master if any.
3046
3380
 
3047
 
        :param _hook_master: Private parameter - set the branch to
3048
 
            be supplied as the master to pull hooks.
3049
3381
        :param run_hooks: Private parameter - if false, this branch
3050
3382
            is being called because it's the master of the primary branch,
3051
3383
            so it should not run its hooks.
3052
 
        :param _override_hook_target: Private parameter - set the branch to be
3053
 
            supplied as the target_branch to pull hooks.
3054
 
        :param local: Only update the local branch, and not the bound branch.
3055
3384
        """
3056
 
        # This type of branch can't be bound.
3057
 
        if local:
 
3385
        bound_location = self.target.get_bound_location()
 
3386
        if local and not bound_location:
3058
3387
            raise errors.LocalRequiresBoundBranch()
3059
 
        result = PullResult()
3060
 
        result.source_branch = self.source
3061
 
        if _override_hook_target is None:
3062
 
            result.target_branch = self.target
3063
 
        else:
3064
 
            result.target_branch = _override_hook_target
3065
 
        self.source.lock_read()
 
3388
        master_branch = None
 
3389
        source_is_master = (self.source.user_url == bound_location)
 
3390
        if not local and bound_location and not source_is_master:
 
3391
            # not pulling from master, so we need to update master.
 
3392
            master_branch = self.target.get_master_branch(possible_transports)
 
3393
            master_branch.lock_write()
3066
3394
        try:
3067
 
            # We assume that during 'pull' the target repository is closer than
3068
 
            # the source one.
3069
 
            self.source.update_references(self.target)
3070
 
            graph = self.target.repository.get_graph(self.source.repository)
3071
 
            # TODO: Branch formats should have a flag that indicates 
3072
 
            # that revno's are expensive, and pull() should honor that flag.
3073
 
            # -- JRV20090506
3074
 
            result.old_revno, result.old_revid = \
3075
 
                self.target.last_revision_info()
3076
 
            self.target.update_revisions(self.source, stop_revision,
3077
 
                overwrite=overwrite, graph=graph)
3078
 
            # TODO: The old revid should be specified when merging tags, 
3079
 
            # so a tags implementation that versions tags can only 
3080
 
            # pull in the most recent changes. -- JRV20090506
3081
 
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3082
 
                overwrite)
3083
 
            result.new_revno, result.new_revid = self.target.last_revision_info()
3084
 
            if _hook_master:
3085
 
                result.master_branch = _hook_master
3086
 
                result.local_branch = result.target_branch
3087
 
            else:
3088
 
                result.master_branch = result.target_branch
3089
 
                result.local_branch = None
3090
 
            if run_hooks:
3091
 
                for hook in Branch.hooks['post_pull']:
3092
 
                    hook(result)
 
3395
            if master_branch:
 
3396
                # pull from source into master.
 
3397
                master_branch.pull(self.source, overwrite, stop_revision,
 
3398
                    run_hooks=False)
 
3399
            return self._pull(overwrite,
 
3400
                stop_revision, _hook_master=master_branch,
 
3401
                run_hooks=run_hooks,
 
3402
                _override_hook_target=_override_hook_target,
 
3403
                merge_tags_to_master=not source_is_master)
3093
3404
        finally:
3094
 
            self.source.unlock()
3095
 
        return result
 
3405
            if master_branch:
 
3406
                master_branch.unlock()
3096
3407
 
3097
3408
    def push(self, overwrite=False, stop_revision=None,
3098
3409
             _override_hook_source_branch=None):
3116
3427
        finally:
3117
3428
            self.source.unlock()
3118
3429
 
 
3430
    def _basic_push(self, overwrite, stop_revision):
 
3431
        """Basic implementation of push without bound branches or hooks.
 
3432
 
 
3433
        Must be called with source read locked and target write locked.
 
3434
        """
 
3435
        result = BranchPushResult()
 
3436
        result.source_branch = self.source
 
3437
        result.target_branch = self.target
 
3438
        result.old_revno, result.old_revid = self.target.last_revision_info()
 
3439
        self.source.update_references(self.target)
 
3440
        if result.old_revid != stop_revision:
 
3441
            # We assume that during 'push' this repository is closer than
 
3442
            # the target.
 
3443
            graph = self.source.repository.get_graph(self.target.repository)
 
3444
            self._update_revisions(stop_revision, overwrite=overwrite,
 
3445
                    graph=graph)
 
3446
        if self.source._push_should_merge_tags():
 
3447
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
3448
                overwrite)
 
3449
        result.new_revno, result.new_revid = self.target.last_revision_info()
 
3450
        return result
 
3451
 
3119
3452
    def _push_with_bound_branches(self, overwrite, stop_revision,
3120
3453
            _override_hook_source_branch=None):
3121
3454
        """Push from source into target, and into target's master if any.
3136
3469
            master_branch.lock_write()
3137
3470
            try:
3138
3471
                # push into the master from the source branch.
3139
 
                self.source._basic_push(master_branch, overwrite, stop_revision)
3140
 
                # and push into the target branch from the source. Note that we
3141
 
                # push from the source branch again, because its considered the
3142
 
                # highest bandwidth repository.
3143
 
                result = self.source._basic_push(self.target, overwrite,
3144
 
                    stop_revision)
 
3472
                master_inter = InterBranch.get(self.source, master_branch)
 
3473
                master_inter._basic_push(overwrite, stop_revision)
 
3474
                # and push into the target branch from the source. Note that
 
3475
                # we push from the source branch again, because it's considered
 
3476
                # the highest bandwidth repository.
 
3477
                result = self._basic_push(overwrite, stop_revision)
3145
3478
                result.master_branch = master_branch
3146
3479
                result.local_branch = self.target
3147
3480
                _run_hooks()
3150
3483
                master_branch.unlock()
3151
3484
        else:
3152
3485
            # no master branch
3153
 
            result = self.source._basic_push(self.target, overwrite,
3154
 
                stop_revision)
 
3486
            result = self._basic_push(overwrite, stop_revision)
3155
3487
            # TODO: Why set master_branch and local_branch if there's no
3156
3488
            # binding?  Maybe cleaner to just leave them unset? -- mbp
3157
3489
            # 20070504
3160
3492
            _run_hooks()
3161
3493
            return result
3162
3494
 
3163
 
    @classmethod
3164
 
    def is_compatible(self, source, target):
3165
 
        # GenericBranch uses the public API, so always compatible
3166
 
        return True
3167
 
 
3168
 
 
3169
 
class InterToBranch5(GenericInterBranch):
3170
 
 
3171
 
    @staticmethod
3172
 
    def _get_branch_formats_to_test():
3173
 
        return BranchFormat._default_format, BzrBranchFormat5()
3174
 
 
3175
 
    def pull(self, overwrite=False, stop_revision=None,
3176
 
             possible_transports=None, run_hooks=True,
3177
 
             _override_hook_target=None, local=False):
3178
 
        """Pull from source into self, updating my master if any.
3179
 
 
 
3495
    def _pull(self, overwrite=False, stop_revision=None,
 
3496
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3497
             _override_hook_target=None, local=False,
 
3498
             merge_tags_to_master=True):
 
3499
        """See Branch.pull.
 
3500
 
 
3501
        This function is the core worker, used by GenericInterBranch.pull to
 
3502
        avoid duplication when pulling source->master and source->local.
 
3503
 
 
3504
        :param _hook_master: Private parameter - set the branch to
 
3505
            be supplied as the master to pull hooks.
3180
3506
        :param run_hooks: Private parameter - if false, this branch
3181
3507
            is being called because it's the master of the primary branch,
3182
3508
            so it should not run its hooks.
 
3509
            is being called because it's the master of the primary branch,
 
3510
            so it should not run its hooks.
 
3511
        :param _override_hook_target: Private parameter - set the branch to be
 
3512
            supplied as the target_branch to pull hooks.
 
3513
        :param local: Only update the local branch, and not the bound branch.
3183
3514
        """
3184
 
        bound_location = self.target.get_bound_location()
3185
 
        if local and not bound_location:
 
3515
        # This type of branch can't be bound.
 
3516
        if local:
3186
3517
            raise errors.LocalRequiresBoundBranch()
3187
 
        master_branch = None
3188
 
        if not local and bound_location and self.source.base != bound_location:
3189
 
            # not pulling from master, so we need to update master.
3190
 
            master_branch = self.target.get_master_branch(possible_transports)
3191
 
            master_branch.lock_write()
 
3518
        result = PullResult()
 
3519
        result.source_branch = self.source
 
3520
        if _override_hook_target is None:
 
3521
            result.target_branch = self.target
 
3522
        else:
 
3523
            result.target_branch = _override_hook_target
 
3524
        self.source.lock_read()
3192
3525
        try:
3193
 
            if master_branch:
3194
 
                # pull from source into master.
3195
 
                master_branch.pull(self.source, overwrite, stop_revision,
3196
 
                    run_hooks=False)
3197
 
            return super(InterToBranch5, self).pull(overwrite,
3198
 
                stop_revision, _hook_master=master_branch,
3199
 
                run_hooks=run_hooks,
3200
 
                _override_hook_target=_override_hook_target)
 
3526
            # We assume that during 'pull' the target repository is closer than
 
3527
            # the source one.
 
3528
            self.source.update_references(self.target)
 
3529
            graph = self.target.repository.get_graph(self.source.repository)
 
3530
            # TODO: Branch formats should have a flag that indicates 
 
3531
            # that revno's are expensive, and pull() should honor that flag.
 
3532
            # -- JRV20090506
 
3533
            result.old_revno, result.old_revid = \
 
3534
                self.target.last_revision_info()
 
3535
            self._update_revisions(stop_revision, overwrite=overwrite,
 
3536
                graph=graph)
 
3537
            # TODO: The old revid should be specified when merging tags, 
 
3538
            # so a tags implementation that versions tags can only 
 
3539
            # pull in the most recent changes. -- JRV20090506
 
3540
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
3541
                overwrite, ignore_master=not merge_tags_to_master)
 
3542
            result.new_revno, result.new_revid = self.target.last_revision_info()
 
3543
            if _hook_master:
 
3544
                result.master_branch = _hook_master
 
3545
                result.local_branch = result.target_branch
 
3546
            else:
 
3547
                result.master_branch = result.target_branch
 
3548
                result.local_branch = None
 
3549
            if run_hooks:
 
3550
                for hook in Branch.hooks['post_pull']:
 
3551
                    hook(result)
3201
3552
        finally:
3202
 
            if master_branch:
3203
 
                master_branch.unlock()
 
3553
            self.source.unlock()
 
3554
        return result
3204
3555
 
3205
3556
 
3206
3557
InterBranch.register_optimiser(GenericInterBranch)
3207
 
InterBranch.register_optimiser(InterToBranch5)