/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Jelmer Vernooij
  • Date: 2011-05-08 13:46:49 UTC
  • mto: This revision was merged to the branch mainline in revision 5842.
  • Revision ID: jelmer@samba.org-20110508134649-26xas3otdjlw9jpa
Translate local set_rh calls to remote set_rh calls.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 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
 
class Branch(bzrdir.ControlComponent):
 
75
class Branch(controldir.ControlComponent):
67
76
    """Branch holding a history of revisions.
68
77
 
69
78
    :ivar base:
70
79
        Base directory/url of the branch; using control_url and
71
80
        control_transport is more standardized.
72
 
 
73
 
    hooks: An instance of BranchHooks.
 
81
    :ivar hooks: An instance of BranchHooks.
 
82
    :ivar _master_branch_cache: cached result of get_master_branch, see
 
83
        _clear_cached_state.
74
84
    """
75
85
    # this is really an instance variable - FIXME move it there
76
86
    # - RBC 20060112
90
100
        self._revision_id_to_revno_cache = None
91
101
        self._partial_revision_id_to_revno_cache = {}
92
102
        self._partial_revision_history_cache = []
 
103
        self._tags_bytes = None
93
104
        self._last_revision_info_cache = None
 
105
        self._master_branch_cache = None
94
106
        self._merge_sorted_revisions_cache = None
95
107
        self._open_hook()
96
108
        hooks = Branch.hooks['open']
102
114
 
103
115
    def _activate_fallback_location(self, url):
104
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
105
124
        repo = self._get_fallback_repository(url)
106
125
        if repo.has_same_location(self.repository):
107
126
            raise errors.UnstackableLocationError(self.user_url, url)
197
216
        return self.supports_tags() and self.tags.get_tag_dict()
198
217
 
199
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
        """
200
226
        return BranchConfig(self)
201
227
 
202
228
    def _get_config(self):
218
244
            possible_transports=[self.bzrdir.root_transport])
219
245
        return a_branch.repository
220
246
 
 
247
    @needs_read_lock
221
248
    def _get_tags_bytes(self):
222
249
        """Get the bytes of a serialised tags dict.
223
250
 
230
257
        :return: The bytes of the tags file.
231
258
        :seealso: Branch._set_tags_bytes.
232
259
        """
233
 
        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
234
263
 
235
264
    def _get_nick(self, local=False, possible_transports=None):
236
265
        config = self.get_config()
238
267
        if not local and not config.has_explicit_nickname():
239
268
            try:
240
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)
241
272
                if master is not None:
242
273
                    # return the master branch value
243
274
                    return master.nick
 
275
            except errors.RecursiveBind, e:
 
276
                raise e
244
277
            except errors.BzrError, e:
245
278
                # Silently fall back to local implicit nick if the master is
246
279
                # unavailable
283
316
        new_history.reverse()
284
317
        return new_history
285
318
 
286
 
    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
        """
287
326
        raise NotImplementedError(self.lock_write)
288
327
 
289
328
    def lock_read(self):
 
329
        """Lock the branch for read operations.
 
330
 
 
331
        :return: A bzrlib.lock.LogicalLockResult.
 
332
        """
290
333
        raise NotImplementedError(self.lock_read)
291
334
 
292
335
    def unlock(self):
626
669
        raise errors.UnsupportedOperation(self.get_reference_info, self)
627
670
 
628
671
    @needs_write_lock
629
 
    def fetch(self, from_branch, last_revision=None, pb=None):
 
672
    def fetch(self, from_branch, last_revision=None):
630
673
        """Copy revisions from from_branch into this branch.
631
674
 
632
675
        :param from_branch: Where to copy from.
633
676
        :param last_revision: What revision to stop at (None for at the end
634
677
                              of the branch.
635
 
        :param pb: An optional progress bar to use.
636
678
        :return: None
637
679
        """
638
 
        if self.base == from_branch.base:
639
 
            return (0, [])
640
 
        if pb is not None:
641
 
            symbol_versioning.warn(
642
 
                symbol_versioning.deprecated_in((1, 14, 0))
643
 
                % "pb parameter to fetch()")
644
 
        from_branch.lock_read()
645
 
        try:
646
 
            if last_revision is None:
647
 
                last_revision = from_branch.last_revision()
648
 
                last_revision = _mod_revision.ensure_null(last_revision)
649
 
            return self.repository.fetch(from_branch.repository,
650
 
                                         revision_id=last_revision,
651
 
                                         pb=pb)
652
 
        finally:
653
 
            from_branch.unlock()
 
680
        return InterBranch.get(from_branch, self).fetch(last_revision)
654
681
 
655
682
    def get_bound_location(self):
656
683
        """Return the URL of the branch we are bound to.
667
694
 
668
695
    def get_commit_builder(self, parents, config=None, timestamp=None,
669
696
                           timezone=None, committer=None, revprops=None,
670
 
                           revision_id=None):
 
697
                           revision_id=None, lossy=False):
671
698
        """Obtain a CommitBuilder for this branch.
672
699
 
673
700
        :param parents: Revision ids of the parents of the new revision.
677
704
        :param committer: Optional committer to set for commit.
678
705
        :param revprops: Optional dictionary of revision properties.
679
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 
680
709
        """
681
710
 
682
711
        if config is None:
683
712
            config = self.get_config()
684
713
 
685
714
        return self.repository.get_commit_builder(self, parents, config,
686
 
            timestamp, timezone, committer, revprops, revision_id)
 
715
            timestamp, timezone, committer, revprops, revision_id,
 
716
            lossy)
687
717
 
688
718
    def get_master_branch(self, possible_transports=None):
689
719
        """Return the branch we are bound to.
716
746
        """Print `file` to stdout."""
717
747
        raise NotImplementedError(self.print_file)
718
748
 
 
749
    @deprecated_method(deprecated_in((2, 4, 0)))
719
750
    def set_revision_history(self, rev_history):
720
 
        raise NotImplementedError(self.set_revision_history)
 
751
        """See Branch.set_revision_history."""
 
752
        self._set_revision_history(rev_history)
 
753
 
 
754
    @needs_write_lock
 
755
    def _set_revision_history(self, rev_history):
 
756
        if len(rev_history) == 0:
 
757
            revid = _mod_revision.NULL_REVISION
 
758
        else:
 
759
            revid = rev_history[-1]
 
760
        if rev_history != self._lefthand_history(revid):
 
761
            raise errors.NotLefthandHistory(rev_history)
 
762
        self.set_last_revision_info(len(rev_history), revid)
 
763
        self._cache_revision_history(rev_history)
 
764
        for hook in Branch.hooks['set_rh']:
 
765
            hook(self, rev_history)
 
766
 
 
767
    @needs_write_lock
 
768
    def set_last_revision_info(self, revno, revision_id):
 
769
        """Set the last revision of this branch.
 
770
 
 
771
        The caller is responsible for checking that the revno is correct
 
772
        for this revision id.
 
773
 
 
774
        It may be possible to set the branch last revision to an id not
 
775
        present in the repository.  However, branches can also be
 
776
        configured to check constraints on history, in which case this may not
 
777
        be permitted.
 
778
        """
 
779
        raise NotImplementedError(self.last_revision_info)
 
780
 
 
781
    @needs_write_lock
 
782
    def generate_revision_history(self, revision_id, last_rev=None,
 
783
                                  other_branch=None):
 
784
        """See Branch.generate_revision_history"""
 
785
        # FIXME: This shouldn't have to fetch the entire history
 
786
        history = self._lefthand_history(revision_id, last_rev, other_branch)
 
787
        revno = len(history)
 
788
        self.set_last_revision_info(revno, revision_id)
 
789
        self._cache_revision_history(history)
721
790
 
722
791
    @needs_write_lock
723
792
    def set_parent(self, url):
767
836
 
768
837
    def _unstack(self):
769
838
        """Change a branch to be unstacked, copying data as needed.
770
 
        
 
839
 
771
840
        Don't call this directly, use set_stacked_on_url(None).
772
841
        """
773
842
        pb = ui.ui_factory.nested_progress_bar()
782
851
            old_repository = self.repository
783
852
            if len(old_repository._fallback_repositories) != 1:
784
853
                raise AssertionError("can't cope with fallback repositories "
785
 
                    "of %r" % (self.repository,))
786
 
            # unlock it, including unlocking the fallback
 
854
                    "of %r (fallbacks: %r)" % (old_repository,
 
855
                        old_repository._fallback_repositories))
 
856
            # Open the new repository object.
 
857
            # Repositories don't offer an interface to remove fallback
 
858
            # repositories today; take the conceptually simpler option and just
 
859
            # reopen it.  We reopen it starting from the URL so that we
 
860
            # get a separate connection for RemoteRepositories and can
 
861
            # stream from one of them to the other.  This does mean doing
 
862
            # separate SSH connection setup, but unstacking is not a
 
863
            # common operation so it's tolerable.
 
864
            new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
 
865
            new_repository = new_bzrdir.find_repository()
 
866
            if new_repository._fallback_repositories:
 
867
                raise AssertionError("didn't expect %r to have "
 
868
                    "fallback_repositories"
 
869
                    % (self.repository,))
 
870
            # Replace self.repository with the new repository.
 
871
            # Do our best to transfer the lock state (i.e. lock-tokens and
 
872
            # lock count) of self.repository to the new repository.
 
873
            lock_token = old_repository.lock_write().repository_token
 
874
            self.repository = new_repository
 
875
            if isinstance(self, remote.RemoteBranch):
 
876
                # Remote branches can have a second reference to the old
 
877
                # repository that need to be replaced.
 
878
                if self._real_branch is not None:
 
879
                    self._real_branch.repository = new_repository
 
880
            self.repository.lock_write(token=lock_token)
 
881
            if lock_token is not None:
 
882
                old_repository.leave_lock_in_place()
787
883
            old_repository.unlock()
 
884
            if lock_token is not None:
 
885
                # XXX: self.repository.leave_lock_in_place() before this
 
886
                # function will not be preserved.  Fortunately that doesn't
 
887
                # affect the current default format (2a), and would be a
 
888
                # corner-case anyway.
 
889
                #  - Andrew Bennetts, 2010/06/30
 
890
                self.repository.dont_leave_lock_in_place()
 
891
            old_lock_count = 0
 
892
            while True:
 
893
                try:
 
894
                    old_repository.unlock()
 
895
                except errors.LockNotHeld:
 
896
                    break
 
897
                old_lock_count += 1
 
898
            if old_lock_count == 0:
 
899
                raise AssertionError(
 
900
                    'old_repository should have been locked at least once.')
 
901
            for i in range(old_lock_count-1):
 
902
                self.repository.lock_write()
 
903
            # Fetch from the old repository into the new.
788
904
            old_repository.lock_read()
789
905
            try:
790
 
                # Repositories don't offer an interface to remove fallback
791
 
                # repositories today; take the conceptually simpler option and just
792
 
                # reopen it.  We reopen it starting from the URL so that we
793
 
                # get a separate connection for RemoteRepositories and can
794
 
                # stream from one of them to the other.  This does mean doing
795
 
                # separate SSH connection setup, but unstacking is not a
796
 
                # common operation so it's tolerable.
797
 
                new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
798
 
                new_repository = new_bzrdir.find_repository()
799
 
                self.repository = new_repository
800
 
                if self.repository._fallback_repositories:
801
 
                    raise AssertionError("didn't expect %r to have "
802
 
                        "fallback_repositories"
803
 
                        % (self.repository,))
804
 
                # this is not paired with an unlock because it's just restoring
805
 
                # the previous state; the lock's released when set_stacked_on_url
806
 
                # returns
807
 
                self.repository.lock_write()
808
906
                # XXX: If you unstack a branch while it has a working tree
809
907
                # with a pending merge, the pending-merged revisions will no
810
908
                # longer be present.  You can (probably) revert and remerge.
811
 
                #
812
 
                # XXX: This only fetches up to the tip of the repository; it
813
 
                # doesn't bring across any tags.  That's fairly consistent
814
 
                # with how branch works, but perhaps not ideal.
815
 
                self.repository.fetch(old_repository,
816
 
                    revision_id=self.last_revision(),
817
 
                    find_ghosts=True)
 
909
                try:
 
910
                    tags_to_fetch = set(self.tags.get_reverse_tag_dict())
 
911
                except errors.TagsNotSupported:
 
912
                    tags_to_fetch = set()
 
913
                fetch_spec = _mod_graph.NotInOtherForRevs(self.repository,
 
914
                    old_repository, required_ids=[self.last_revision()],
 
915
                    if_present_ids=tags_to_fetch, find_ghosts=True).execute()
 
916
                self.repository.fetch(old_repository, fetch_spec=fetch_spec)
818
917
            finally:
819
918
                old_repository.unlock()
820
919
        finally:
825
924
 
826
925
        :seealso: Branch._get_tags_bytes.
827
926
        """
828
 
        return _run_with_write_locked_target(self, self._transport.put_bytes,
829
 
            'tags', bytes)
 
927
        return _run_with_write_locked_target(self, self._set_tags_bytes_locked,
 
928
                bytes)
 
929
 
 
930
    def _set_tags_bytes_locked(self, bytes):
 
931
        self._tags_bytes = bytes
 
932
        return self._transport.put_bytes('tags', bytes)
830
933
 
831
934
    def _cache_revision_history(self, rev_history):
832
935
        """Set the cached revision history to rev_history.
859
962
        self._revision_history_cache = None
860
963
        self._revision_id_to_revno_cache = None
861
964
        self._last_revision_info_cache = None
 
965
        self._master_branch_cache = None
862
966
        self._merge_sorted_revisions_cache = None
863
967
        self._partial_revision_history_cache = []
864
968
        self._partial_revision_id_to_revno_cache = {}
 
969
        self._tags_bytes = None
865
970
 
866
971
    def _gen_revision_history(self):
867
972
        """Return sequence of revision hashes on to this branch.
917
1022
        :return: A tuple (revno, revision_id).
918
1023
        """
919
1024
        if self._last_revision_info_cache is None:
920
 
            self._last_revision_info_cache = self._last_revision_info()
 
1025
            self._last_revision_info_cache = self._read_last_revision_info()
921
1026
        return self._last_revision_info_cache
922
1027
 
923
 
    def _last_revision_info(self):
924
 
        rh = self.revision_history()
925
 
        revno = len(rh)
926
 
        if revno:
927
 
            return (revno, rh[-1])
928
 
        else:
929
 
            return (0, _mod_revision.NULL_REVISION)
930
 
 
931
 
    @deprecated_method(deprecated_in((1, 6, 0)))
932
 
    def missing_revisions(self, other, stop_revision=None):
933
 
        """Return a list of new revisions that would perfectly fit.
934
 
 
935
 
        If self and other have not diverged, return a list of the revisions
936
 
        present in other, but missing from self.
937
 
        """
938
 
        self_history = self.revision_history()
939
 
        self_len = len(self_history)
940
 
        other_history = other.revision_history()
941
 
        other_len = len(other_history)
942
 
        common_index = min(self_len, other_len) -1
943
 
        if common_index >= 0 and \
944
 
            self_history[common_index] != other_history[common_index]:
945
 
            raise errors.DivergedBranches(self, other)
946
 
 
947
 
        if stop_revision is None:
948
 
            stop_revision = other_len
949
 
        else:
950
 
            if stop_revision > other_len:
951
 
                raise errors.NoSuchRevision(self, stop_revision)
952
 
        return other_history[self_len:stop_revision]
953
 
 
954
 
    @needs_write_lock
 
1028
    def _read_last_revision_info(self):
 
1029
        raise NotImplementedError(self._read_last_revision_info)
 
1030
 
955
1031
    def update_revisions(self, other, stop_revision=None, overwrite=False,
956
 
                         graph=None):
 
1032
            graph=None):
957
1033
        """Pull in new perfect-fit revisions.
958
1034
 
959
1035
        :param other: Another Branch to pull from
967
1043
        return InterBranch.get(other, self).update_revisions(stop_revision,
968
1044
            overwrite, graph)
969
1045
 
 
1046
    @deprecated_method(deprecated_in((2, 4, 0)))
970
1047
    def import_last_revision_info(self, source_repo, revno, revid):
971
1048
        """Set the last revision info, importing from another repo if necessary.
972
1049
 
973
 
        This is used by the bound branch code to upload a revision to
974
 
        the master branch first before updating the tip of the local branch.
975
 
 
976
1050
        :param source_repo: Source repository to optionally fetch from
977
1051
        :param revno: Revision number of the new tip
978
1052
        :param revid: Revision id of the new tip
981
1055
            self.repository.fetch(source_repo, revision_id=revid)
982
1056
        self.set_last_revision_info(revno, revid)
983
1057
 
 
1058
    def import_last_revision_info_and_tags(self, source, revno, revid,
 
1059
                                           lossy=False):
 
1060
        """Set the last revision info, importing from another repo if necessary.
 
1061
 
 
1062
        This is used by the bound branch code to upload a revision to
 
1063
        the master branch first before updating the tip of the local branch.
 
1064
        Revisions referenced by source's tags are also transferred.
 
1065
 
 
1066
        :param source: Source branch to optionally fetch from
 
1067
        :param revno: Revision number of the new tip
 
1068
        :param revid: Revision id of the new tip
 
1069
        :param lossy: Whether to discard metadata that can not be
 
1070
            natively represented
 
1071
        :return: Tuple with the new revision number and revision id
 
1072
            (should only be different from the arguments when lossy=True)
 
1073
        """
 
1074
        if not self.repository.has_same_location(source.repository):
 
1075
            self.fetch(source, revid)
 
1076
        self.set_last_revision_info(revno, revid)
 
1077
        return (revno, revid)
 
1078
 
984
1079
    def revision_id_to_revno(self, revision_id):
985
1080
        """Given a revision id, return its revno"""
986
1081
        if _mod_revision.is_null(revision_id):
1006
1101
            self._extend_partial_history(distance_from_last)
1007
1102
        return self._partial_revision_history_cache[distance_from_last]
1008
1103
 
1009
 
    @needs_write_lock
1010
1104
    def pull(self, source, overwrite=False, stop_revision=None,
1011
1105
             possible_transports=None, *args, **kwargs):
1012
1106
        """Mirror source into this branch.
1208
1302
        return result
1209
1303
 
1210
1304
    @needs_read_lock
1211
 
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None):
 
1305
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None,
 
1306
            repository=None):
1212
1307
        """Create a new line of development from the branch, into to_bzrdir.
1213
1308
 
1214
1309
        to_bzrdir controls the branch format.
1219
1314
        if (repository_policy is not None and
1220
1315
            repository_policy.requires_stacking()):
1221
1316
            to_bzrdir._format.require_stacking(_skip_repo=True)
1222
 
        result = to_bzrdir.create_branch()
 
1317
        result = to_bzrdir.create_branch(repository=repository)
1223
1318
        result.lock_write()
1224
1319
        try:
1225
1320
            if repository_policy is not None:
1255
1350
                revno = 1
1256
1351
        destination.set_last_revision_info(revno, revision_id)
1257
1352
 
1258
 
    @needs_read_lock
1259
1353
    def copy_content_into(self, destination, revision_id=None):
1260
1354
        """Copy the content of self into destination.
1261
1355
 
1262
1356
        revision_id: if not None, the revision history in the new branch will
1263
1357
                     be truncated to end with revision_id.
1264
1358
        """
1265
 
        self.update_references(destination)
1266
 
        self._synchronize_history(destination, revision_id)
1267
 
        try:
1268
 
            parent = self.get_parent()
1269
 
        except errors.InaccessibleParent, e:
1270
 
            mutter('parent was not accessible to copy: %s', e)
1271
 
        else:
1272
 
            if parent:
1273
 
                destination.set_parent(parent)
1274
 
        if self._push_should_merge_tags():
1275
 
            self.tags.merge_to(destination.tags)
 
1359
        return InterBranch.get(self, destination).copy_content_into(
 
1360
            revision_id=revision_id)
1276
1361
 
1277
1362
    def update_references(self, target):
1278
1363
        if not getattr(self._format, 'supports_reference_locations', False):
1323
1408
        """Return the most suitable metadir for a checkout of this branch.
1324
1409
        Weaves are used if this branch's repository uses weaves.
1325
1410
        """
1326
 
        if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
1327
 
            from bzrlib.repofmt import weaverepo
1328
 
            format = bzrdir.BzrDirMetaFormat1()
1329
 
            format.repository_format = weaverepo.RepositoryFormat7()
1330
 
        else:
1331
 
            format = self.repository.bzrdir.checkout_metadir()
1332
 
            format.set_branch_format(self._format)
 
1411
        format = self.repository.bzrdir.checkout_metadir()
 
1412
        format.set_branch_format(self._format)
1333
1413
        return format
1334
1414
 
1335
1415
    def create_clone_on_transport(self, to_transport, revision_id=None,
1336
 
        stacked_on=None, create_prefix=False, use_existing_dir=False):
 
1416
        stacked_on=None, create_prefix=False, use_existing_dir=False,
 
1417
        no_tree=None):
1337
1418
        """Create a clone of this branch and its bzrdir.
1338
1419
 
1339
1420
        :param to_transport: The transport to clone onto.
1346
1427
        """
1347
1428
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1348
1429
        # clone call. Or something. 20090224 RBC/spiv.
 
1430
        # XXX: Should this perhaps clone colocated branches as well, 
 
1431
        # rather than just the default branch? 20100319 JRV
1349
1432
        if revision_id is None:
1350
1433
            revision_id = self.last_revision()
1351
1434
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1352
1435
            revision_id=revision_id, stacked_on=stacked_on,
1353
 
            create_prefix=create_prefix, use_existing_dir=use_existing_dir)
 
1436
            create_prefix=create_prefix, use_existing_dir=use_existing_dir,
 
1437
            no_tree=no_tree)
1354
1438
        return dir_to.open_branch()
1355
1439
 
1356
1440
    def create_checkout(self, to_location, revision_id=None,
1471
1555
        else:
1472
1556
            raise AssertionError("invalid heads: %r" % (heads,))
1473
1557
 
1474
 
 
1475
 
class BranchFormat(object):
 
1558
    def heads_to_fetch(self):
 
1559
        """Return the heads that must and that should be fetched to copy this
 
1560
        branch into another repo.
 
1561
 
 
1562
        :returns: a 2-tuple of (must_fetch, if_present_fetch).  must_fetch is a
 
1563
            set of heads that must be fetched.  if_present_fetch is a set of
 
1564
            heads that must be fetched if present, but no error is necessary if
 
1565
            they are not present.
 
1566
        """
 
1567
        # For bzr native formats must_fetch is just the tip, and if_present_fetch
 
1568
        # are the tags.
 
1569
        must_fetch = set([self.last_revision()])
 
1570
        try:
 
1571
            if_present_fetch = set(self.tags.get_reverse_tag_dict())
 
1572
        except errors.TagsNotSupported:
 
1573
            if_present_fetch = set()
 
1574
        must_fetch.discard(_mod_revision.NULL_REVISION)
 
1575
        if_present_fetch.discard(_mod_revision.NULL_REVISION)
 
1576
        return must_fetch, if_present_fetch
 
1577
 
 
1578
 
 
1579
class BranchFormat(controldir.ControlComponentFormat):
1476
1580
    """An encapsulation of the initialization and open routines for a format.
1477
1581
 
1478
1582
    Formats provide three things:
1481
1585
     * an open routine.
1482
1586
 
1483
1587
    Formats are placed in an dict by their format string for reference
1484
 
    during branch opening. Its not required that these be instances, they
 
1588
    during branch opening. It's not required that these be instances, they
1485
1589
    can be classes themselves with class methods - it simply depends on
1486
1590
    whether state is needed for a given format or not.
1487
1591
 
1490
1594
    object will be created every time regardless.
1491
1595
    """
1492
1596
 
1493
 
    _default_format = None
1494
 
    """The default format used for new branches."""
1495
 
 
1496
 
    _formats = {}
1497
 
    """The known formats."""
1498
 
 
1499
1597
    can_set_append_revisions_only = True
1500
1598
 
1501
1599
    def __eq__(self, other):
1510
1608
        try:
1511
1609
            transport = a_bzrdir.get_branch_transport(None, name=name)
1512
1610
            format_string = transport.get_bytes("format")
1513
 
            return klass._formats[format_string]
 
1611
            return format_registry.get(format_string)
1514
1612
        except errors.NoSuchFile:
1515
1613
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1516
1614
        except KeyError:
1517
1615
            raise errors.UnknownFormatError(format=format_string, kind='branch')
1518
1616
 
1519
1617
    @classmethod
 
1618
    @deprecated_method(deprecated_in((2, 4, 0)))
1520
1619
    def get_default_format(klass):
1521
1620
        """Return the current default format."""
1522
 
        return klass._default_format
1523
 
 
1524
 
    def get_reference(self, a_bzrdir):
 
1621
        return format_registry.get_default()
 
1622
 
 
1623
    @classmethod
 
1624
    @deprecated_method(deprecated_in((2, 4, 0)))
 
1625
    def get_formats(klass):
 
1626
        """Get all the known formats.
 
1627
 
 
1628
        Warning: This triggers a load of all lazy registered formats: do not
 
1629
        use except when that is desireed.
 
1630
        """
 
1631
        return format_registry._get_all()
 
1632
 
 
1633
    def get_reference(self, a_bzrdir, name=None):
1525
1634
        """Get the target reference of the branch in a_bzrdir.
1526
1635
 
1527
1636
        format probing must have been completed before calling
1529
1638
        in a_bzrdir is correct.
1530
1639
 
1531
1640
        :param a_bzrdir: The bzrdir to get the branch data from.
 
1641
        :param name: Name of the colocated branch to fetch
1532
1642
        :return: None if the branch is not a reference branch.
1533
1643
        """
1534
1644
        return None
1535
1645
 
1536
1646
    @classmethod
1537
 
    def set_reference(self, a_bzrdir, to_branch):
 
1647
    def set_reference(self, a_bzrdir, name, to_branch):
1538
1648
        """Set the target reference of the branch in a_bzrdir.
1539
1649
 
1540
1650
        format probing must have been completed before calling
1542
1652
        in a_bzrdir is correct.
1543
1653
 
1544
1654
        :param a_bzrdir: The bzrdir to set the branch reference for.
 
1655
        :param name: Name of colocated branch to set, None for default
1545
1656
        :param to_branch: branch that the checkout is to reference
1546
1657
        """
1547
1658
        raise NotImplementedError(self.set_reference)
1562
1673
        for hook in hooks:
1563
1674
            hook(params)
1564
1675
 
1565
 
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
1566
 
                           lock_type='metadir', set_format=True):
1567
 
        """Initialize a branch in a bzrdir, with specified files
1568
 
 
1569
 
        :param a_bzrdir: The bzrdir to initialize the branch in
1570
 
        :param utf8_files: The files to create as a list of
1571
 
            (filename, content) tuples
1572
 
        :param name: Name of colocated branch to create, if any
1573
 
        :param set_format: If True, set the format with
1574
 
            self.get_format_string.  (BzrBranch4 has its format set
1575
 
            elsewhere)
1576
 
        :return: a branch in this format
1577
 
        """
1578
 
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
1579
 
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
1580
 
        lock_map = {
1581
 
            'metadir': ('lock', lockdir.LockDir),
1582
 
            'branch4': ('branch-lock', lockable_files.TransportLock),
1583
 
        }
1584
 
        lock_name, lock_class = lock_map[lock_type]
1585
 
        control_files = lockable_files.LockableFiles(branch_transport,
1586
 
            lock_name, lock_class)
1587
 
        control_files.create_lock()
1588
 
        try:
1589
 
            control_files.lock_write()
1590
 
        except errors.LockContention:
1591
 
            if lock_type != 'branch4':
1592
 
                raise
1593
 
            lock_taken = False
1594
 
        else:
1595
 
            lock_taken = True
1596
 
        if set_format:
1597
 
            utf8_files += [('format', self.get_format_string())]
1598
 
        try:
1599
 
            for (filename, content) in utf8_files:
1600
 
                branch_transport.put_bytes(
1601
 
                    filename, content,
1602
 
                    mode=a_bzrdir._get_file_mode())
1603
 
        finally:
1604
 
            if lock_taken:
1605
 
                control_files.unlock()
1606
 
        branch = self.open(a_bzrdir, name, _found=True)
1607
 
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
1608
 
        return branch
1609
 
 
1610
 
    def initialize(self, a_bzrdir, name=None):
 
1676
    def initialize(self, a_bzrdir, name=None, repository=None):
1611
1677
        """Create a branch of this format in a_bzrdir.
1612
1678
        
1613
1679
        :param name: Name of the colocated branch to create.
1647
1713
        """
1648
1714
        raise NotImplementedError(self.network_name)
1649
1715
 
1650
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1716
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
 
1717
            found_repository=None):
1651
1718
        """Return the branch object for a_bzrdir
1652
1719
 
1653
1720
        :param a_bzrdir: A BzrDir that contains a branch.
1660
1727
        raise NotImplementedError(self.open)
1661
1728
 
1662
1729
    @classmethod
 
1730
    @deprecated_method(deprecated_in((2, 4, 0)))
1663
1731
    def register_format(klass, format):
1664
 
        """Register a metadir format."""
1665
 
        klass._formats[format.get_format_string()] = format
1666
 
        # Metadir formats have a network name of their format string, and get
1667
 
        # registered as class factories.
1668
 
        network_format_registry.register(format.get_format_string(), format.__class__)
 
1732
        """Register a metadir format.
 
1733
 
 
1734
        See MetaDirBranchFormatFactory for the ability to register a format
 
1735
        without loading the code the format needs until it is actually used.
 
1736
        """
 
1737
        format_registry.register(format)
1669
1738
 
1670
1739
    @classmethod
 
1740
    @deprecated_method(deprecated_in((2, 4, 0)))
1671
1741
    def set_default_format(klass, format):
1672
 
        klass._default_format = format
 
1742
        format_registry.set_default(format)
1673
1743
 
1674
1744
    def supports_set_append_revisions_only(self):
1675
1745
        """True if this format supports set_append_revisions_only."""
1679
1749
        """True if this format records a stacked-on branch."""
1680
1750
        return False
1681
1751
 
 
1752
    def supports_leaving_lock(self):
 
1753
        """True if this format supports leaving locks in place."""
 
1754
        return False # by default
 
1755
 
1682
1756
    @classmethod
 
1757
    @deprecated_method(deprecated_in((2, 4, 0)))
1683
1758
    def unregister_format(klass, format):
1684
 
        del klass._formats[format.get_format_string()]
 
1759
        format_registry.remove(format)
1685
1760
 
1686
1761
    def __str__(self):
1687
1762
        return self.get_format_description().rstrip()
1691
1766
        return False  # by default
1692
1767
 
1693
1768
 
 
1769
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
 
1770
    """A factory for a BranchFormat object, permitting simple lazy registration.
 
1771
    
 
1772
    While none of the built in BranchFormats are lazy registered yet,
 
1773
    bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
 
1774
    use it, and the bzr-loom plugin uses it as well (see
 
1775
    bzrlib.plugins.loom.formats).
 
1776
    """
 
1777
 
 
1778
    def __init__(self, format_string, module_name, member_name):
 
1779
        """Create a MetaDirBranchFormatFactory.
 
1780
 
 
1781
        :param format_string: The format string the format has.
 
1782
        :param module_name: Module to load the format class from.
 
1783
        :param member_name: Attribute name within the module for the format class.
 
1784
        """
 
1785
        registry._LazyObjectGetter.__init__(self, module_name, member_name)
 
1786
        self._format_string = format_string
 
1787
        
 
1788
    def get_format_string(self):
 
1789
        """See BranchFormat.get_format_string."""
 
1790
        return self._format_string
 
1791
 
 
1792
    def __call__(self):
 
1793
        """Used for network_format_registry support."""
 
1794
        return self.get_obj()()
 
1795
 
 
1796
 
1694
1797
class BranchHooks(Hooks):
1695
1798
    """A dictionary mapping hook name to a list of callables for branch hooks.
1696
1799
 
1704
1807
        These are all empty initially, because by default nothing should get
1705
1808
        notified.
1706
1809
        """
1707
 
        Hooks.__init__(self)
1708
 
        self.create_hook(HookPoint('set_rh',
 
1810
        Hooks.__init__(self, "bzrlib.branch", "Branch.hooks")
 
1811
        self.add_hook('set_rh',
1709
1812
            "Invoked whenever the revision history has been set via "
1710
1813
            "set_revision_history. The api signature is (branch, "
1711
1814
            "revision_history), and the branch will be write-locked. "
1712
1815
            "The set_rh hook can be expensive for bzr to trigger, a better "
1713
 
            "hook to use is Branch.post_change_branch_tip.", (0, 15), None))
1714
 
        self.create_hook(HookPoint('open',
 
1816
            "hook to use is Branch.post_change_branch_tip.", (0, 15))
 
1817
        self.add_hook('open',
1715
1818
            "Called with the Branch object that has been opened after a "
1716
 
            "branch is opened.", (1, 8), None))
1717
 
        self.create_hook(HookPoint('post_push',
 
1819
            "branch is opened.", (1, 8))
 
1820
        self.add_hook('post_push',
1718
1821
            "Called after a push operation completes. post_push is called "
1719
1822
            "with a bzrlib.branch.BranchPushResult object and only runs in the "
1720
 
            "bzr client.", (0, 15), None))
1721
 
        self.create_hook(HookPoint('post_pull',
 
1823
            "bzr client.", (0, 15))
 
1824
        self.add_hook('post_pull',
1722
1825
            "Called after a pull operation completes. post_pull is called "
1723
1826
            "with a bzrlib.branch.PullResult object and only runs in the "
1724
 
            "bzr client.", (0, 15), None))
1725
 
        self.create_hook(HookPoint('pre_commit',
1726
 
            "Called after a commit is calculated but before it is is "
 
1827
            "bzr client.", (0, 15))
 
1828
        self.add_hook('pre_commit',
 
1829
            "Called after a commit is calculated but before it is "
1727
1830
            "completed. pre_commit is called with (local, master, old_revno, "
1728
1831
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
1729
1832
            "). old_revid is NULL_REVISION for the first commit to a branch, "
1731
1834
            "basis revision. hooks MUST NOT modify this delta. "
1732
1835
            " future_tree is an in-memory tree obtained from "
1733
1836
            "CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1734
 
            "tree.", (0,91), None))
1735
 
        self.create_hook(HookPoint('post_commit',
 
1837
            "tree.", (0,91))
 
1838
        self.add_hook('post_commit',
1736
1839
            "Called in the bzr client after a commit has completed. "
1737
1840
            "post_commit is called with (local, master, old_revno, old_revid, "
1738
1841
            "new_revno, new_revid). old_revid is NULL_REVISION for the first "
1739
 
            "commit to a branch.", (0, 15), None))
1740
 
        self.create_hook(HookPoint('post_uncommit',
 
1842
            "commit to a branch.", (0, 15))
 
1843
        self.add_hook('post_uncommit',
1741
1844
            "Called in the bzr client after an uncommit completes. "
1742
1845
            "post_uncommit is called with (local, master, old_revno, "
1743
1846
            "old_revid, new_revno, new_revid) where local is the local branch "
1744
1847
            "or None, master is the target branch, and an empty branch "
1745
 
            "receives new_revno of 0, new_revid of None.", (0, 15), None))
1746
 
        self.create_hook(HookPoint('pre_change_branch_tip',
 
1848
            "receives new_revno of 0, new_revid of None.", (0, 15))
 
1849
        self.add_hook('pre_change_branch_tip',
1747
1850
            "Called in bzr client and server before a change to the tip of a "
1748
1851
            "branch is made. pre_change_branch_tip is called with a "
1749
1852
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1750
 
            "commit, uncommit will all trigger this hook.", (1, 6), None))
1751
 
        self.create_hook(HookPoint('post_change_branch_tip',
 
1853
            "commit, uncommit will all trigger this hook.", (1, 6))
 
1854
        self.add_hook('post_change_branch_tip',
1752
1855
            "Called in bzr client and server after a change to the tip of a "
1753
1856
            "branch is made. post_change_branch_tip is called with a "
1754
1857
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1755
 
            "commit, uncommit will all trigger this hook.", (1, 4), None))
1756
 
        self.create_hook(HookPoint('transform_fallback_location',
 
1858
            "commit, uncommit will all trigger this hook.", (1, 4))
 
1859
        self.add_hook('transform_fallback_location',
1757
1860
            "Called when a stacked branch is activating its fallback "
1758
1861
            "locations. transform_fallback_location is called with (branch, "
1759
1862
            "url), and should return a new url. Returning the same url "
1764
1867
            "fallback locations have not been activated. When there are "
1765
1868
            "multiple hooks installed for transform_fallback_location, "
1766
1869
            "all are called with the url returned from the previous hook."
1767
 
            "The order is however undefined.", (1, 9), None))
1768
 
        self.create_hook(HookPoint('automatic_tag_name',
1769
 
            "Called to determine an automatic tag name for a revision."
 
1870
            "The order is however undefined.", (1, 9))
 
1871
        self.add_hook('automatic_tag_name',
 
1872
            "Called to determine an automatic tag name for a revision. "
1770
1873
            "automatic_tag_name is called with (branch, revision_id) and "
1771
1874
            "should return a tag name or None if no tag name could be "
1772
1875
            "determined. The first non-None tag name returned will be used.",
1773
 
            (2, 2), None))
1774
 
        self.create_hook(HookPoint('post_branch_init',
 
1876
            (2, 2))
 
1877
        self.add_hook('post_branch_init',
1775
1878
            "Called after new branch initialization completes. "
1776
1879
            "post_branch_init is called with a "
1777
1880
            "bzrlib.branch.BranchInitHookParams. "
1778
1881
            "Note that init, branch and checkout (both heavyweight and "
1779
 
            "lightweight) will all trigger this hook.", (2, 2), None))
1780
 
        self.create_hook(HookPoint('post_switch',
 
1882
            "lightweight) will all trigger this hook.", (2, 2))
 
1883
        self.add_hook('post_switch',
1781
1884
            "Called after a checkout switches branch. "
1782
1885
            "post_switch is called with a "
1783
 
            "bzrlib.branch.SwitchHookParams.", (2, 2), None))
 
1886
            "bzrlib.branch.SwitchHookParams.", (2, 2))
1784
1887
 
1785
1888
 
1786
1889
 
1863
1966
        return self.__dict__ == other.__dict__
1864
1967
 
1865
1968
    def __repr__(self):
1866
 
        if self.branch:
1867
 
            return "<%s of %s>" % (self.__class__.__name__, self.branch)
1868
 
        else:
1869
 
            return "<%s of format:%s bzrdir:%s>" % (
1870
 
                self.__class__.__name__, self.branch,
1871
 
                self.format, self.bzrdir)
 
1969
        return "<%s of %s>" % (self.__class__.__name__, self.branch)
1872
1970
 
1873
1971
 
1874
1972
class SwitchHookParams(object):
1904
2002
            self.revision_id)
1905
2003
 
1906
2004
 
1907
 
class BzrBranchFormat4(BranchFormat):
1908
 
    """Bzr branch format 4.
1909
 
 
1910
 
    This format has:
1911
 
     - a revision-history file.
1912
 
     - a branch-lock lock file [ to be shared with the bzrdir ]
1913
 
    """
1914
 
 
1915
 
    def get_format_description(self):
1916
 
        """See BranchFormat.get_format_description()."""
1917
 
        return "Branch format 4"
1918
 
 
1919
 
    def initialize(self, a_bzrdir, name=None):
1920
 
        """Create a branch of this format in a_bzrdir."""
1921
 
        utf8_files = [('revision-history', ''),
1922
 
                      ('branch-name', ''),
1923
 
                      ]
1924
 
        return self._initialize_helper(a_bzrdir, utf8_files, name=name,
1925
 
                                       lock_type='branch4', set_format=False)
1926
 
 
1927
 
    def __init__(self):
1928
 
        super(BzrBranchFormat4, self).__init__()
1929
 
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
1930
 
 
1931
 
    def network_name(self):
1932
 
        """The network name for this format is the control dirs disk label."""
1933
 
        return self._matchingbzrdir.get_format_string()
1934
 
 
1935
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
1936
 
        """See BranchFormat.open()."""
1937
 
        if not _found:
1938
 
            # we are being called directly and must probe.
1939
 
            raise NotImplementedError
1940
 
        return BzrBranch(_format=self,
1941
 
                         _control_files=a_bzrdir._control_files,
1942
 
                         a_bzrdir=a_bzrdir,
1943
 
                         name=name,
1944
 
                         _repository=a_bzrdir.open_repository())
1945
 
 
1946
 
    def __str__(self):
1947
 
        return "Bazaar-NG branch format 4"
1948
 
 
1949
 
 
1950
2005
class BranchFormatMetadir(BranchFormat):
1951
2006
    """Common logic for meta-dir based branch formats."""
1952
2007
 
1954
2009
        """What class to instantiate on open calls."""
1955
2010
        raise NotImplementedError(self._branch_class)
1956
2011
 
 
2012
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
 
2013
                           repository=None):
 
2014
        """Initialize a branch in a bzrdir, with specified files
 
2015
 
 
2016
        :param a_bzrdir: The bzrdir to initialize the branch in
 
2017
        :param utf8_files: The files to create as a list of
 
2018
            (filename, content) tuples
 
2019
        :param name: Name of colocated branch to create, if any
 
2020
        :return: a branch in this format
 
2021
        """
 
2022
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
 
2023
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
2024
        control_files = lockable_files.LockableFiles(branch_transport,
 
2025
            'lock', lockdir.LockDir)
 
2026
        control_files.create_lock()
 
2027
        control_files.lock_write()
 
2028
        try:
 
2029
            utf8_files += [('format', self.get_format_string())]
 
2030
            for (filename, content) in utf8_files:
 
2031
                branch_transport.put_bytes(
 
2032
                    filename, content,
 
2033
                    mode=a_bzrdir._get_file_mode())
 
2034
        finally:
 
2035
            control_files.unlock()
 
2036
        branch = self.open(a_bzrdir, name, _found=True,
 
2037
                found_repository=repository)
 
2038
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
 
2039
        return branch
 
2040
 
1957
2041
    def network_name(self):
1958
2042
        """A simple byte string uniquely identifying this format for RPC calls.
1959
2043
 
1961
2045
        """
1962
2046
        return self.get_format_string()
1963
2047
 
1964
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
2048
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
 
2049
            found_repository=None):
1965
2050
        """See BranchFormat.open()."""
1966
2051
        if not _found:
1967
2052
            format = BranchFormat.find_format(a_bzrdir, name=name)
1972
2057
        try:
1973
2058
            control_files = lockable_files.LockableFiles(transport, 'lock',
1974
2059
                                                         lockdir.LockDir)
 
2060
            if found_repository is None:
 
2061
                found_repository = a_bzrdir.find_repository()
1975
2062
            return self._branch_class()(_format=self,
1976
2063
                              _control_files=control_files,
1977
2064
                              name=name,
1978
2065
                              a_bzrdir=a_bzrdir,
1979
 
                              _repository=a_bzrdir.find_repository(),
 
2066
                              _repository=found_repository,
1980
2067
                              ignore_fallbacks=ignore_fallbacks)
1981
2068
        except errors.NoSuchFile:
1982
2069
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1989
2076
    def supports_tags(self):
1990
2077
        return True
1991
2078
 
 
2079
    def supports_leaving_lock(self):
 
2080
        return True
 
2081
 
1992
2082
 
1993
2083
class BzrBranchFormat5(BranchFormatMetadir):
1994
2084
    """Bzr branch format 5.
2014
2104
        """See BranchFormat.get_format_description()."""
2015
2105
        return "Branch format 5"
2016
2106
 
2017
 
    def initialize(self, a_bzrdir, name=None):
 
2107
    def initialize(self, a_bzrdir, name=None, repository=None):
2018
2108
        """Create a branch of this format in a_bzrdir."""
2019
2109
        utf8_files = [('revision-history', ''),
2020
2110
                      ('branch-name', ''),
2021
2111
                      ]
2022
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2112
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2023
2113
 
2024
2114
    def supports_tags(self):
2025
2115
        return False
2047
2137
        """See BranchFormat.get_format_description()."""
2048
2138
        return "Branch format 6"
2049
2139
 
2050
 
    def initialize(self, a_bzrdir, name=None):
 
2140
    def initialize(self, a_bzrdir, name=None, repository=None):
2051
2141
        """Create a branch of this format in a_bzrdir."""
2052
2142
        utf8_files = [('last-revision', '0 null:\n'),
2053
2143
                      ('branch.conf', ''),
2054
2144
                      ('tags', ''),
2055
2145
                      ]
2056
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2146
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2057
2147
 
2058
2148
    def make_tags(self, branch):
2059
2149
        """See bzrlib.branch.BranchFormat.make_tags()."""
2077
2167
        """See BranchFormat.get_format_description()."""
2078
2168
        return "Branch format 8"
2079
2169
 
2080
 
    def initialize(self, a_bzrdir, name=None):
 
2170
    def initialize(self, a_bzrdir, name=None, repository=None):
2081
2171
        """Create a branch of this format in a_bzrdir."""
2082
2172
        utf8_files = [('last-revision', '0 null:\n'),
2083
2173
                      ('branch.conf', ''),
2084
2174
                      ('tags', ''),
2085
2175
                      ('references', '')
2086
2176
                      ]
2087
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
2088
 
 
2089
 
    def __init__(self):
2090
 
        super(BzrBranchFormat8, self).__init__()
2091
 
        self._matchingbzrdir.repository_format = \
2092
 
            RepositoryFormatKnitPack5RichRoot()
 
2177
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2093
2178
 
2094
2179
    def make_tags(self, branch):
2095
2180
        """See bzrlib.branch.BranchFormat.make_tags()."""
2104
2189
    supports_reference_locations = True
2105
2190
 
2106
2191
 
2107
 
class BzrBranchFormat7(BzrBranchFormat8):
 
2192
class BzrBranchFormat7(BranchFormatMetadir):
2108
2193
    """Branch format with last-revision, tags, and a stacked location pointer.
2109
2194
 
2110
2195
    The stacked location pointer is passed down to the repository and requires
2113
2198
    This format was introduced in bzr 1.6.
2114
2199
    """
2115
2200
 
2116
 
    def initialize(self, a_bzrdir, name=None):
 
2201
    def initialize(self, a_bzrdir, name=None, repository=None):
2117
2202
        """Create a branch of this format in a_bzrdir."""
2118
2203
        utf8_files = [('last-revision', '0 null:\n'),
2119
2204
                      ('branch.conf', ''),
2120
2205
                      ('tags', ''),
2121
2206
                      ]
2122
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2207
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2123
2208
 
2124
2209
    def _branch_class(self):
2125
2210
        return BzrBranch7
2135
2220
    def supports_set_append_revisions_only(self):
2136
2221
        return True
2137
2222
 
 
2223
    def supports_stacking(self):
 
2224
        return True
 
2225
 
 
2226
    def make_tags(self, branch):
 
2227
        """See bzrlib.branch.BranchFormat.make_tags()."""
 
2228
        return BasicTags(branch)
 
2229
 
2138
2230
    supports_reference_locations = False
2139
2231
 
2140
2232
 
2157
2249
        """See BranchFormat.get_format_description()."""
2158
2250
        return "Checkout reference format 1"
2159
2251
 
2160
 
    def get_reference(self, a_bzrdir):
 
2252
    def get_reference(self, a_bzrdir, name=None):
2161
2253
        """See BranchFormat.get_reference()."""
2162
 
        transport = a_bzrdir.get_branch_transport(None)
 
2254
        transport = a_bzrdir.get_branch_transport(None, name=name)
2163
2255
        return transport.get_bytes('location')
2164
2256
 
2165
 
    def set_reference(self, a_bzrdir, to_branch):
 
2257
    def set_reference(self, a_bzrdir, name, to_branch):
2166
2258
        """See BranchFormat.set_reference()."""
2167
 
        transport = a_bzrdir.get_branch_transport(None)
 
2259
        transport = a_bzrdir.get_branch_transport(None, name=name)
2168
2260
        location = transport.put_bytes('location', to_branch.base)
2169
2261
 
2170
 
    def initialize(self, a_bzrdir, name=None, target_branch=None):
 
2262
    def initialize(self, a_bzrdir, name=None, target_branch=None,
 
2263
            repository=None):
2171
2264
        """Create a branch of this format in a_bzrdir."""
2172
2265
        if target_branch is None:
2173
2266
            # this format does not implement branch itself, thus the implicit
2201
2294
        return clone
2202
2295
 
2203
2296
    def open(self, a_bzrdir, name=None, _found=False, location=None,
2204
 
             possible_transports=None, ignore_fallbacks=False):
 
2297
             possible_transports=None, ignore_fallbacks=False,
 
2298
             found_repository=None):
2205
2299
        """Return the branch that the branch reference in a_bzrdir points at.
2206
2300
 
2207
2301
        :param a_bzrdir: A BzrDir that contains a branch.
2221
2315
                raise AssertionError("wrong format %r found for %r" %
2222
2316
                    (format, self))
2223
2317
        if location is None:
2224
 
            location = self.get_reference(a_bzrdir)
 
2318
            location = self.get_reference(a_bzrdir, name)
2225
2319
        real_bzrdir = bzrdir.BzrDir.open(
2226
2320
            location, possible_transports=possible_transports)
2227
2321
        result = real_bzrdir.open_branch(name=name, 
2238
2332
        return result
2239
2333
 
2240
2334
 
 
2335
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
 
2336
    """Branch format registry."""
 
2337
 
 
2338
    def __init__(self, other_registry=None):
 
2339
        super(BranchFormatRegistry, self).__init__(other_registry)
 
2340
        self._default_format = None
 
2341
 
 
2342
    def set_default(self, format):
 
2343
        self._default_format = format
 
2344
 
 
2345
    def get_default(self):
 
2346
        return self._default_format
 
2347
 
 
2348
 
2241
2349
network_format_registry = registry.FormatRegistry()
2242
2350
"""Registry of formats indexed by their network name.
2243
2351
 
2246
2354
BranchFormat.network_name() for more detail.
2247
2355
"""
2248
2356
 
 
2357
format_registry = BranchFormatRegistry(network_format_registry)
 
2358
 
2249
2359
 
2250
2360
# formats which have no format string are not discoverable
2251
2361
# and not independently creatable, so are not registered.
2253
2363
__format6 = BzrBranchFormat6()
2254
2364
__format7 = BzrBranchFormat7()
2255
2365
__format8 = BzrBranchFormat8()
2256
 
BranchFormat.register_format(__format5)
2257
 
BranchFormat.register_format(BranchReferenceFormat())
2258
 
BranchFormat.register_format(__format6)
2259
 
BranchFormat.register_format(__format7)
2260
 
BranchFormat.register_format(__format8)
2261
 
BranchFormat.set_default_format(__format7)
2262
 
_legacy_formats = [BzrBranchFormat4(),
2263
 
    ]
2264
 
network_format_registry.register(
2265
 
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
 
2366
format_registry.register(__format5)
 
2367
format_registry.register(BranchReferenceFormat())
 
2368
format_registry.register(__format6)
 
2369
format_registry.register(__format7)
 
2370
format_registry.register(__format8)
 
2371
format_registry.set_default(__format7)
 
2372
 
 
2373
 
 
2374
class BranchWriteLockResult(LogicalLockResult):
 
2375
    """The result of write locking a branch.
 
2376
 
 
2377
    :ivar branch_token: The token obtained from the underlying branch lock, or
 
2378
        None.
 
2379
    :ivar unlock: A callable which will unlock the lock.
 
2380
    """
 
2381
 
 
2382
    def __init__(self, unlock, branch_token):
 
2383
        LogicalLockResult.__init__(self, unlock)
 
2384
        self.branch_token = branch_token
 
2385
 
 
2386
    def __repr__(self):
 
2387
        return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
 
2388
            self.unlock)
2266
2389
 
2267
2390
 
2268
2391
class BzrBranch(Branch, _RelockDebugMixin):
2324
2447
        return self.control_files.is_locked()
2325
2448
 
2326
2449
    def lock_write(self, token=None):
 
2450
        """Lock the branch for write operations.
 
2451
 
 
2452
        :param token: A token to permit reacquiring a previously held and
 
2453
            preserved lock.
 
2454
        :return: A BranchWriteLockResult.
 
2455
        """
2327
2456
        if not self.is_locked():
2328
2457
            self._note_lock('w')
2329
2458
        # All-in-one needs to always unlock/lock.
2335
2464
        else:
2336
2465
            took_lock = False
2337
2466
        try:
2338
 
            return self.control_files.lock_write(token=token)
 
2467
            return BranchWriteLockResult(self.unlock,
 
2468
                self.control_files.lock_write(token=token))
2339
2469
        except:
2340
2470
            if took_lock:
2341
2471
                self.repository.unlock()
2342
2472
            raise
2343
2473
 
2344
2474
    def lock_read(self):
 
2475
        """Lock the branch for read operations.
 
2476
 
 
2477
        :return: A bzrlib.lock.LogicalLockResult.
 
2478
        """
2345
2479
        if not self.is_locked():
2346
2480
            self._note_lock('r')
2347
2481
        # All-in-one needs to always unlock/lock.
2354
2488
            took_lock = False
2355
2489
        try:
2356
2490
            self.control_files.lock_read()
 
2491
            return LogicalLockResult(self.unlock)
2357
2492
        except:
2358
2493
            if took_lock:
2359
2494
                self.repository.unlock()
2387
2522
        """See Branch.print_file."""
2388
2523
        return self.repository.print_file(file, revision_id)
2389
2524
 
2390
 
    def _write_revision_history(self, history):
2391
 
        """Factored out of set_revision_history.
2392
 
 
2393
 
        This performs the actual writing to disk.
2394
 
        It is intended to be called by BzrBranch5.set_revision_history."""
2395
 
        self._transport.put_bytes(
2396
 
            'revision-history', '\n'.join(history),
2397
 
            mode=self.bzrdir._get_file_mode())
2398
 
 
2399
 
    @needs_write_lock
2400
 
    def set_revision_history(self, rev_history):
2401
 
        """See Branch.set_revision_history."""
2402
 
        if 'evil' in debug.debug_flags:
2403
 
            mutter_callsite(3, "set_revision_history scales with history.")
2404
 
        check_not_reserved_id = _mod_revision.check_not_reserved_id
2405
 
        for rev_id in rev_history:
2406
 
            check_not_reserved_id(rev_id)
2407
 
        if Branch.hooks['post_change_branch_tip']:
2408
 
            # Don't calculate the last_revision_info() if there are no hooks
2409
 
            # that will use it.
2410
 
            old_revno, old_revid = self.last_revision_info()
2411
 
        if len(rev_history) == 0:
2412
 
            revid = _mod_revision.NULL_REVISION
2413
 
        else:
2414
 
            revid = rev_history[-1]
2415
 
        self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
2416
 
        self._write_revision_history(rev_history)
2417
 
        self._clear_cached_state()
2418
 
        self._cache_revision_history(rev_history)
2419
 
        for hook in Branch.hooks['set_rh']:
2420
 
            hook(self, rev_history)
2421
 
        if Branch.hooks['post_change_branch_tip']:
2422
 
            self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2423
 
 
2424
 
    def _synchronize_history(self, destination, revision_id):
2425
 
        """Synchronize last revision and revision history between branches.
2426
 
 
2427
 
        This version is most efficient when the destination is also a
2428
 
        BzrBranch5, but works for BzrBranch6 as long as the revision
2429
 
        history is the true lefthand parent history, and all of the revisions
2430
 
        are in the destination's repository.  If not, set_revision_history
2431
 
        will fail.
2432
 
 
2433
 
        :param destination: The branch to copy the history into
2434
 
        :param revision_id: The revision-id to truncate history at.  May
2435
 
          be None to copy complete history.
2436
 
        """
2437
 
        if not isinstance(destination._format, BzrBranchFormat5):
2438
 
            super(BzrBranch, self)._synchronize_history(
2439
 
                destination, revision_id)
2440
 
            return
2441
 
        if revision_id == _mod_revision.NULL_REVISION:
2442
 
            new_history = []
2443
 
        else:
2444
 
            new_history = self.revision_history()
2445
 
        if revision_id is not None and new_history != []:
2446
 
            try:
2447
 
                new_history = new_history[:new_history.index(revision_id) + 1]
2448
 
            except ValueError:
2449
 
                rev = self.repository.get_revision(revision_id)
2450
 
                new_history = rev.get_history(self.repository)[1:]
2451
 
        destination.set_revision_history(new_history)
2452
 
 
2453
2525
    @needs_write_lock
2454
2526
    def set_last_revision_info(self, revno, revision_id):
2455
 
        """Set the last revision of this branch.
2456
 
 
2457
 
        The caller is responsible for checking that the revno is correct
2458
 
        for this revision id.
2459
 
 
2460
 
        It may be possible to set the branch last revision to an id not
2461
 
        present in the repository.  However, branches can also be
2462
 
        configured to check constraints on history, in which case this may not
2463
 
        be permitted.
2464
 
        """
 
2527
        if not revision_id or not isinstance(revision_id, basestring):
 
2528
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2465
2529
        revision_id = _mod_revision.ensure_null(revision_id)
2466
 
        # this old format stores the full history, but this api doesn't
2467
 
        # provide it, so we must generate, and might as well check it's
2468
 
        # correct
2469
 
        history = self._lefthand_history(revision_id)
2470
 
        if len(history) != revno:
2471
 
            raise AssertionError('%d != %d' % (len(history), revno))
2472
 
        self.set_revision_history(history)
2473
 
 
2474
 
    def _gen_revision_history(self):
2475
 
        history = self._transport.get_bytes('revision-history').split('\n')
2476
 
        if history[-1:] == ['']:
2477
 
            # There shouldn't be a trailing newline, but just in case.
2478
 
            history.pop()
2479
 
        return history
2480
 
 
2481
 
    @needs_write_lock
2482
 
    def generate_revision_history(self, revision_id, last_rev=None,
2483
 
        other_branch=None):
2484
 
        """Create a new revision history that will finish with revision_id.
2485
 
 
2486
 
        :param revision_id: the new tip to use.
2487
 
        :param last_rev: The previous last_revision. If not None, then this
2488
 
            must be a ancestory of revision_id, or DivergedBranches is raised.
2489
 
        :param other_branch: The other branch that DivergedBranches should
2490
 
            raise with respect to.
2491
 
        """
2492
 
        self.set_revision_history(self._lefthand_history(revision_id,
2493
 
            last_rev, other_branch))
 
2530
        old_revno, old_revid = self.last_revision_info()
 
2531
        if self._get_append_revisions_only():
 
2532
            self._check_history_violation(revision_id)
 
2533
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
 
2534
        self._write_last_revision_info(revno, revision_id)
 
2535
        self._clear_cached_state()
 
2536
        self._last_revision_info_cache = revno, revision_id
 
2537
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2494
2538
 
2495
2539
    def basis_tree(self):
2496
2540
        """See Branch.basis_tree."""
2515
2559
        result.target_branch = target
2516
2560
        result.old_revno, result.old_revid = target.last_revision_info()
2517
2561
        self.update_references(target)
2518
 
        if result.old_revid != self.last_revision():
 
2562
        if result.old_revid != stop_revision:
2519
2563
            # We assume that during 'push' this repository is closer than
2520
2564
            # the target.
2521
2565
            graph = self.repository.get_graph(target.repository)
2522
2566
            target.update_revisions(self, stop_revision,
2523
2567
                overwrite=overwrite, graph=graph)
2524
2568
        if self._push_should_merge_tags():
2525
 
            result.tag_conflicts = self.tags.merge_to(target.tags,
2526
 
                overwrite)
 
2569
            result.tag_conflicts = self.tags.merge_to(target.tags, overwrite)
2527
2570
        result.new_revno, result.new_revid = target.last_revision_info()
2528
2571
        return result
2529
2572
 
2543
2586
            self._transport.put_bytes('parent', url + '\n',
2544
2587
                mode=self.bzrdir._get_file_mode())
2545
2588
 
2546
 
 
2547
 
class BzrBranch5(BzrBranch):
2548
 
    """A format 5 branch. This supports new features over plain branches.
2549
 
 
2550
 
    It has support for a master_branch which is the data for bound branches.
2551
 
    """
2552
 
 
2553
 
    def get_bound_location(self):
2554
 
        try:
2555
 
            return self._transport.get_bytes('bound')[:-1]
2556
 
        except errors.NoSuchFile:
2557
 
            return None
2558
 
 
2559
 
    @needs_read_lock
2560
 
    def get_master_branch(self, possible_transports=None):
2561
 
        """Return the branch we are bound to.
2562
 
 
2563
 
        :return: Either a Branch, or None
2564
 
 
2565
 
        This could memoise the branch, but if thats done
2566
 
        it must be revalidated on each new lock.
2567
 
        So for now we just don't memoise it.
2568
 
        # RBC 20060304 review this decision.
2569
 
        """
2570
 
        bound_loc = self.get_bound_location()
2571
 
        if not bound_loc:
2572
 
            return None
2573
 
        try:
2574
 
            return Branch.open(bound_loc,
2575
 
                               possible_transports=possible_transports)
2576
 
        except (errors.NotBranchError, errors.ConnectionError), e:
2577
 
            raise errors.BoundBranchConnectionFailure(
2578
 
                    self, bound_loc, e)
2579
 
 
2580
2589
    @needs_write_lock
2581
 
    def set_bound_location(self, location):
2582
 
        """Set the target where this branch is bound to.
2583
 
 
2584
 
        :param location: URL to the target branch
2585
 
        """
2586
 
        if location:
2587
 
            self._transport.put_bytes('bound', location+'\n',
2588
 
                mode=self.bzrdir._get_file_mode())
2589
 
        else:
2590
 
            try:
2591
 
                self._transport.delete('bound')
2592
 
            except errors.NoSuchFile:
2593
 
                return False
2594
 
            return True
 
2590
    def unbind(self):
 
2591
        """If bound, unbind"""
 
2592
        return self.set_bound_location(None)
2595
2593
 
2596
2594
    @needs_write_lock
2597
2595
    def bind(self, other):
2619
2617
        # history around
2620
2618
        self.set_bound_location(other.base)
2621
2619
 
 
2620
    def get_bound_location(self):
 
2621
        try:
 
2622
            return self._transport.get_bytes('bound')[:-1]
 
2623
        except errors.NoSuchFile:
 
2624
            return None
 
2625
 
 
2626
    @needs_read_lock
 
2627
    def get_master_branch(self, possible_transports=None):
 
2628
        """Return the branch we are bound to.
 
2629
 
 
2630
        :return: Either a Branch, or None
 
2631
        """
 
2632
        if self._master_branch_cache is None:
 
2633
            self._master_branch_cache = self._get_master_branch(
 
2634
                possible_transports)
 
2635
        return self._master_branch_cache
 
2636
 
 
2637
    def _get_master_branch(self, possible_transports):
 
2638
        bound_loc = self.get_bound_location()
 
2639
        if not bound_loc:
 
2640
            return None
 
2641
        try:
 
2642
            return Branch.open(bound_loc,
 
2643
                               possible_transports=possible_transports)
 
2644
        except (errors.NotBranchError, errors.ConnectionError), e:
 
2645
            raise errors.BoundBranchConnectionFailure(
 
2646
                    self, bound_loc, e)
 
2647
 
2622
2648
    @needs_write_lock
2623
 
    def unbind(self):
2624
 
        """If bound, unbind"""
2625
 
        return self.set_bound_location(None)
 
2649
    def set_bound_location(self, location):
 
2650
        """Set the target where this branch is bound to.
 
2651
 
 
2652
        :param location: URL to the target branch
 
2653
        """
 
2654
        self._master_branch_cache = None
 
2655
        if location:
 
2656
            self._transport.put_bytes('bound', location+'\n',
 
2657
                mode=self.bzrdir._get_file_mode())
 
2658
        else:
 
2659
            try:
 
2660
                self._transport.delete('bound')
 
2661
            except errors.NoSuchFile:
 
2662
                return False
 
2663
            return True
2626
2664
 
2627
2665
    @needs_write_lock
2628
2666
    def update(self, possible_transports=None):
2641
2679
            return old_tip
2642
2680
        return None
2643
2681
 
2644
 
 
2645
 
class BzrBranch8(BzrBranch5):
 
2682
    def _read_last_revision_info(self):
 
2683
        revision_string = self._transport.get_bytes('last-revision')
 
2684
        revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
 
2685
        revision_id = cache_utf8.get_cached_utf8(revision_id)
 
2686
        revno = int(revno)
 
2687
        return revno, revision_id
 
2688
 
 
2689
    def _write_last_revision_info(self, revno, revision_id):
 
2690
        """Simply write out the revision id, with no checks.
 
2691
 
 
2692
        Use set_last_revision_info to perform this safely.
 
2693
 
 
2694
        Does not update the revision_history cache.
 
2695
        """
 
2696
        revision_id = _mod_revision.ensure_null(revision_id)
 
2697
        out_string = '%d %s\n' % (revno, revision_id)
 
2698
        self._transport.put_bytes('last-revision', out_string,
 
2699
            mode=self.bzrdir._get_file_mode())
 
2700
 
 
2701
 
 
2702
class FullHistoryBzrBranch(BzrBranch):
 
2703
    """Bzr branch which contains the full revision history."""
 
2704
 
 
2705
    @needs_write_lock
 
2706
    def set_last_revision_info(self, revno, revision_id):
 
2707
        if not revision_id or not isinstance(revision_id, basestring):
 
2708
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
 
2709
        revision_id = _mod_revision.ensure_null(revision_id)
 
2710
        # this old format stores the full history, but this api doesn't
 
2711
        # provide it, so we must generate, and might as well check it's
 
2712
        # correct
 
2713
        history = self._lefthand_history(revision_id)
 
2714
        if len(history) != revno:
 
2715
            raise AssertionError('%d != %d' % (len(history), revno))
 
2716
        self._set_revision_history(history)
 
2717
 
 
2718
    def _read_last_revision_info(self):
 
2719
        rh = self.revision_history()
 
2720
        revno = len(rh)
 
2721
        if revno:
 
2722
            return (revno, rh[-1])
 
2723
        else:
 
2724
            return (0, _mod_revision.NULL_REVISION)
 
2725
 
 
2726
    @deprecated_method(deprecated_in((2, 4, 0)))
 
2727
    @needs_write_lock
 
2728
    def set_revision_history(self, rev_history):
 
2729
        """See Branch.set_revision_history."""
 
2730
        self._set_revision_history(rev_history)
 
2731
 
 
2732
    def _set_revision_history(self, rev_history):
 
2733
        if 'evil' in debug.debug_flags:
 
2734
            mutter_callsite(3, "set_revision_history scales with history.")
 
2735
        check_not_reserved_id = _mod_revision.check_not_reserved_id
 
2736
        for rev_id in rev_history:
 
2737
            check_not_reserved_id(rev_id)
 
2738
        if Branch.hooks['post_change_branch_tip']:
 
2739
            # Don't calculate the last_revision_info() if there are no hooks
 
2740
            # that will use it.
 
2741
            old_revno, old_revid = self.last_revision_info()
 
2742
        if len(rev_history) == 0:
 
2743
            revid = _mod_revision.NULL_REVISION
 
2744
        else:
 
2745
            revid = rev_history[-1]
 
2746
        self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
 
2747
        self._write_revision_history(rev_history)
 
2748
        self._clear_cached_state()
 
2749
        self._cache_revision_history(rev_history)
 
2750
        for hook in Branch.hooks['set_rh']:
 
2751
            hook(self, rev_history)
 
2752
        if Branch.hooks['post_change_branch_tip']:
 
2753
            self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2754
 
 
2755
    def _write_revision_history(self, history):
 
2756
        """Factored out of set_revision_history.
 
2757
 
 
2758
        This performs the actual writing to disk.
 
2759
        It is intended to be called by set_revision_history."""
 
2760
        self._transport.put_bytes(
 
2761
            'revision-history', '\n'.join(history),
 
2762
            mode=self.bzrdir._get_file_mode())
 
2763
 
 
2764
    def _gen_revision_history(self):
 
2765
        history = self._transport.get_bytes('revision-history').split('\n')
 
2766
        if history[-1:] == ['']:
 
2767
            # There shouldn't be a trailing newline, but just in case.
 
2768
            history.pop()
 
2769
        return history
 
2770
 
 
2771
    def _synchronize_history(self, destination, revision_id):
 
2772
        if not isinstance(destination, FullHistoryBzrBranch):
 
2773
            super(BzrBranch, self)._synchronize_history(
 
2774
                destination, revision_id)
 
2775
            return
 
2776
        if revision_id == _mod_revision.NULL_REVISION:
 
2777
            new_history = []
 
2778
        else:
 
2779
            new_history = self.revision_history()
 
2780
        if revision_id is not None and new_history != []:
 
2781
            try:
 
2782
                new_history = new_history[:new_history.index(revision_id) + 1]
 
2783
            except ValueError:
 
2784
                rev = self.repository.get_revision(revision_id)
 
2785
                new_history = rev.get_history(self.repository)[1:]
 
2786
        destination._set_revision_history(new_history)
 
2787
 
 
2788
    @needs_write_lock
 
2789
    def generate_revision_history(self, revision_id, last_rev=None,
 
2790
        other_branch=None):
 
2791
        """Create a new revision history that will finish with revision_id.
 
2792
 
 
2793
        :param revision_id: the new tip to use.
 
2794
        :param last_rev: The previous last_revision. If not None, then this
 
2795
            must be a ancestory of revision_id, or DivergedBranches is raised.
 
2796
        :param other_branch: The other branch that DivergedBranches should
 
2797
            raise with respect to.
 
2798
        """
 
2799
        self._set_revision_history(self._lefthand_history(revision_id,
 
2800
            last_rev, other_branch))
 
2801
 
 
2802
 
 
2803
class BzrBranch5(FullHistoryBzrBranch):
 
2804
    """A format 5 branch. This supports new features over plain branches.
 
2805
 
 
2806
    It has support for a master_branch which is the data for bound branches.
 
2807
    """
 
2808
 
 
2809
 
 
2810
class BzrBranch8(BzrBranch):
2646
2811
    """A branch that stores tree-reference locations."""
2647
2812
 
2648
2813
    def _open_hook(self):
2674
2839
        self._last_revision_info_cache = None
2675
2840
        self._reference_info = None
2676
2841
 
2677
 
    def _last_revision_info(self):
2678
 
        revision_string = self._transport.get_bytes('last-revision')
2679
 
        revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
2680
 
        revision_id = cache_utf8.get_cached_utf8(revision_id)
2681
 
        revno = int(revno)
2682
 
        return revno, revision_id
2683
 
 
2684
 
    def _write_last_revision_info(self, revno, revision_id):
2685
 
        """Simply write out the revision id, with no checks.
2686
 
 
2687
 
        Use set_last_revision_info to perform this safely.
2688
 
 
2689
 
        Does not update the revision_history cache.
2690
 
        Intended to be called by set_last_revision_info and
2691
 
        _write_revision_history.
2692
 
        """
2693
 
        revision_id = _mod_revision.ensure_null(revision_id)
2694
 
        out_string = '%d %s\n' % (revno, revision_id)
2695
 
        self._transport.put_bytes('last-revision', out_string,
2696
 
            mode=self.bzrdir._get_file_mode())
2697
 
 
2698
 
    @needs_write_lock
2699
 
    def set_last_revision_info(self, revno, revision_id):
2700
 
        revision_id = _mod_revision.ensure_null(revision_id)
2701
 
        old_revno, old_revid = self.last_revision_info()
2702
 
        if self._get_append_revisions_only():
2703
 
            self._check_history_violation(revision_id)
2704
 
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
2705
 
        self._write_last_revision_info(revno, revision_id)
2706
 
        self._clear_cached_state()
2707
 
        self._last_revision_info_cache = revno, revision_id
2708
 
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2709
 
 
2710
 
    def _synchronize_history(self, destination, revision_id):
2711
 
        """Synchronize last revision and revision history between branches.
2712
 
 
2713
 
        :see: Branch._synchronize_history
2714
 
        """
2715
 
        # XXX: The base Branch has a fast implementation of this method based
2716
 
        # on set_last_revision_info, but BzrBranch/BzrBranch5 have a slower one
2717
 
        # that uses set_revision_history.  This class inherits from BzrBranch5,
2718
 
        # but wants the fast implementation, so it calls
2719
 
        # Branch._synchronize_history directly.
2720
 
        Branch._synchronize_history(self, destination, revision_id)
2721
 
 
2722
2842
    def _check_history_violation(self, revision_id):
2723
2843
        last_revision = _mod_revision.ensure_null(self.last_revision())
2724
2844
        if _mod_revision.is_null(last_revision):
2733
2853
        self._extend_partial_history(stop_index=last_revno-1)
2734
2854
        return list(reversed(self._partial_revision_history_cache))
2735
2855
 
2736
 
    def _write_revision_history(self, history):
2737
 
        """Factored out of set_revision_history.
2738
 
 
2739
 
        This performs the actual writing to disk, with format-specific checks.
2740
 
        It is intended to be called by BzrBranch5.set_revision_history.
2741
 
        """
2742
 
        if len(history) == 0:
2743
 
            last_revision = 'null:'
2744
 
        else:
2745
 
            if history != self._lefthand_history(history[-1]):
2746
 
                raise errors.NotLefthandHistory(history)
2747
 
            last_revision = history[-1]
2748
 
        if self._get_append_revisions_only():
2749
 
            self._check_history_violation(last_revision)
2750
 
        self._write_last_revision_info(len(history), last_revision)
2751
 
 
2752
2856
    @needs_write_lock
2753
2857
    def _set_parent_location(self, url):
2754
2858
        """Set the parent branch"""
2840
2944
 
2841
2945
    def set_bound_location(self, location):
2842
2946
        """See Branch.set_push_location."""
 
2947
        self._master_branch_cache = None
2843
2948
        result = None
2844
2949
        config = self.get_config()
2845
2950
        if location is None:
2885
2990
        return self.get_config(
2886
2991
            ).get_user_option_as_bool('append_revisions_only')
2887
2992
 
2888
 
    @needs_write_lock
2889
 
    def generate_revision_history(self, revision_id, last_rev=None,
2890
 
                                  other_branch=None):
2891
 
        """See BzrBranch5.generate_revision_history"""
2892
 
        history = self._lefthand_history(revision_id, last_rev, other_branch)
2893
 
        revno = len(history)
2894
 
        self.set_last_revision_info(revno, revision_id)
2895
 
 
2896
2993
    @needs_read_lock
2897
2994
    def get_rev_id(self, revno, history=None):
2898
2995
        """Find the revision id of the specified revno."""
2922
3019
        try:
2923
3020
            index = self._partial_revision_history_cache.index(revision_id)
2924
3021
        except ValueError:
2925
 
            self._extend_partial_history(stop_revision=revision_id)
 
3022
            try:
 
3023
                self._extend_partial_history(stop_revision=revision_id)
 
3024
            except errors.RevisionNotPresent, e:
 
3025
                raise errors.GhostRevisionsHaveNoRevno(revision_id, e.revision_id)
2926
3026
            index = len(self._partial_revision_history_cache) - 1
2927
3027
            if self._partial_revision_history_cache[index] != revision_id:
2928
3028
                raise errors.NoSuchRevision(self, revision_id)
2983
3083
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
2984
3084
    """
2985
3085
 
 
3086
    @deprecated_method(deprecated_in((2, 3, 0)))
2986
3087
    def __int__(self):
2987
 
        # DEPRECATED: pull used to return the change in revno
 
3088
        """Return the relative change in revno.
 
3089
 
 
3090
        :deprecated: Use `new_revno` and `old_revno` instead.
 
3091
        """
2988
3092
        return self.new_revno - self.old_revno
2989
3093
 
2990
3094
    def report(self, to_file):
3015
3119
        target, otherwise it will be None.
3016
3120
    """
3017
3121
 
 
3122
    @deprecated_method(deprecated_in((2, 3, 0)))
3018
3123
    def __int__(self):
3019
 
        # DEPRECATED: push used to return the change in revno
 
3124
        """Return the relative change in revno.
 
3125
 
 
3126
        :deprecated: Use `new_revno` and `old_revno` instead.
 
3127
        """
3020
3128
        return self.new_revno - self.old_revno
3021
3129
 
3022
3130
    def report(self, to_file):
3145
3253
    _optimisers = []
3146
3254
    """The available optimised InterBranch types."""
3147
3255
 
3148
 
    @staticmethod
3149
 
    def _get_branch_formats_to_test():
3150
 
        """Return a tuple with the Branch formats to use when testing."""
3151
 
        raise NotImplementedError(InterBranch._get_branch_formats_to_test)
 
3256
    @classmethod
 
3257
    def _get_branch_formats_to_test(klass):
 
3258
        """Return an iterable of format tuples for testing.
 
3259
        
 
3260
        :return: An iterable of (from_format, to_format) to use when testing
 
3261
            this InterBranch class. Each InterBranch class should define this
 
3262
            method itself.
 
3263
        """
 
3264
        raise NotImplementedError(klass._get_branch_formats_to_test)
3152
3265
 
 
3266
    @needs_write_lock
3153
3267
    def pull(self, overwrite=False, stop_revision=None,
3154
3268
             possible_transports=None, local=False):
3155
3269
        """Mirror source into target branch.
3160
3274
        """
3161
3275
        raise NotImplementedError(self.pull)
3162
3276
 
 
3277
    @needs_write_lock
3163
3278
    def update_revisions(self, stop_revision=None, overwrite=False,
3164
 
                         graph=None):
 
3279
            graph=None):
3165
3280
        """Pull in new perfect-fit revisions.
3166
3281
 
3167
3282
        :param stop_revision: Updated until the given revision
3173
3288
        """
3174
3289
        raise NotImplementedError(self.update_revisions)
3175
3290
 
 
3291
    @needs_write_lock
3176
3292
    def push(self, overwrite=False, stop_revision=None,
3177
3293
             _override_hook_source_branch=None):
3178
3294
        """Mirror the source branch into the target branch.
3181
3297
        """
3182
3298
        raise NotImplementedError(self.push)
3183
3299
 
 
3300
    @needs_write_lock
 
3301
    def copy_content_into(self, revision_id=None):
 
3302
        """Copy the content of source into target
 
3303
 
 
3304
        revision_id: if not None, the revision history in the new branch will
 
3305
                     be truncated to end with revision_id.
 
3306
        """
 
3307
        raise NotImplementedError(self.copy_content_into)
 
3308
 
 
3309
    @needs_write_lock
 
3310
    def fetch(self, stop_revision=None):
 
3311
        """Fetch revisions.
 
3312
 
 
3313
        :param stop_revision: Last revision to fetch
 
3314
        """
 
3315
        raise NotImplementedError(self.fetch)
 
3316
 
3184
3317
 
3185
3318
class GenericInterBranch(InterBranch):
3186
 
    """InterBranch implementation that uses public Branch functions.
3187
 
    """
3188
 
 
3189
 
    @staticmethod
3190
 
    def _get_branch_formats_to_test():
3191
 
        return BranchFormat._default_format, BranchFormat._default_format
3192
 
 
 
3319
    """InterBranch implementation that uses public Branch functions."""
 
3320
 
 
3321
    @classmethod
 
3322
    def is_compatible(klass, source, target):
 
3323
        # GenericBranch uses the public API, so always compatible
 
3324
        return True
 
3325
 
 
3326
    @classmethod
 
3327
    def _get_branch_formats_to_test(klass):
 
3328
        return [(format_registry.get_default(), format_registry.get_default())]
 
3329
 
 
3330
    @classmethod
 
3331
    def unwrap_format(klass, format):
 
3332
        if isinstance(format, remote.RemoteBranchFormat):
 
3333
            format._ensure_real()
 
3334
            return format._custom_format
 
3335
        return format
 
3336
 
 
3337
    @needs_write_lock
 
3338
    def copy_content_into(self, revision_id=None):
 
3339
        """Copy the content of source into target
 
3340
 
 
3341
        revision_id: if not None, the revision history in the new branch will
 
3342
                     be truncated to end with revision_id.
 
3343
        """
 
3344
        self.source.update_references(self.target)
 
3345
        self.source._synchronize_history(self.target, revision_id)
 
3346
        try:
 
3347
            parent = self.source.get_parent()
 
3348
        except errors.InaccessibleParent, e:
 
3349
            mutter('parent was not accessible to copy: %s', e)
 
3350
        else:
 
3351
            if parent:
 
3352
                self.target.set_parent(parent)
 
3353
        if self.source._push_should_merge_tags():
 
3354
            self.source.tags.merge_to(self.target.tags)
 
3355
 
 
3356
    @needs_write_lock
 
3357
    def fetch(self, stop_revision=None):
 
3358
        if self.target.base == self.source.base:
 
3359
            return (0, [])
 
3360
        self.source.lock_read()
 
3361
        try:
 
3362
            fetch_spec_factory = fetch.FetchSpecFactory()
 
3363
            fetch_spec_factory.source_branch = self.source
 
3364
            fetch_spec_factory.source_branch_stop_revision_id = stop_revision
 
3365
            fetch_spec_factory.source_repo = self.source.repository
 
3366
            fetch_spec_factory.target_repo = self.target.repository
 
3367
            fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
 
3368
            fetch_spec = fetch_spec_factory.make_fetch_spec()
 
3369
            return self.target.repository.fetch(self.source.repository,
 
3370
                fetch_spec=fetch_spec)
 
3371
        finally:
 
3372
            self.source.unlock()
 
3373
 
 
3374
    @needs_write_lock
3193
3375
    def update_revisions(self, stop_revision=None, overwrite=False,
3194
 
        graph=None):
 
3376
            graph=None):
3195
3377
        """See InterBranch.update_revisions()."""
3196
 
        self.source.lock_read()
3197
 
        try:
3198
 
            other_revno, other_last_revision = self.source.last_revision_info()
3199
 
            stop_revno = None # unknown
3200
 
            if stop_revision is None:
3201
 
                stop_revision = other_last_revision
3202
 
                if _mod_revision.is_null(stop_revision):
3203
 
                    # if there are no commits, we're done.
3204
 
                    return
3205
 
                stop_revno = other_revno
3206
 
 
3207
 
            # what's the current last revision, before we fetch [and change it
3208
 
            # possibly]
3209
 
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
3210
 
            # we fetch here so that we don't process data twice in the common
3211
 
            # case of having something to pull, and so that the check for
3212
 
            # already merged can operate on the just fetched graph, which will
3213
 
            # be cached in memory.
3214
 
            self.target.fetch(self.source, stop_revision)
3215
 
            # Check to see if one is an ancestor of the other
3216
 
            if not overwrite:
3217
 
                if graph is None:
3218
 
                    graph = self.target.repository.get_graph()
3219
 
                if self.target._check_if_descendant_or_diverged(
3220
 
                        stop_revision, last_rev, graph, self.source):
3221
 
                    # stop_revision is a descendant of last_rev, but we aren't
3222
 
                    # overwriting, so we're done.
3223
 
                    return
3224
 
            if stop_revno is None:
3225
 
                if graph is None:
3226
 
                    graph = self.target.repository.get_graph()
3227
 
                this_revno, this_last_revision = \
3228
 
                        self.target.last_revision_info()
3229
 
                stop_revno = graph.find_distance_to_null(stop_revision,
3230
 
                                [(other_last_revision, other_revno),
3231
 
                                 (this_last_revision, this_revno)])
3232
 
            self.target.set_last_revision_info(stop_revno, stop_revision)
3233
 
        finally:
3234
 
            self.source.unlock()
3235
 
 
 
3378
        other_revno, other_last_revision = self.source.last_revision_info()
 
3379
        stop_revno = None # unknown
 
3380
        if stop_revision is None:
 
3381
            stop_revision = other_last_revision
 
3382
            if _mod_revision.is_null(stop_revision):
 
3383
                # if there are no commits, we're done.
 
3384
                return
 
3385
            stop_revno = other_revno
 
3386
 
 
3387
        # what's the current last revision, before we fetch [and change it
 
3388
        # possibly]
 
3389
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
3390
        # we fetch here so that we don't process data twice in the common
 
3391
        # case of having something to pull, and so that the check for
 
3392
        # already merged can operate on the just fetched graph, which will
 
3393
        # be cached in memory.
 
3394
        self.fetch(stop_revision=stop_revision)
 
3395
        # Check to see if one is an ancestor of the other
 
3396
        if not overwrite:
 
3397
            if graph is None:
 
3398
                graph = self.target.repository.get_graph()
 
3399
            if self.target._check_if_descendant_or_diverged(
 
3400
                    stop_revision, last_rev, graph, self.source):
 
3401
                # stop_revision is a descendant of last_rev, but we aren't
 
3402
                # overwriting, so we're done.
 
3403
                return
 
3404
        if stop_revno is None:
 
3405
            if graph is None:
 
3406
                graph = self.target.repository.get_graph()
 
3407
            this_revno, this_last_revision = \
 
3408
                    self.target.last_revision_info()
 
3409
            stop_revno = graph.find_distance_to_null(stop_revision,
 
3410
                            [(other_last_revision, other_revno),
 
3411
                             (this_last_revision, this_revno)])
 
3412
        self.target.set_last_revision_info(stop_revno, stop_revision)
 
3413
 
 
3414
    @needs_write_lock
3236
3415
    def pull(self, overwrite=False, stop_revision=None,
3237
 
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3416
             possible_transports=None, run_hooks=True,
3238
3417
             _override_hook_target=None, local=False):
3239
 
        """See Branch.pull.
 
3418
        """Pull from source into self, updating my master if any.
3240
3419
 
3241
 
        :param _hook_master: Private parameter - set the branch to
3242
 
            be supplied as the master to pull hooks.
3243
3420
        :param run_hooks: Private parameter - if false, this branch
3244
3421
            is being called because it's the master of the primary branch,
3245
3422
            so it should not run its hooks.
3246
 
        :param _override_hook_target: Private parameter - set the branch to be
3247
 
            supplied as the target_branch to pull hooks.
3248
 
        :param local: Only update the local branch, and not the bound branch.
3249
3423
        """
3250
 
        # This type of branch can't be bound.
3251
 
        if local:
 
3424
        bound_location = self.target.get_bound_location()
 
3425
        if local and not bound_location:
3252
3426
            raise errors.LocalRequiresBoundBranch()
3253
 
        result = PullResult()
3254
 
        result.source_branch = self.source
3255
 
        if _override_hook_target is None:
3256
 
            result.target_branch = self.target
3257
 
        else:
3258
 
            result.target_branch = _override_hook_target
3259
 
        self.source.lock_read()
 
3427
        master_branch = None
 
3428
        source_is_master = (self.source.user_url == bound_location)
 
3429
        if not local and bound_location and not source_is_master:
 
3430
            # not pulling from master, so we need to update master.
 
3431
            master_branch = self.target.get_master_branch(possible_transports)
 
3432
            master_branch.lock_write()
3260
3433
        try:
3261
 
            # We assume that during 'pull' the target repository is closer than
3262
 
            # the source one.
3263
 
            self.source.update_references(self.target)
3264
 
            graph = self.target.repository.get_graph(self.source.repository)
3265
 
            # TODO: Branch formats should have a flag that indicates 
3266
 
            # that revno's are expensive, and pull() should honor that flag.
3267
 
            # -- JRV20090506
3268
 
            result.old_revno, result.old_revid = \
3269
 
                self.target.last_revision_info()
3270
 
            self.target.update_revisions(self.source, stop_revision,
3271
 
                overwrite=overwrite, graph=graph)
3272
 
            # TODO: The old revid should be specified when merging tags, 
3273
 
            # so a tags implementation that versions tags can only 
3274
 
            # pull in the most recent changes. -- JRV20090506
3275
 
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3276
 
                overwrite)
3277
 
            result.new_revno, result.new_revid = self.target.last_revision_info()
3278
 
            if _hook_master:
3279
 
                result.master_branch = _hook_master
3280
 
                result.local_branch = result.target_branch
3281
 
            else:
3282
 
                result.master_branch = result.target_branch
3283
 
                result.local_branch = None
3284
 
            if run_hooks:
3285
 
                for hook in Branch.hooks['post_pull']:
3286
 
                    hook(result)
 
3434
            if master_branch:
 
3435
                # pull from source into master.
 
3436
                master_branch.pull(self.source, overwrite, stop_revision,
 
3437
                    run_hooks=False)
 
3438
            return self._pull(overwrite,
 
3439
                stop_revision, _hook_master=master_branch,
 
3440
                run_hooks=run_hooks,
 
3441
                _override_hook_target=_override_hook_target,
 
3442
                merge_tags_to_master=not source_is_master)
3287
3443
        finally:
3288
 
            self.source.unlock()
3289
 
        return result
 
3444
            if master_branch:
 
3445
                master_branch.unlock()
3290
3446
 
3291
3447
    def push(self, overwrite=False, stop_revision=None,
3292
3448
             _override_hook_source_branch=None):
3332
3488
                # push into the master from the source branch.
3333
3489
                self.source._basic_push(master_branch, overwrite, stop_revision)
3334
3490
                # and push into the target branch from the source. Note that we
3335
 
                # push from the source branch again, because its considered the
 
3491
                # push from the source branch again, because it's considered the
3336
3492
                # highest bandwidth repository.
3337
3493
                result = self.source._basic_push(self.target, overwrite,
3338
3494
                    stop_revision)
3354
3510
            _run_hooks()
3355
3511
            return result
3356
3512
 
3357
 
    @classmethod
3358
 
    def is_compatible(self, source, target):
3359
 
        # GenericBranch uses the public API, so always compatible
3360
 
        return True
3361
 
 
3362
 
 
3363
 
class InterToBranch5(GenericInterBranch):
3364
 
 
3365
 
    @staticmethod
3366
 
    def _get_branch_formats_to_test():
3367
 
        return BranchFormat._default_format, BzrBranchFormat5()
3368
 
 
3369
 
    def pull(self, overwrite=False, stop_revision=None,
3370
 
             possible_transports=None, run_hooks=True,
3371
 
             _override_hook_target=None, local=False):
3372
 
        """Pull from source into self, updating my master if any.
3373
 
 
 
3513
    def _pull(self, overwrite=False, stop_revision=None,
 
3514
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3515
             _override_hook_target=None, local=False,
 
3516
             merge_tags_to_master=True):
 
3517
        """See Branch.pull.
 
3518
 
 
3519
        This function is the core worker, used by GenericInterBranch.pull to
 
3520
        avoid duplication when pulling source->master and source->local.
 
3521
 
 
3522
        :param _hook_master: Private parameter - set the branch to
 
3523
            be supplied as the master to pull hooks.
3374
3524
        :param run_hooks: Private parameter - if false, this branch
3375
3525
            is being called because it's the master of the primary branch,
3376
3526
            so it should not run its hooks.
 
3527
            is being called because it's the master of the primary branch,
 
3528
            so it should not run its hooks.
 
3529
        :param _override_hook_target: Private parameter - set the branch to be
 
3530
            supplied as the target_branch to pull hooks.
 
3531
        :param local: Only update the local branch, and not the bound branch.
3377
3532
        """
3378
 
        bound_location = self.target.get_bound_location()
3379
 
        if local and not bound_location:
 
3533
        # This type of branch can't be bound.
 
3534
        if local:
3380
3535
            raise errors.LocalRequiresBoundBranch()
3381
 
        master_branch = None
3382
 
        if not local and bound_location and self.source.user_url != bound_location:
3383
 
            # not pulling from master, so we need to update master.
3384
 
            master_branch = self.target.get_master_branch(possible_transports)
3385
 
            master_branch.lock_write()
 
3536
        result = PullResult()
 
3537
        result.source_branch = self.source
 
3538
        if _override_hook_target is None:
 
3539
            result.target_branch = self.target
 
3540
        else:
 
3541
            result.target_branch = _override_hook_target
 
3542
        self.source.lock_read()
3386
3543
        try:
3387
 
            if master_branch:
3388
 
                # pull from source into master.
3389
 
                master_branch.pull(self.source, overwrite, stop_revision,
3390
 
                    run_hooks=False)
3391
 
            return super(InterToBranch5, self).pull(overwrite,
3392
 
                stop_revision, _hook_master=master_branch,
3393
 
                run_hooks=run_hooks,
3394
 
                _override_hook_target=_override_hook_target)
 
3544
            # We assume that during 'pull' the target repository is closer than
 
3545
            # the source one.
 
3546
            self.source.update_references(self.target)
 
3547
            graph = self.target.repository.get_graph(self.source.repository)
 
3548
            # TODO: Branch formats should have a flag that indicates 
 
3549
            # that revno's are expensive, and pull() should honor that flag.
 
3550
            # -- JRV20090506
 
3551
            result.old_revno, result.old_revid = \
 
3552
                self.target.last_revision_info()
 
3553
            self.target.update_revisions(self.source, stop_revision,
 
3554
                overwrite=overwrite, graph=graph)
 
3555
            # TODO: The old revid should be specified when merging tags, 
 
3556
            # so a tags implementation that versions tags can only 
 
3557
            # pull in the most recent changes. -- JRV20090506
 
3558
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
3559
                overwrite, ignore_master=not merge_tags_to_master)
 
3560
            result.new_revno, result.new_revid = self.target.last_revision_info()
 
3561
            if _hook_master:
 
3562
                result.master_branch = _hook_master
 
3563
                result.local_branch = result.target_branch
 
3564
            else:
 
3565
                result.master_branch = result.target_branch
 
3566
                result.local_branch = None
 
3567
            if run_hooks:
 
3568
                for hook in Branch.hooks['post_pull']:
 
3569
                    hook(result)
3395
3570
        finally:
3396
 
            if master_branch:
3397
 
                master_branch.unlock()
 
3571
            self.source.unlock()
 
3572
        return result
3398
3573
 
3399
3574
 
3400
3575
InterBranch.register_optimiser(GenericInterBranch)
3401
 
InterBranch.register_optimiser(InterToBranch5)