/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: A. S. Budden
  • Date: 2011-05-04 13:26:14 UTC
  • mto: (5816.6.16 bazaar_source)
  • mto: This revision was merged to the branch mainline in revision 5835.
  • Revision ID: abudden@gmail.com-20110504132614-3ghb1ajucl6plc5z
Set the parent location of the bound branch to that of the master branch.

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
61
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
53
62
from bzrlib import registry
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
636
669
        raise errors.UnsupportedOperation(self.get_reference_info, self)
637
670
 
638
671
    @needs_write_lock
639
 
    def fetch(self, from_branch, last_revision=None, pb=None):
 
672
    def fetch(self, from_branch, last_revision=None):
640
673
        """Copy revisions from from_branch into this branch.
641
674
 
642
675
        :param from_branch: Where to copy from.
643
676
        :param last_revision: What revision to stop at (None for at the end
644
677
                              of the branch.
645
 
        :param pb: An optional progress bar to use.
646
678
        :return: None
647
679
        """
648
 
        if self.base == from_branch.base:
649
 
            return (0, [])
650
 
        if pb is not None:
651
 
            symbol_versioning.warn(
652
 
                symbol_versioning.deprecated_in((1, 14, 0))
653
 
                % "pb parameter to fetch()")
654
 
        from_branch.lock_read()
655
 
        try:
656
 
            if last_revision is None:
657
 
                last_revision = from_branch.last_revision()
658
 
                last_revision = _mod_revision.ensure_null(last_revision)
659
 
            return self.repository.fetch(from_branch.repository,
660
 
                                         revision_id=last_revision,
661
 
                                         pb=pb)
662
 
        finally:
663
 
            from_branch.unlock()
 
680
        return InterBranch.get(from_branch, self).fetch(last_revision)
664
681
 
665
682
    def get_bound_location(self):
666
683
        """Return the URL of the branch we are bound to.
677
694
 
678
695
    def get_commit_builder(self, parents, config=None, timestamp=None,
679
696
                           timezone=None, committer=None, revprops=None,
680
 
                           revision_id=None):
 
697
                           revision_id=None, lossy=False):
681
698
        """Obtain a CommitBuilder for this branch.
682
699
 
683
700
        :param parents: Revision ids of the parents of the new revision.
687
704
        :param committer: Optional committer to set for commit.
688
705
        :param revprops: Optional dictionary of revision properties.
689
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 
690
709
        """
691
710
 
692
711
        if config is None:
693
712
            config = self.get_config()
694
713
 
695
714
        return self.repository.get_commit_builder(self, parents, config,
696
 
            timestamp, timezone, committer, revprops, revision_id)
 
715
            timestamp, timezone, committer, revprops, revision_id,
 
716
            lossy)
697
717
 
698
718
    def get_master_branch(self, possible_transports=None):
699
719
        """Return the branch we are bound to.
777
797
 
778
798
    def _unstack(self):
779
799
        """Change a branch to be unstacked, copying data as needed.
780
 
        
 
800
 
781
801
        Don't call this directly, use set_stacked_on_url(None).
782
802
        """
783
803
        pb = ui.ui_factory.nested_progress_bar()
792
812
            old_repository = self.repository
793
813
            if len(old_repository._fallback_repositories) != 1:
794
814
                raise AssertionError("can't cope with fallback repositories "
795
 
                    "of %r" % (self.repository,))
796
 
            # unlock it, including unlocking the fallback
 
815
                    "of %r (fallbacks: %r)" % (old_repository,
 
816
                        old_repository._fallback_repositories))
 
817
            # Open the new repository object.
 
818
            # Repositories don't offer an interface to remove fallback
 
819
            # repositories today; take the conceptually simpler option and just
 
820
            # reopen it.  We reopen it starting from the URL so that we
 
821
            # get a separate connection for RemoteRepositories and can
 
822
            # stream from one of them to the other.  This does mean doing
 
823
            # separate SSH connection setup, but unstacking is not a
 
824
            # common operation so it's tolerable.
 
825
            new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
 
826
            new_repository = new_bzrdir.find_repository()
 
827
            if new_repository._fallback_repositories:
 
828
                raise AssertionError("didn't expect %r to have "
 
829
                    "fallback_repositories"
 
830
                    % (self.repository,))
 
831
            # Replace self.repository with the new repository.
 
832
            # Do our best to transfer the lock state (i.e. lock-tokens and
 
833
            # lock count) of self.repository to the new repository.
 
834
            lock_token = old_repository.lock_write().repository_token
 
835
            self.repository = new_repository
 
836
            if isinstance(self, remote.RemoteBranch):
 
837
                # Remote branches can have a second reference to the old
 
838
                # repository that need to be replaced.
 
839
                if self._real_branch is not None:
 
840
                    self._real_branch.repository = new_repository
 
841
            self.repository.lock_write(token=lock_token)
 
842
            if lock_token is not None:
 
843
                old_repository.leave_lock_in_place()
797
844
            old_repository.unlock()
 
845
            if lock_token is not None:
 
846
                # XXX: self.repository.leave_lock_in_place() before this
 
847
                # function will not be preserved.  Fortunately that doesn't
 
848
                # affect the current default format (2a), and would be a
 
849
                # corner-case anyway.
 
850
                #  - Andrew Bennetts, 2010/06/30
 
851
                self.repository.dont_leave_lock_in_place()
 
852
            old_lock_count = 0
 
853
            while True:
 
854
                try:
 
855
                    old_repository.unlock()
 
856
                except errors.LockNotHeld:
 
857
                    break
 
858
                old_lock_count += 1
 
859
            if old_lock_count == 0:
 
860
                raise AssertionError(
 
861
                    'old_repository should have been locked at least once.')
 
862
            for i in range(old_lock_count-1):
 
863
                self.repository.lock_write()
 
864
            # Fetch from the old repository into the new.
798
865
            old_repository.lock_read()
799
866
            try:
800
 
                # Repositories don't offer an interface to remove fallback
801
 
                # repositories today; take the conceptually simpler option and just
802
 
                # reopen it.  We reopen it starting from the URL so that we
803
 
                # get a separate connection for RemoteRepositories and can
804
 
                # stream from one of them to the other.  This does mean doing
805
 
                # separate SSH connection setup, but unstacking is not a
806
 
                # common operation so it's tolerable.
807
 
                new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
808
 
                new_repository = new_bzrdir.find_repository()
809
 
                self.repository = new_repository
810
 
                if self.repository._fallback_repositories:
811
 
                    raise AssertionError("didn't expect %r to have "
812
 
                        "fallback_repositories"
813
 
                        % (self.repository,))
814
 
                # this is not paired with an unlock because it's just restoring
815
 
                # the previous state; the lock's released when set_stacked_on_url
816
 
                # returns
817
 
                self.repository.lock_write()
818
867
                # XXX: If you unstack a branch while it has a working tree
819
868
                # with a pending merge, the pending-merged revisions will no
820
869
                # longer be present.  You can (probably) revert and remerge.
821
 
                #
822
 
                # XXX: This only fetches up to the tip of the repository; it
823
 
                # doesn't bring across any tags.  That's fairly consistent
824
 
                # with how branch works, but perhaps not ideal.
825
 
                self.repository.fetch(old_repository,
826
 
                    revision_id=self.last_revision(),
827
 
                    find_ghosts=True)
 
870
                try:
 
871
                    tags_to_fetch = set(self.tags.get_reverse_tag_dict())
 
872
                except errors.TagsNotSupported:
 
873
                    tags_to_fetch = set()
 
874
                fetch_spec = _mod_graph.NotInOtherForRevs(self.repository,
 
875
                    old_repository, required_ids=[self.last_revision()],
 
876
                    if_present_ids=tags_to_fetch, find_ghosts=True).execute()
 
877
                self.repository.fetch(old_repository, fetch_spec=fetch_spec)
828
878
            finally:
829
879
                old_repository.unlock()
830
880
        finally:
835
885
 
836
886
        :seealso: Branch._get_tags_bytes.
837
887
        """
838
 
        return _run_with_write_locked_target(self, self._transport.put_bytes,
839
 
            'tags', bytes)
 
888
        return _run_with_write_locked_target(self, self._set_tags_bytes_locked,
 
889
                bytes)
 
890
 
 
891
    def _set_tags_bytes_locked(self, bytes):
 
892
        self._tags_bytes = bytes
 
893
        return self._transport.put_bytes('tags', bytes)
840
894
 
841
895
    def _cache_revision_history(self, rev_history):
842
896
        """Set the cached revision history to rev_history.
869
923
        self._revision_history_cache = None
870
924
        self._revision_id_to_revno_cache = None
871
925
        self._last_revision_info_cache = None
 
926
        self._master_branch_cache = None
872
927
        self._merge_sorted_revisions_cache = None
873
928
        self._partial_revision_history_cache = []
874
929
        self._partial_revision_id_to_revno_cache = {}
 
930
        self._tags_bytes = None
875
931
 
876
932
    def _gen_revision_history(self):
877
933
        """Return sequence of revision hashes on to this branch.
938
994
        else:
939
995
            return (0, _mod_revision.NULL_REVISION)
940
996
 
941
 
    @deprecated_method(deprecated_in((1, 6, 0)))
942
 
    def missing_revisions(self, other, stop_revision=None):
943
 
        """Return a list of new revisions that would perfectly fit.
944
 
 
945
 
        If self and other have not diverged, return a list of the revisions
946
 
        present in other, but missing from self.
947
 
        """
948
 
        self_history = self.revision_history()
949
 
        self_len = len(self_history)
950
 
        other_history = other.revision_history()
951
 
        other_len = len(other_history)
952
 
        common_index = min(self_len, other_len) -1
953
 
        if common_index >= 0 and \
954
 
            self_history[common_index] != other_history[common_index]:
955
 
            raise errors.DivergedBranches(self, other)
956
 
 
957
 
        if stop_revision is None:
958
 
            stop_revision = other_len
959
 
        else:
960
 
            if stop_revision > other_len:
961
 
                raise errors.NoSuchRevision(self, stop_revision)
962
 
        return other_history[self_len:stop_revision]
963
 
 
964
 
    @needs_write_lock
965
997
    def update_revisions(self, other, stop_revision=None, overwrite=False,
966
 
                         graph=None):
 
998
            graph=None):
967
999
        """Pull in new perfect-fit revisions.
968
1000
 
969
1001
        :param other: Another Branch to pull from
977
1009
        return InterBranch.get(other, self).update_revisions(stop_revision,
978
1010
            overwrite, graph)
979
1011
 
 
1012
    @deprecated_method(deprecated_in((2, 4, 0)))
980
1013
    def import_last_revision_info(self, source_repo, revno, revid):
981
1014
        """Set the last revision info, importing from another repo if necessary.
982
1015
 
983
 
        This is used by the bound branch code to upload a revision to
984
 
        the master branch first before updating the tip of the local branch.
985
 
 
986
1016
        :param source_repo: Source repository to optionally fetch from
987
1017
        :param revno: Revision number of the new tip
988
1018
        :param revid: Revision id of the new tip
991
1021
            self.repository.fetch(source_repo, revision_id=revid)
992
1022
        self.set_last_revision_info(revno, revid)
993
1023
 
 
1024
    def import_last_revision_info_and_tags(self, source, revno, revid,
 
1025
                                           lossy=False):
 
1026
        """Set the last revision info, importing from another repo if necessary.
 
1027
 
 
1028
        This is used by the bound branch code to upload a revision to
 
1029
        the master branch first before updating the tip of the local branch.
 
1030
        Revisions referenced by source's tags are also transferred.
 
1031
 
 
1032
        :param source: Source branch to optionally fetch from
 
1033
        :param revno: Revision number of the new tip
 
1034
        :param revid: Revision id of the new tip
 
1035
        :param lossy: Whether to discard metadata that can not be
 
1036
            natively represented
 
1037
        :return: Tuple with the new revision number and revision id
 
1038
            (should only be different from the arguments when lossy=True)
 
1039
        """
 
1040
        if not self.repository.has_same_location(source.repository):
 
1041
            self.fetch(source, revid)
 
1042
        self.set_last_revision_info(revno, revid)
 
1043
        return (revno, revid)
 
1044
 
994
1045
    def revision_id_to_revno(self, revision_id):
995
1046
        """Given a revision id, return its revno"""
996
1047
        if _mod_revision.is_null(revision_id):
1016
1067
            self._extend_partial_history(distance_from_last)
1017
1068
        return self._partial_revision_history_cache[distance_from_last]
1018
1069
 
1019
 
    @needs_write_lock
1020
1070
    def pull(self, source, overwrite=False, stop_revision=None,
1021
1071
             possible_transports=None, *args, **kwargs):
1022
1072
        """Mirror source into this branch.
1218
1268
        return result
1219
1269
 
1220
1270
    @needs_read_lock
1221
 
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None):
 
1271
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None,
 
1272
            repository=None):
1222
1273
        """Create a new line of development from the branch, into to_bzrdir.
1223
1274
 
1224
1275
        to_bzrdir controls the branch format.
1229
1280
        if (repository_policy is not None and
1230
1281
            repository_policy.requires_stacking()):
1231
1282
            to_bzrdir._format.require_stacking(_skip_repo=True)
1232
 
        result = to_bzrdir.create_branch()
 
1283
        result = to_bzrdir.create_branch(repository=repository)
1233
1284
        result.lock_write()
1234
1285
        try:
1235
1286
            if repository_policy is not None:
1236
1287
                repository_policy.configure_branch(result)
1237
1288
            self.copy_content_into(result, revision_id=revision_id)
1238
 
            result.set_parent(self.bzrdir.root_transport.base)
 
1289
            bound_branch = self.get_master_branch()
 
1290
            if bound_branch is None:
 
1291
                result.set_parent(self.bzrdir.root_transport.base)
 
1292
            else:
 
1293
                result.set_parent(bound_branch.bzrdir.root_transport.base)
1239
1294
        finally:
1240
1295
            result.unlock()
1241
1296
        return result
1265
1320
                revno = 1
1266
1321
        destination.set_last_revision_info(revno, revision_id)
1267
1322
 
1268
 
    @needs_read_lock
1269
1323
    def copy_content_into(self, destination, revision_id=None):
1270
1324
        """Copy the content of self into destination.
1271
1325
 
1272
1326
        revision_id: if not None, the revision history in the new branch will
1273
1327
                     be truncated to end with revision_id.
1274
1328
        """
1275
 
        self.update_references(destination)
1276
 
        self._synchronize_history(destination, revision_id)
1277
 
        try:
1278
 
            parent = self.get_parent()
1279
 
        except errors.InaccessibleParent, e:
1280
 
            mutter('parent was not accessible to copy: %s', e)
1281
 
        else:
1282
 
            if parent:
1283
 
                destination.set_parent(parent)
1284
 
        if self._push_should_merge_tags():
1285
 
            self.tags.merge_to(destination.tags)
 
1329
        return InterBranch.get(self, destination).copy_content_into(
 
1330
            revision_id=revision_id)
1286
1331
 
1287
1332
    def update_references(self, target):
1288
1333
        if not getattr(self._format, 'supports_reference_locations', False):
1333
1378
        """Return the most suitable metadir for a checkout of this branch.
1334
1379
        Weaves are used if this branch's repository uses weaves.
1335
1380
        """
1336
 
        if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
1337
 
            from bzrlib.repofmt import weaverepo
1338
 
            format = bzrdir.BzrDirMetaFormat1()
1339
 
            format.repository_format = weaverepo.RepositoryFormat7()
1340
 
        else:
1341
 
            format = self.repository.bzrdir.checkout_metadir()
1342
 
            format.set_branch_format(self._format)
 
1381
        format = self.repository.bzrdir.checkout_metadir()
 
1382
        format.set_branch_format(self._format)
1343
1383
        return format
1344
1384
 
1345
1385
    def create_clone_on_transport(self, to_transport, revision_id=None,
1346
 
        stacked_on=None, create_prefix=False, use_existing_dir=False):
 
1386
        stacked_on=None, create_prefix=False, use_existing_dir=False,
 
1387
        no_tree=None):
1347
1388
        """Create a clone of this branch and its bzrdir.
1348
1389
 
1349
1390
        :param to_transport: The transport to clone onto.
1362
1403
            revision_id = self.last_revision()
1363
1404
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1364
1405
            revision_id=revision_id, stacked_on=stacked_on,
1365
 
            create_prefix=create_prefix, use_existing_dir=use_existing_dir)
 
1406
            create_prefix=create_prefix, use_existing_dir=use_existing_dir,
 
1407
            no_tree=no_tree)
1366
1408
        return dir_to.open_branch()
1367
1409
 
1368
1410
    def create_checkout(self, to_location, revision_id=None,
1483
1525
        else:
1484
1526
            raise AssertionError("invalid heads: %r" % (heads,))
1485
1527
 
1486
 
 
1487
 
class BranchFormat(object):
 
1528
    def heads_to_fetch(self):
 
1529
        """Return the heads that must and that should be fetched to copy this
 
1530
        branch into another repo.
 
1531
 
 
1532
        :returns: a 2-tuple of (must_fetch, if_present_fetch).  must_fetch is a
 
1533
            set of heads that must be fetched.  if_present_fetch is a set of
 
1534
            heads that must be fetched if present, but no error is necessary if
 
1535
            they are not present.
 
1536
        """
 
1537
        # For bzr native formats must_fetch is just the tip, and if_present_fetch
 
1538
        # are the tags.
 
1539
        must_fetch = set([self.last_revision()])
 
1540
        try:
 
1541
            if_present_fetch = set(self.tags.get_reverse_tag_dict())
 
1542
        except errors.TagsNotSupported:
 
1543
            if_present_fetch = set()
 
1544
        must_fetch.discard(_mod_revision.NULL_REVISION)
 
1545
        if_present_fetch.discard(_mod_revision.NULL_REVISION)
 
1546
        return must_fetch, if_present_fetch
 
1547
 
 
1548
 
 
1549
class BranchFormat(controldir.ControlComponentFormat):
1488
1550
    """An encapsulation of the initialization and open routines for a format.
1489
1551
 
1490
1552
    Formats provide three things:
1493
1555
     * an open routine.
1494
1556
 
1495
1557
    Formats are placed in an dict by their format string for reference
1496
 
    during branch opening. Its not required that these be instances, they
 
1558
    during branch opening. It's not required that these be instances, they
1497
1559
    can be classes themselves with class methods - it simply depends on
1498
1560
    whether state is needed for a given format or not.
1499
1561
 
1502
1564
    object will be created every time regardless.
1503
1565
    """
1504
1566
 
1505
 
    _default_format = None
1506
 
    """The default format used for new branches."""
1507
 
 
1508
 
    _formats = {}
1509
 
    """The known formats."""
1510
 
 
1511
1567
    can_set_append_revisions_only = True
1512
1568
 
1513
1569
    def __eq__(self, other):
1522
1578
        try:
1523
1579
            transport = a_bzrdir.get_branch_transport(None, name=name)
1524
1580
            format_string = transport.get_bytes("format")
1525
 
            return klass._formats[format_string]
 
1581
            return format_registry.get(format_string)
1526
1582
        except errors.NoSuchFile:
1527
1583
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1528
1584
        except KeyError:
1529
1585
            raise errors.UnknownFormatError(format=format_string, kind='branch')
1530
1586
 
1531
1587
    @classmethod
 
1588
    @deprecated_method(deprecated_in((2, 4, 0)))
1532
1589
    def get_default_format(klass):
1533
1590
        """Return the current default format."""
1534
 
        return klass._default_format
 
1591
        return format_registry.get_default()
 
1592
 
 
1593
    @classmethod
 
1594
    @deprecated_method(deprecated_in((2, 4, 0)))
 
1595
    def get_formats(klass):
 
1596
        """Get all the known formats.
 
1597
 
 
1598
        Warning: This triggers a load of all lazy registered formats: do not
 
1599
        use except when that is desireed.
 
1600
        """
 
1601
        return format_registry._get_all()
1535
1602
 
1536
1603
    def get_reference(self, a_bzrdir, name=None):
1537
1604
        """Get the target reference of the branch in a_bzrdir.
1576
1643
        for hook in hooks:
1577
1644
            hook(params)
1578
1645
 
1579
 
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
1580
 
                           lock_type='metadir', set_format=True):
1581
 
        """Initialize a branch in a bzrdir, with specified files
1582
 
 
1583
 
        :param a_bzrdir: The bzrdir to initialize the branch in
1584
 
        :param utf8_files: The files to create as a list of
1585
 
            (filename, content) tuples
1586
 
        :param name: Name of colocated branch to create, if any
1587
 
        :param set_format: If True, set the format with
1588
 
            self.get_format_string.  (BzrBranch4 has its format set
1589
 
            elsewhere)
1590
 
        :return: a branch in this format
1591
 
        """
1592
 
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
1593
 
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
1594
 
        lock_map = {
1595
 
            'metadir': ('lock', lockdir.LockDir),
1596
 
            'branch4': ('branch-lock', lockable_files.TransportLock),
1597
 
        }
1598
 
        lock_name, lock_class = lock_map[lock_type]
1599
 
        control_files = lockable_files.LockableFiles(branch_transport,
1600
 
            lock_name, lock_class)
1601
 
        control_files.create_lock()
1602
 
        try:
1603
 
            control_files.lock_write()
1604
 
        except errors.LockContention:
1605
 
            if lock_type != 'branch4':
1606
 
                raise
1607
 
            lock_taken = False
1608
 
        else:
1609
 
            lock_taken = True
1610
 
        if set_format:
1611
 
            utf8_files += [('format', self.get_format_string())]
1612
 
        try:
1613
 
            for (filename, content) in utf8_files:
1614
 
                branch_transport.put_bytes(
1615
 
                    filename, content,
1616
 
                    mode=a_bzrdir._get_file_mode())
1617
 
        finally:
1618
 
            if lock_taken:
1619
 
                control_files.unlock()
1620
 
        branch = self.open(a_bzrdir, name, _found=True)
1621
 
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
1622
 
        return branch
1623
 
 
1624
 
    def initialize(self, a_bzrdir, name=None):
 
1646
    def initialize(self, a_bzrdir, name=None, repository=None):
1625
1647
        """Create a branch of this format in a_bzrdir.
1626
1648
        
1627
1649
        :param name: Name of the colocated branch to create.
1661
1683
        """
1662
1684
        raise NotImplementedError(self.network_name)
1663
1685
 
1664
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1686
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
 
1687
            found_repository=None):
1665
1688
        """Return the branch object for a_bzrdir
1666
1689
 
1667
1690
        :param a_bzrdir: A BzrDir that contains a branch.
1674
1697
        raise NotImplementedError(self.open)
1675
1698
 
1676
1699
    @classmethod
 
1700
    @deprecated_method(deprecated_in((2, 4, 0)))
1677
1701
    def register_format(klass, format):
1678
 
        """Register a metadir format."""
1679
 
        klass._formats[format.get_format_string()] = format
1680
 
        # Metadir formats have a network name of their format string, and get
1681
 
        # registered as class factories.
1682
 
        network_format_registry.register(format.get_format_string(), format.__class__)
 
1702
        """Register a metadir format.
 
1703
 
 
1704
        See MetaDirBranchFormatFactory for the ability to register a format
 
1705
        without loading the code the format needs until it is actually used.
 
1706
        """
 
1707
        format_registry.register(format)
1683
1708
 
1684
1709
    @classmethod
 
1710
    @deprecated_method(deprecated_in((2, 4, 0)))
1685
1711
    def set_default_format(klass, format):
1686
 
        klass._default_format = format
 
1712
        format_registry.set_default(format)
1687
1713
 
1688
1714
    def supports_set_append_revisions_only(self):
1689
1715
        """True if this format supports set_append_revisions_only."""
1693
1719
        """True if this format records a stacked-on branch."""
1694
1720
        return False
1695
1721
 
 
1722
    def supports_leaving_lock(self):
 
1723
        """True if this format supports leaving locks in place."""
 
1724
        return False # by default
 
1725
 
1696
1726
    @classmethod
 
1727
    @deprecated_method(deprecated_in((2, 4, 0)))
1697
1728
    def unregister_format(klass, format):
1698
 
        del klass._formats[format.get_format_string()]
 
1729
        format_registry.remove(format)
1699
1730
 
1700
1731
    def __str__(self):
1701
1732
        return self.get_format_description().rstrip()
1705
1736
        return False  # by default
1706
1737
 
1707
1738
 
 
1739
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
 
1740
    """A factory for a BranchFormat object, permitting simple lazy registration.
 
1741
    
 
1742
    While none of the built in BranchFormats are lazy registered yet,
 
1743
    bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
 
1744
    use it, and the bzr-loom plugin uses it as well (see
 
1745
    bzrlib.plugins.loom.formats).
 
1746
    """
 
1747
 
 
1748
    def __init__(self, format_string, module_name, member_name):
 
1749
        """Create a MetaDirBranchFormatFactory.
 
1750
 
 
1751
        :param format_string: The format string the format has.
 
1752
        :param module_name: Module to load the format class from.
 
1753
        :param member_name: Attribute name within the module for the format class.
 
1754
        """
 
1755
        registry._LazyObjectGetter.__init__(self, module_name, member_name)
 
1756
        self._format_string = format_string
 
1757
        
 
1758
    def get_format_string(self):
 
1759
        """See BranchFormat.get_format_string."""
 
1760
        return self._format_string
 
1761
 
 
1762
    def __call__(self):
 
1763
        """Used for network_format_registry support."""
 
1764
        return self.get_obj()()
 
1765
 
 
1766
 
1708
1767
class BranchHooks(Hooks):
1709
1768
    """A dictionary mapping hook name to a list of callables for branch hooks.
1710
1769
 
1718
1777
        These are all empty initially, because by default nothing should get
1719
1778
        notified.
1720
1779
        """
1721
 
        Hooks.__init__(self)
1722
 
        self.create_hook(HookPoint('set_rh',
 
1780
        Hooks.__init__(self, "bzrlib.branch", "Branch.hooks")
 
1781
        self.add_hook('set_rh',
1723
1782
            "Invoked whenever the revision history has been set via "
1724
1783
            "set_revision_history. The api signature is (branch, "
1725
1784
            "revision_history), and the branch will be write-locked. "
1726
1785
            "The set_rh hook can be expensive for bzr to trigger, a better "
1727
 
            "hook to use is Branch.post_change_branch_tip.", (0, 15), None))
1728
 
        self.create_hook(HookPoint('open',
 
1786
            "hook to use is Branch.post_change_branch_tip.", (0, 15))
 
1787
        self.add_hook('open',
1729
1788
            "Called with the Branch object that has been opened after a "
1730
 
            "branch is opened.", (1, 8), None))
1731
 
        self.create_hook(HookPoint('post_push',
 
1789
            "branch is opened.", (1, 8))
 
1790
        self.add_hook('post_push',
1732
1791
            "Called after a push operation completes. post_push is called "
1733
1792
            "with a bzrlib.branch.BranchPushResult object and only runs in the "
1734
 
            "bzr client.", (0, 15), None))
1735
 
        self.create_hook(HookPoint('post_pull',
 
1793
            "bzr client.", (0, 15))
 
1794
        self.add_hook('post_pull',
1736
1795
            "Called after a pull operation completes. post_pull is called "
1737
1796
            "with a bzrlib.branch.PullResult object and only runs in the "
1738
 
            "bzr client.", (0, 15), None))
1739
 
        self.create_hook(HookPoint('pre_commit',
1740
 
            "Called after a commit is calculated but before it is is "
 
1797
            "bzr client.", (0, 15))
 
1798
        self.add_hook('pre_commit',
 
1799
            "Called after a commit is calculated but before it is "
1741
1800
            "completed. pre_commit is called with (local, master, old_revno, "
1742
1801
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
1743
1802
            "). old_revid is NULL_REVISION for the first commit to a branch, "
1745
1804
            "basis revision. hooks MUST NOT modify this delta. "
1746
1805
            " future_tree is an in-memory tree obtained from "
1747
1806
            "CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1748
 
            "tree.", (0,91), None))
1749
 
        self.create_hook(HookPoint('post_commit',
 
1807
            "tree.", (0,91))
 
1808
        self.add_hook('post_commit',
1750
1809
            "Called in the bzr client after a commit has completed. "
1751
1810
            "post_commit is called with (local, master, old_revno, old_revid, "
1752
1811
            "new_revno, new_revid). old_revid is NULL_REVISION for the first "
1753
 
            "commit to a branch.", (0, 15), None))
1754
 
        self.create_hook(HookPoint('post_uncommit',
 
1812
            "commit to a branch.", (0, 15))
 
1813
        self.add_hook('post_uncommit',
1755
1814
            "Called in the bzr client after an uncommit completes. "
1756
1815
            "post_uncommit is called with (local, master, old_revno, "
1757
1816
            "old_revid, new_revno, new_revid) where local is the local branch "
1758
1817
            "or None, master is the target branch, and an empty branch "
1759
 
            "receives new_revno of 0, new_revid of None.", (0, 15), None))
1760
 
        self.create_hook(HookPoint('pre_change_branch_tip',
 
1818
            "receives new_revno of 0, new_revid of None.", (0, 15))
 
1819
        self.add_hook('pre_change_branch_tip',
1761
1820
            "Called in bzr client and server before a change to the tip of a "
1762
1821
            "branch is made. pre_change_branch_tip is called with a "
1763
1822
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1764
 
            "commit, uncommit will all trigger this hook.", (1, 6), None))
1765
 
        self.create_hook(HookPoint('post_change_branch_tip',
 
1823
            "commit, uncommit will all trigger this hook.", (1, 6))
 
1824
        self.add_hook('post_change_branch_tip',
1766
1825
            "Called in bzr client and server after a change to the tip of a "
1767
1826
            "branch is made. post_change_branch_tip is called with a "
1768
1827
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1769
 
            "commit, uncommit will all trigger this hook.", (1, 4), None))
1770
 
        self.create_hook(HookPoint('transform_fallback_location',
 
1828
            "commit, uncommit will all trigger this hook.", (1, 4))
 
1829
        self.add_hook('transform_fallback_location',
1771
1830
            "Called when a stacked branch is activating its fallback "
1772
1831
            "locations. transform_fallback_location is called with (branch, "
1773
1832
            "url), and should return a new url. Returning the same url "
1778
1837
            "fallback locations have not been activated. When there are "
1779
1838
            "multiple hooks installed for transform_fallback_location, "
1780
1839
            "all are called with the url returned from the previous hook."
1781
 
            "The order is however undefined.", (1, 9), None))
1782
 
        self.create_hook(HookPoint('automatic_tag_name',
1783
 
            "Called to determine an automatic tag name for a revision."
 
1840
            "The order is however undefined.", (1, 9))
 
1841
        self.add_hook('automatic_tag_name',
 
1842
            "Called to determine an automatic tag name for a revision. "
1784
1843
            "automatic_tag_name is called with (branch, revision_id) and "
1785
1844
            "should return a tag name or None if no tag name could be "
1786
1845
            "determined. The first non-None tag name returned will be used.",
1787
 
            (2, 2), None))
1788
 
        self.create_hook(HookPoint('post_branch_init',
 
1846
            (2, 2))
 
1847
        self.add_hook('post_branch_init',
1789
1848
            "Called after new branch initialization completes. "
1790
1849
            "post_branch_init is called with a "
1791
1850
            "bzrlib.branch.BranchInitHookParams. "
1792
1851
            "Note that init, branch and checkout (both heavyweight and "
1793
 
            "lightweight) will all trigger this hook.", (2, 2), None))
1794
 
        self.create_hook(HookPoint('post_switch',
 
1852
            "lightweight) will all trigger this hook.", (2, 2))
 
1853
        self.add_hook('post_switch',
1795
1854
            "Called after a checkout switches branch. "
1796
1855
            "post_switch is called with a "
1797
 
            "bzrlib.branch.SwitchHookParams.", (2, 2), None))
 
1856
            "bzrlib.branch.SwitchHookParams.", (2, 2))
1798
1857
 
1799
1858
 
1800
1859
 
1877
1936
        return self.__dict__ == other.__dict__
1878
1937
 
1879
1938
    def __repr__(self):
1880
 
        if self.branch:
1881
 
            return "<%s of %s>" % (self.__class__.__name__, self.branch)
1882
 
        else:
1883
 
            return "<%s of format:%s bzrdir:%s>" % (
1884
 
                self.__class__.__name__, self.branch,
1885
 
                self.format, self.bzrdir)
 
1939
        return "<%s of %s>" % (self.__class__.__name__, self.branch)
1886
1940
 
1887
1941
 
1888
1942
class SwitchHookParams(object):
1918
1972
            self.revision_id)
1919
1973
 
1920
1974
 
1921
 
class BzrBranchFormat4(BranchFormat):
1922
 
    """Bzr branch format 4.
1923
 
 
1924
 
    This format has:
1925
 
     - a revision-history file.
1926
 
     - a branch-lock lock file [ to be shared with the bzrdir ]
1927
 
    """
1928
 
 
1929
 
    def get_format_description(self):
1930
 
        """See BranchFormat.get_format_description()."""
1931
 
        return "Branch format 4"
1932
 
 
1933
 
    def initialize(self, a_bzrdir, name=None):
1934
 
        """Create a branch of this format in a_bzrdir."""
1935
 
        utf8_files = [('revision-history', ''),
1936
 
                      ('branch-name', ''),
1937
 
                      ]
1938
 
        return self._initialize_helper(a_bzrdir, utf8_files, name=name,
1939
 
                                       lock_type='branch4', set_format=False)
1940
 
 
1941
 
    def __init__(self):
1942
 
        super(BzrBranchFormat4, self).__init__()
1943
 
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
1944
 
 
1945
 
    def network_name(self):
1946
 
        """The network name for this format is the control dirs disk label."""
1947
 
        return self._matchingbzrdir.get_format_string()
1948
 
 
1949
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
1950
 
        """See BranchFormat.open()."""
1951
 
        if not _found:
1952
 
            # we are being called directly and must probe.
1953
 
            raise NotImplementedError
1954
 
        return BzrBranch(_format=self,
1955
 
                         _control_files=a_bzrdir._control_files,
1956
 
                         a_bzrdir=a_bzrdir,
1957
 
                         name=name,
1958
 
                         _repository=a_bzrdir.open_repository())
1959
 
 
1960
 
    def __str__(self):
1961
 
        return "Bazaar-NG branch format 4"
1962
 
 
1963
 
 
1964
1975
class BranchFormatMetadir(BranchFormat):
1965
1976
    """Common logic for meta-dir based branch formats."""
1966
1977
 
1968
1979
        """What class to instantiate on open calls."""
1969
1980
        raise NotImplementedError(self._branch_class)
1970
1981
 
 
1982
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
 
1983
                           repository=None):
 
1984
        """Initialize a branch in a bzrdir, with specified files
 
1985
 
 
1986
        :param a_bzrdir: The bzrdir to initialize the branch in
 
1987
        :param utf8_files: The files to create as a list of
 
1988
            (filename, content) tuples
 
1989
        :param name: Name of colocated branch to create, if any
 
1990
        :return: a branch in this format
 
1991
        """
 
1992
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
 
1993
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
1994
        control_files = lockable_files.LockableFiles(branch_transport,
 
1995
            'lock', lockdir.LockDir)
 
1996
        control_files.create_lock()
 
1997
        control_files.lock_write()
 
1998
        try:
 
1999
            utf8_files += [('format', self.get_format_string())]
 
2000
            for (filename, content) in utf8_files:
 
2001
                branch_transport.put_bytes(
 
2002
                    filename, content,
 
2003
                    mode=a_bzrdir._get_file_mode())
 
2004
        finally:
 
2005
            control_files.unlock()
 
2006
        branch = self.open(a_bzrdir, name, _found=True,
 
2007
                found_repository=repository)
 
2008
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
 
2009
        return branch
 
2010
 
1971
2011
    def network_name(self):
1972
2012
        """A simple byte string uniquely identifying this format for RPC calls.
1973
2013
 
1975
2015
        """
1976
2016
        return self.get_format_string()
1977
2017
 
1978
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
2018
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
 
2019
            found_repository=None):
1979
2020
        """See BranchFormat.open()."""
1980
2021
        if not _found:
1981
2022
            format = BranchFormat.find_format(a_bzrdir, name=name)
1986
2027
        try:
1987
2028
            control_files = lockable_files.LockableFiles(transport, 'lock',
1988
2029
                                                         lockdir.LockDir)
 
2030
            if found_repository is None:
 
2031
                found_repository = a_bzrdir.find_repository()
1989
2032
            return self._branch_class()(_format=self,
1990
2033
                              _control_files=control_files,
1991
2034
                              name=name,
1992
2035
                              a_bzrdir=a_bzrdir,
1993
 
                              _repository=a_bzrdir.find_repository(),
 
2036
                              _repository=found_repository,
1994
2037
                              ignore_fallbacks=ignore_fallbacks)
1995
2038
        except errors.NoSuchFile:
1996
2039
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
2003
2046
    def supports_tags(self):
2004
2047
        return True
2005
2048
 
 
2049
    def supports_leaving_lock(self):
 
2050
        return True
 
2051
 
2006
2052
 
2007
2053
class BzrBranchFormat5(BranchFormatMetadir):
2008
2054
    """Bzr branch format 5.
2028
2074
        """See BranchFormat.get_format_description()."""
2029
2075
        return "Branch format 5"
2030
2076
 
2031
 
    def initialize(self, a_bzrdir, name=None):
 
2077
    def initialize(self, a_bzrdir, name=None, repository=None):
2032
2078
        """Create a branch of this format in a_bzrdir."""
2033
2079
        utf8_files = [('revision-history', ''),
2034
2080
                      ('branch-name', ''),
2035
2081
                      ]
2036
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2082
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2037
2083
 
2038
2084
    def supports_tags(self):
2039
2085
        return False
2061
2107
        """See BranchFormat.get_format_description()."""
2062
2108
        return "Branch format 6"
2063
2109
 
2064
 
    def initialize(self, a_bzrdir, name=None):
 
2110
    def initialize(self, a_bzrdir, name=None, repository=None):
2065
2111
        """Create a branch of this format in a_bzrdir."""
2066
2112
        utf8_files = [('last-revision', '0 null:\n'),
2067
2113
                      ('branch.conf', ''),
2068
2114
                      ('tags', ''),
2069
2115
                      ]
2070
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2116
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2071
2117
 
2072
2118
    def make_tags(self, branch):
2073
2119
        """See bzrlib.branch.BranchFormat.make_tags()."""
2091
2137
        """See BranchFormat.get_format_description()."""
2092
2138
        return "Branch format 8"
2093
2139
 
2094
 
    def initialize(self, a_bzrdir, name=None):
 
2140
    def initialize(self, a_bzrdir, name=None, repository=None):
2095
2141
        """Create a branch of this format in a_bzrdir."""
2096
2142
        utf8_files = [('last-revision', '0 null:\n'),
2097
2143
                      ('branch.conf', ''),
2098
2144
                      ('tags', ''),
2099
2145
                      ('references', '')
2100
2146
                      ]
2101
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
2102
 
 
2103
 
    def __init__(self):
2104
 
        super(BzrBranchFormat8, self).__init__()
2105
 
        self._matchingbzrdir.repository_format = \
2106
 
            RepositoryFormatKnitPack5RichRoot()
 
2147
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2107
2148
 
2108
2149
    def make_tags(self, branch):
2109
2150
        """See bzrlib.branch.BranchFormat.make_tags()."""
2118
2159
    supports_reference_locations = True
2119
2160
 
2120
2161
 
2121
 
class BzrBranchFormat7(BzrBranchFormat8):
 
2162
class BzrBranchFormat7(BranchFormatMetadir):
2122
2163
    """Branch format with last-revision, tags, and a stacked location pointer.
2123
2164
 
2124
2165
    The stacked location pointer is passed down to the repository and requires
2127
2168
    This format was introduced in bzr 1.6.
2128
2169
    """
2129
2170
 
2130
 
    def initialize(self, a_bzrdir, name=None):
 
2171
    def initialize(self, a_bzrdir, name=None, repository=None):
2131
2172
        """Create a branch of this format in a_bzrdir."""
2132
2173
        utf8_files = [('last-revision', '0 null:\n'),
2133
2174
                      ('branch.conf', ''),
2134
2175
                      ('tags', ''),
2135
2176
                      ]
2136
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2177
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2137
2178
 
2138
2179
    def _branch_class(self):
2139
2180
        return BzrBranch7
2149
2190
    def supports_set_append_revisions_only(self):
2150
2191
        return True
2151
2192
 
 
2193
    def supports_stacking(self):
 
2194
        return True
 
2195
 
 
2196
    def make_tags(self, branch):
 
2197
        """See bzrlib.branch.BranchFormat.make_tags()."""
 
2198
        return BasicTags(branch)
 
2199
 
2152
2200
    supports_reference_locations = False
2153
2201
 
2154
2202
 
2181
2229
        transport = a_bzrdir.get_branch_transport(None, name=name)
2182
2230
        location = transport.put_bytes('location', to_branch.base)
2183
2231
 
2184
 
    def initialize(self, a_bzrdir, name=None, target_branch=None):
 
2232
    def initialize(self, a_bzrdir, name=None, target_branch=None,
 
2233
            repository=None):
2185
2234
        """Create a branch of this format in a_bzrdir."""
2186
2235
        if target_branch is None:
2187
2236
            # this format does not implement branch itself, thus the implicit
2215
2264
        return clone
2216
2265
 
2217
2266
    def open(self, a_bzrdir, name=None, _found=False, location=None,
2218
 
             possible_transports=None, ignore_fallbacks=False):
 
2267
             possible_transports=None, ignore_fallbacks=False,
 
2268
             found_repository=None):
2219
2269
        """Return the branch that the branch reference in a_bzrdir points at.
2220
2270
 
2221
2271
        :param a_bzrdir: A BzrDir that contains a branch.
2252
2302
        return result
2253
2303
 
2254
2304
 
 
2305
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
 
2306
    """Branch format registry."""
 
2307
 
 
2308
    def __init__(self, other_registry=None):
 
2309
        super(BranchFormatRegistry, self).__init__(other_registry)
 
2310
        self._default_format = None
 
2311
 
 
2312
    def set_default(self, format):
 
2313
        self._default_format = format
 
2314
 
 
2315
    def get_default(self):
 
2316
        return self._default_format
 
2317
 
 
2318
 
2255
2319
network_format_registry = registry.FormatRegistry()
2256
2320
"""Registry of formats indexed by their network name.
2257
2321
 
2260
2324
BranchFormat.network_name() for more detail.
2261
2325
"""
2262
2326
 
 
2327
format_registry = BranchFormatRegistry(network_format_registry)
 
2328
 
2263
2329
 
2264
2330
# formats which have no format string are not discoverable
2265
2331
# and not independently creatable, so are not registered.
2267
2333
__format6 = BzrBranchFormat6()
2268
2334
__format7 = BzrBranchFormat7()
2269
2335
__format8 = BzrBranchFormat8()
2270
 
BranchFormat.register_format(__format5)
2271
 
BranchFormat.register_format(BranchReferenceFormat())
2272
 
BranchFormat.register_format(__format6)
2273
 
BranchFormat.register_format(__format7)
2274
 
BranchFormat.register_format(__format8)
2275
 
BranchFormat.set_default_format(__format7)
2276
 
_legacy_formats = [BzrBranchFormat4(),
2277
 
    ]
2278
 
network_format_registry.register(
2279
 
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
 
2336
format_registry.register(__format5)
 
2337
format_registry.register(BranchReferenceFormat())
 
2338
format_registry.register(__format6)
 
2339
format_registry.register(__format7)
 
2340
format_registry.register(__format8)
 
2341
format_registry.set_default(__format7)
2280
2342
 
2281
2343
 
2282
2344
class BranchWriteLockResult(LogicalLockResult):
2439
2501
            'revision-history', '\n'.join(history),
2440
2502
            mode=self.bzrdir._get_file_mode())
2441
2503
 
2442
 
    @needs_write_lock
 
2504
    @deprecated_method(deprecated_in((2, 4, 0)))
2443
2505
    def set_revision_history(self, rev_history):
2444
2506
        """See Branch.set_revision_history."""
 
2507
        self._set_revision_history(rev_history)
 
2508
 
 
2509
    @needs_write_lock
 
2510
    def _set_revision_history(self, rev_history):
2445
2511
        if 'evil' in debug.debug_flags:
2446
2512
            mutter_callsite(3, "set_revision_history scales with history.")
2447
2513
        check_not_reserved_id = _mod_revision.check_not_reserved_id
2491
2557
            except ValueError:
2492
2558
                rev = self.repository.get_revision(revision_id)
2493
2559
                new_history = rev.get_history(self.repository)[1:]
2494
 
        destination.set_revision_history(new_history)
 
2560
        destination._set_revision_history(new_history)
2495
2561
 
2496
2562
    @needs_write_lock
2497
2563
    def set_last_revision_info(self, revno, revision_id):
2505
2571
        configured to check constraints on history, in which case this may not
2506
2572
        be permitted.
2507
2573
        """
2508
 
        revision_id = _mod_revision.ensure_null(revision_id)
 
2574
        if not revision_id or not isinstance(revision_id, basestring):
 
2575
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2509
2576
        # this old format stores the full history, but this api doesn't
2510
2577
        # provide it, so we must generate, and might as well check it's
2511
2578
        # correct
2512
2579
        history = self._lefthand_history(revision_id)
2513
2580
        if len(history) != revno:
2514
2581
            raise AssertionError('%d != %d' % (len(history), revno))
2515
 
        self.set_revision_history(history)
 
2582
        self._set_revision_history(history)
2516
2583
 
2517
2584
    def _gen_revision_history(self):
2518
2585
        history = self._transport.get_bytes('revision-history').split('\n')
2532
2599
        :param other_branch: The other branch that DivergedBranches should
2533
2600
            raise with respect to.
2534
2601
        """
2535
 
        self.set_revision_history(self._lefthand_history(revision_id,
 
2602
        self._set_revision_history(self._lefthand_history(revision_id,
2536
2603
            last_rev, other_branch))
2537
2604
 
2538
2605
    def basis_tree(self):
2558
2625
        result.target_branch = target
2559
2626
        result.old_revno, result.old_revid = target.last_revision_info()
2560
2627
        self.update_references(target)
2561
 
        if result.old_revid != self.last_revision():
 
2628
        if result.old_revid != stop_revision:
2562
2629
            # We assume that during 'push' this repository is closer than
2563
2630
            # the target.
2564
2631
            graph = self.repository.get_graph(target.repository)
2565
2632
            target.update_revisions(self, stop_revision,
2566
2633
                overwrite=overwrite, graph=graph)
2567
2634
        if self._push_should_merge_tags():
2568
 
            result.tag_conflicts = self.tags.merge_to(target.tags,
2569
 
                overwrite)
 
2635
            result.tag_conflicts = self.tags.merge_to(target.tags, overwrite)
2570
2636
        result.new_revno, result.new_revid = target.last_revision_info()
2571
2637
        return result
2572
2638
 
2604
2670
        """Return the branch we are bound to.
2605
2671
 
2606
2672
        :return: Either a Branch, or None
2607
 
 
2608
 
        This could memoise the branch, but if thats done
2609
 
        it must be revalidated on each new lock.
2610
 
        So for now we just don't memoise it.
2611
 
        # RBC 20060304 review this decision.
2612
2673
        """
 
2674
        if self._master_branch_cache is None:
 
2675
            self._master_branch_cache = self._get_master_branch(
 
2676
                possible_transports)
 
2677
        return self._master_branch_cache
 
2678
 
 
2679
    def _get_master_branch(self, possible_transports):
2613
2680
        bound_loc = self.get_bound_location()
2614
2681
        if not bound_loc:
2615
2682
            return None
2626
2693
 
2627
2694
        :param location: URL to the target branch
2628
2695
        """
 
2696
        self._master_branch_cache = None
2629
2697
        if location:
2630
2698
            self._transport.put_bytes('bound', location+'\n',
2631
2699
                mode=self.bzrdir._get_file_mode())
2740
2808
 
2741
2809
    @needs_write_lock
2742
2810
    def set_last_revision_info(self, revno, revision_id):
2743
 
        revision_id = _mod_revision.ensure_null(revision_id)
 
2811
        if not revision_id or not isinstance(revision_id, basestring):
 
2812
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2744
2813
        old_revno, old_revid = self.last_revision_info()
2745
2814
        if self._get_append_revisions_only():
2746
2815
            self._check_history_violation(revision_id)
2883
2952
 
2884
2953
    def set_bound_location(self, location):
2885
2954
        """See Branch.set_push_location."""
 
2955
        self._master_branch_cache = None
2886
2956
        result = None
2887
2957
        config = self.get_config()
2888
2958
        if location is None:
2965
3035
        try:
2966
3036
            index = self._partial_revision_history_cache.index(revision_id)
2967
3037
        except ValueError:
2968
 
            self._extend_partial_history(stop_revision=revision_id)
 
3038
            try:
 
3039
                self._extend_partial_history(stop_revision=revision_id)
 
3040
            except errors.RevisionNotPresent, e:
 
3041
                raise errors.GhostRevisionsHaveNoRevno(revision_id, e.revision_id)
2969
3042
            index = len(self._partial_revision_history_cache) - 1
2970
3043
            if self._partial_revision_history_cache[index] != revision_id:
2971
3044
                raise errors.NoSuchRevision(self, revision_id)
3026
3099
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
3027
3100
    """
3028
3101
 
 
3102
    @deprecated_method(deprecated_in((2, 3, 0)))
3029
3103
    def __int__(self):
3030
 
        # DEPRECATED: pull used to return the change in revno
 
3104
        """Return the relative change in revno.
 
3105
 
 
3106
        :deprecated: Use `new_revno` and `old_revno` instead.
 
3107
        """
3031
3108
        return self.new_revno - self.old_revno
3032
3109
 
3033
3110
    def report(self, to_file):
3058
3135
        target, otherwise it will be None.
3059
3136
    """
3060
3137
 
 
3138
    @deprecated_method(deprecated_in((2, 3, 0)))
3061
3139
    def __int__(self):
3062
 
        # DEPRECATED: push used to return the change in revno
 
3140
        """Return the relative change in revno.
 
3141
 
 
3142
        :deprecated: Use `new_revno` and `old_revno` instead.
 
3143
        """
3063
3144
        return self.new_revno - self.old_revno
3064
3145
 
3065
3146
    def report(self, to_file):
3188
3269
    _optimisers = []
3189
3270
    """The available optimised InterBranch types."""
3190
3271
 
3191
 
    @staticmethod
3192
 
    def _get_branch_formats_to_test():
3193
 
        """Return a tuple with the Branch formats to use when testing."""
3194
 
        raise NotImplementedError(InterBranch._get_branch_formats_to_test)
 
3272
    @classmethod
 
3273
    def _get_branch_formats_to_test(klass):
 
3274
        """Return an iterable of format tuples for testing.
 
3275
        
 
3276
        :return: An iterable of (from_format, to_format) to use when testing
 
3277
            this InterBranch class. Each InterBranch class should define this
 
3278
            method itself.
 
3279
        """
 
3280
        raise NotImplementedError(klass._get_branch_formats_to_test)
3195
3281
 
 
3282
    @needs_write_lock
3196
3283
    def pull(self, overwrite=False, stop_revision=None,
3197
3284
             possible_transports=None, local=False):
3198
3285
        """Mirror source into target branch.
3203
3290
        """
3204
3291
        raise NotImplementedError(self.pull)
3205
3292
 
 
3293
    @needs_write_lock
3206
3294
    def update_revisions(self, stop_revision=None, overwrite=False,
3207
 
                         graph=None):
 
3295
            graph=None):
3208
3296
        """Pull in new perfect-fit revisions.
3209
3297
 
3210
3298
        :param stop_revision: Updated until the given revision
3216
3304
        """
3217
3305
        raise NotImplementedError(self.update_revisions)
3218
3306
 
 
3307
    @needs_write_lock
3219
3308
    def push(self, overwrite=False, stop_revision=None,
3220
3309
             _override_hook_source_branch=None):
3221
3310
        """Mirror the source branch into the target branch.
3224
3313
        """
3225
3314
        raise NotImplementedError(self.push)
3226
3315
 
 
3316
    @needs_write_lock
 
3317
    def copy_content_into(self, revision_id=None):
 
3318
        """Copy the content of source into target
 
3319
 
 
3320
        revision_id: if not None, the revision history in the new branch will
 
3321
                     be truncated to end with revision_id.
 
3322
        """
 
3323
        raise NotImplementedError(self.copy_content_into)
 
3324
 
 
3325
    @needs_write_lock
 
3326
    def fetch(self, stop_revision=None):
 
3327
        """Fetch revisions.
 
3328
 
 
3329
        :param stop_revision: Last revision to fetch
 
3330
        """
 
3331
        raise NotImplementedError(self.fetch)
 
3332
 
3227
3333
 
3228
3334
class GenericInterBranch(InterBranch):
3229
 
    """InterBranch implementation that uses public Branch functions.
3230
 
    """
3231
 
 
3232
 
    @staticmethod
3233
 
    def _get_branch_formats_to_test():
3234
 
        return BranchFormat._default_format, BranchFormat._default_format
3235
 
 
 
3335
    """InterBranch implementation that uses public Branch functions."""
 
3336
 
 
3337
    @classmethod
 
3338
    def is_compatible(klass, source, target):
 
3339
        # GenericBranch uses the public API, so always compatible
 
3340
        return True
 
3341
 
 
3342
    @classmethod
 
3343
    def _get_branch_formats_to_test(klass):
 
3344
        return [(format_registry.get_default(), format_registry.get_default())]
 
3345
 
 
3346
    @classmethod
 
3347
    def unwrap_format(klass, format):
 
3348
        if isinstance(format, remote.RemoteBranchFormat):
 
3349
            format._ensure_real()
 
3350
            return format._custom_format
 
3351
        return format
 
3352
 
 
3353
    @needs_write_lock
 
3354
    def copy_content_into(self, revision_id=None):
 
3355
        """Copy the content of source into target
 
3356
 
 
3357
        revision_id: if not None, the revision history in the new branch will
 
3358
                     be truncated to end with revision_id.
 
3359
        """
 
3360
        self.source.update_references(self.target)
 
3361
        self.source._synchronize_history(self.target, revision_id)
 
3362
        try:
 
3363
            parent = self.source.get_parent()
 
3364
        except errors.InaccessibleParent, e:
 
3365
            mutter('parent was not accessible to copy: %s', e)
 
3366
        else:
 
3367
            if parent:
 
3368
                self.target.set_parent(parent)
 
3369
        if self.source._push_should_merge_tags():
 
3370
            self.source.tags.merge_to(self.target.tags)
 
3371
 
 
3372
    @needs_write_lock
 
3373
    def fetch(self, stop_revision=None):
 
3374
        if self.target.base == self.source.base:
 
3375
            return (0, [])
 
3376
        self.source.lock_read()
 
3377
        try:
 
3378
            fetch_spec_factory = fetch.FetchSpecFactory()
 
3379
            fetch_spec_factory.source_branch = self.source
 
3380
            fetch_spec_factory.source_branch_stop_revision_id = stop_revision
 
3381
            fetch_spec_factory.source_repo = self.source.repository
 
3382
            fetch_spec_factory.target_repo = self.target.repository
 
3383
            fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
 
3384
            fetch_spec = fetch_spec_factory.make_fetch_spec()
 
3385
            return self.target.repository.fetch(self.source.repository,
 
3386
                fetch_spec=fetch_spec)
 
3387
        finally:
 
3388
            self.source.unlock()
 
3389
 
 
3390
    @needs_write_lock
3236
3391
    def update_revisions(self, stop_revision=None, overwrite=False,
3237
 
        graph=None):
 
3392
            graph=None):
3238
3393
        """See InterBranch.update_revisions()."""
3239
 
        self.source.lock_read()
3240
 
        try:
3241
 
            other_revno, other_last_revision = self.source.last_revision_info()
3242
 
            stop_revno = None # unknown
3243
 
            if stop_revision is None:
3244
 
                stop_revision = other_last_revision
3245
 
                if _mod_revision.is_null(stop_revision):
3246
 
                    # if there are no commits, we're done.
3247
 
                    return
3248
 
                stop_revno = other_revno
3249
 
 
3250
 
            # what's the current last revision, before we fetch [and change it
3251
 
            # possibly]
3252
 
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
3253
 
            # we fetch here so that we don't process data twice in the common
3254
 
            # case of having something to pull, and so that the check for
3255
 
            # already merged can operate on the just fetched graph, which will
3256
 
            # be cached in memory.
3257
 
            self.target.fetch(self.source, stop_revision)
3258
 
            # Check to see if one is an ancestor of the other
3259
 
            if not overwrite:
3260
 
                if graph is None:
3261
 
                    graph = self.target.repository.get_graph()
3262
 
                if self.target._check_if_descendant_or_diverged(
3263
 
                        stop_revision, last_rev, graph, self.source):
3264
 
                    # stop_revision is a descendant of last_rev, but we aren't
3265
 
                    # overwriting, so we're done.
3266
 
                    return
3267
 
            if stop_revno is None:
3268
 
                if graph is None:
3269
 
                    graph = self.target.repository.get_graph()
3270
 
                this_revno, this_last_revision = \
3271
 
                        self.target.last_revision_info()
3272
 
                stop_revno = graph.find_distance_to_null(stop_revision,
3273
 
                                [(other_last_revision, other_revno),
3274
 
                                 (this_last_revision, this_revno)])
3275
 
            self.target.set_last_revision_info(stop_revno, stop_revision)
3276
 
        finally:
3277
 
            self.source.unlock()
3278
 
 
 
3394
        other_revno, other_last_revision = self.source.last_revision_info()
 
3395
        stop_revno = None # unknown
 
3396
        if stop_revision is None:
 
3397
            stop_revision = other_last_revision
 
3398
            if _mod_revision.is_null(stop_revision):
 
3399
                # if there are no commits, we're done.
 
3400
                return
 
3401
            stop_revno = other_revno
 
3402
 
 
3403
        # what's the current last revision, before we fetch [and change it
 
3404
        # possibly]
 
3405
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
3406
        # we fetch here so that we don't process data twice in the common
 
3407
        # case of having something to pull, and so that the check for
 
3408
        # already merged can operate on the just fetched graph, which will
 
3409
        # be cached in memory.
 
3410
        self.fetch(stop_revision=stop_revision)
 
3411
        # Check to see if one is an ancestor of the other
 
3412
        if not overwrite:
 
3413
            if graph is None:
 
3414
                graph = self.target.repository.get_graph()
 
3415
            if self.target._check_if_descendant_or_diverged(
 
3416
                    stop_revision, last_rev, graph, self.source):
 
3417
                # stop_revision is a descendant of last_rev, but we aren't
 
3418
                # overwriting, so we're done.
 
3419
                return
 
3420
        if stop_revno is None:
 
3421
            if graph is None:
 
3422
                graph = self.target.repository.get_graph()
 
3423
            this_revno, this_last_revision = \
 
3424
                    self.target.last_revision_info()
 
3425
            stop_revno = graph.find_distance_to_null(stop_revision,
 
3426
                            [(other_last_revision, other_revno),
 
3427
                             (this_last_revision, this_revno)])
 
3428
        self.target.set_last_revision_info(stop_revno, stop_revision)
 
3429
 
 
3430
    @needs_write_lock
3279
3431
    def pull(self, overwrite=False, stop_revision=None,
3280
 
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3432
             possible_transports=None, run_hooks=True,
3281
3433
             _override_hook_target=None, local=False):
3282
 
        """See Branch.pull.
 
3434
        """Pull from source into self, updating my master if any.
3283
3435
 
3284
 
        :param _hook_master: Private parameter - set the branch to
3285
 
            be supplied as the master to pull hooks.
3286
3436
        :param run_hooks: Private parameter - if false, this branch
3287
3437
            is being called because it's the master of the primary branch,
3288
3438
            so it should not run its hooks.
3289
 
        :param _override_hook_target: Private parameter - set the branch to be
3290
 
            supplied as the target_branch to pull hooks.
3291
 
        :param local: Only update the local branch, and not the bound branch.
3292
3439
        """
3293
 
        # This type of branch can't be bound.
3294
 
        if local:
 
3440
        bound_location = self.target.get_bound_location()
 
3441
        if local and not bound_location:
3295
3442
            raise errors.LocalRequiresBoundBranch()
3296
 
        result = PullResult()
3297
 
        result.source_branch = self.source
3298
 
        if _override_hook_target is None:
3299
 
            result.target_branch = self.target
3300
 
        else:
3301
 
            result.target_branch = _override_hook_target
3302
 
        self.source.lock_read()
 
3443
        master_branch = None
 
3444
        source_is_master = (self.source.user_url == bound_location)
 
3445
        if not local and bound_location and not source_is_master:
 
3446
            # not pulling from master, so we need to update master.
 
3447
            master_branch = self.target.get_master_branch(possible_transports)
 
3448
            master_branch.lock_write()
3303
3449
        try:
3304
 
            # We assume that during 'pull' the target repository is closer than
3305
 
            # the source one.
3306
 
            self.source.update_references(self.target)
3307
 
            graph = self.target.repository.get_graph(self.source.repository)
3308
 
            # TODO: Branch formats should have a flag that indicates 
3309
 
            # that revno's are expensive, and pull() should honor that flag.
3310
 
            # -- JRV20090506
3311
 
            result.old_revno, result.old_revid = \
3312
 
                self.target.last_revision_info()
3313
 
            self.target.update_revisions(self.source, stop_revision,
3314
 
                overwrite=overwrite, graph=graph)
3315
 
            # TODO: The old revid should be specified when merging tags, 
3316
 
            # so a tags implementation that versions tags can only 
3317
 
            # pull in the most recent changes. -- JRV20090506
3318
 
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3319
 
                overwrite)
3320
 
            result.new_revno, result.new_revid = self.target.last_revision_info()
3321
 
            if _hook_master:
3322
 
                result.master_branch = _hook_master
3323
 
                result.local_branch = result.target_branch
3324
 
            else:
3325
 
                result.master_branch = result.target_branch
3326
 
                result.local_branch = None
3327
 
            if run_hooks:
3328
 
                for hook in Branch.hooks['post_pull']:
3329
 
                    hook(result)
 
3450
            if master_branch:
 
3451
                # pull from source into master.
 
3452
                master_branch.pull(self.source, overwrite, stop_revision,
 
3453
                    run_hooks=False)
 
3454
            return self._pull(overwrite,
 
3455
                stop_revision, _hook_master=master_branch,
 
3456
                run_hooks=run_hooks,
 
3457
                _override_hook_target=_override_hook_target,
 
3458
                merge_tags_to_master=not source_is_master)
3330
3459
        finally:
3331
 
            self.source.unlock()
3332
 
        return result
 
3460
            if master_branch:
 
3461
                master_branch.unlock()
3333
3462
 
3334
3463
    def push(self, overwrite=False, stop_revision=None,
3335
3464
             _override_hook_source_branch=None):
3375
3504
                # push into the master from the source branch.
3376
3505
                self.source._basic_push(master_branch, overwrite, stop_revision)
3377
3506
                # and push into the target branch from the source. Note that we
3378
 
                # push from the source branch again, because its considered the
 
3507
                # push from the source branch again, because it's considered the
3379
3508
                # highest bandwidth repository.
3380
3509
                result = self.source._basic_push(self.target, overwrite,
3381
3510
                    stop_revision)
3397
3526
            _run_hooks()
3398
3527
            return result
3399
3528
 
3400
 
    @classmethod
3401
 
    def is_compatible(self, source, target):
3402
 
        # GenericBranch uses the public API, so always compatible
3403
 
        return True
3404
 
 
3405
 
 
3406
 
class InterToBranch5(GenericInterBranch):
3407
 
 
3408
 
    @staticmethod
3409
 
    def _get_branch_formats_to_test():
3410
 
        return BranchFormat._default_format, BzrBranchFormat5()
3411
 
 
3412
 
    def pull(self, overwrite=False, stop_revision=None,
3413
 
             possible_transports=None, run_hooks=True,
3414
 
             _override_hook_target=None, local=False):
3415
 
        """Pull from source into self, updating my master if any.
3416
 
 
 
3529
    def _pull(self, overwrite=False, stop_revision=None,
 
3530
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3531
             _override_hook_target=None, local=False,
 
3532
             merge_tags_to_master=True):
 
3533
        """See Branch.pull.
 
3534
 
 
3535
        This function is the core worker, used by GenericInterBranch.pull to
 
3536
        avoid duplication when pulling source->master and source->local.
 
3537
 
 
3538
        :param _hook_master: Private parameter - set the branch to
 
3539
            be supplied as the master to pull hooks.
3417
3540
        :param run_hooks: Private parameter - if false, this branch
3418
3541
            is being called because it's the master of the primary branch,
3419
3542
            so it should not run its hooks.
 
3543
            is being called because it's the master of the primary branch,
 
3544
            so it should not run its hooks.
 
3545
        :param _override_hook_target: Private parameter - set the branch to be
 
3546
            supplied as the target_branch to pull hooks.
 
3547
        :param local: Only update the local branch, and not the bound branch.
3420
3548
        """
3421
 
        bound_location = self.target.get_bound_location()
3422
 
        if local and not bound_location:
 
3549
        # This type of branch can't be bound.
 
3550
        if local:
3423
3551
            raise errors.LocalRequiresBoundBranch()
3424
 
        master_branch = None
3425
 
        if not local and bound_location and self.source.user_url != bound_location:
3426
 
            # not pulling from master, so we need to update master.
3427
 
            master_branch = self.target.get_master_branch(possible_transports)
3428
 
            master_branch.lock_write()
 
3552
        result = PullResult()
 
3553
        result.source_branch = self.source
 
3554
        if _override_hook_target is None:
 
3555
            result.target_branch = self.target
 
3556
        else:
 
3557
            result.target_branch = _override_hook_target
 
3558
        self.source.lock_read()
3429
3559
        try:
3430
 
            if master_branch:
3431
 
                # pull from source into master.
3432
 
                master_branch.pull(self.source, overwrite, stop_revision,
3433
 
                    run_hooks=False)
3434
 
            return super(InterToBranch5, self).pull(overwrite,
3435
 
                stop_revision, _hook_master=master_branch,
3436
 
                run_hooks=run_hooks,
3437
 
                _override_hook_target=_override_hook_target)
 
3560
            # We assume that during 'pull' the target repository is closer than
 
3561
            # the source one.
 
3562
            self.source.update_references(self.target)
 
3563
            graph = self.target.repository.get_graph(self.source.repository)
 
3564
            # TODO: Branch formats should have a flag that indicates 
 
3565
            # that revno's are expensive, and pull() should honor that flag.
 
3566
            # -- JRV20090506
 
3567
            result.old_revno, result.old_revid = \
 
3568
                self.target.last_revision_info()
 
3569
            self.target.update_revisions(self.source, stop_revision,
 
3570
                overwrite=overwrite, graph=graph)
 
3571
            # TODO: The old revid should be specified when merging tags, 
 
3572
            # so a tags implementation that versions tags can only 
 
3573
            # pull in the most recent changes. -- JRV20090506
 
3574
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
3575
                overwrite, ignore_master=not merge_tags_to_master)
 
3576
            result.new_revno, result.new_revid = self.target.last_revision_info()
 
3577
            if _hook_master:
 
3578
                result.master_branch = _hook_master
 
3579
                result.local_branch = result.target_branch
 
3580
            else:
 
3581
                result.master_branch = result.target_branch
 
3582
                result.local_branch = None
 
3583
            if run_hooks:
 
3584
                for hook in Branch.hooks['post_pull']:
 
3585
                    hook(result)
3438
3586
        finally:
3439
 
            if master_branch:
3440
 
                master_branch.unlock()
 
3587
            self.source.unlock()
 
3588
        return result
3441
3589
 
3442
3590
 
3443
3591
InterBranch.register_optimiser(GenericInterBranch)
3444
 
InterBranch.register_optimiser(InterToBranch5)