/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-04-05 14:47:30 UTC
  • mto: (5757.7.2 knitpackrepo-6)
  • mto: This revision was merged to the branch mainline in revision 5771.
  • Revision ID: jelmer@samba.org-20110405144730-uq6jmlblh97plv20
Add separate file for knit pack repository formats.

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
 
45
from bzrlib.repofmt.knitpack_repo import RepositoryFormatKnitPack5RichRoot
43
46
from bzrlib.tag import (
44
47
    BasicTags,
45
48
    DisabledTags,
46
49
    )
47
50
""")
48
51
 
49
 
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
50
 
from bzrlib.hooks import HookPoint, Hooks
 
52
from bzrlib import (
 
53
    controldir,
 
54
    )
 
55
from bzrlib.decorators import (
 
56
    needs_read_lock,
 
57
    needs_write_lock,
 
58
    only_raises,
 
59
    )
 
60
from bzrlib.hooks import Hooks
51
61
from bzrlib.inter import InterObject
52
 
from bzrlib.lock import _RelockDebugMixin
 
62
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
53
63
from bzrlib import registry
54
64
from bzrlib.symbol_versioning import (
55
65
    deprecated_in,
63
73
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
64
74
 
65
75
 
66
 
class Branch(bzrdir.ControlComponent):
 
76
class Branch(controldir.ControlComponent):
67
77
    """Branch holding a history of revisions.
68
78
 
69
79
    :ivar base:
70
80
        Base directory/url of the branch; using control_url and
71
81
        control_transport is more standardized.
72
 
 
73
 
    hooks: An instance of BranchHooks.
 
82
    :ivar hooks: An instance of BranchHooks.
 
83
    :ivar _master_branch_cache: cached result of get_master_branch, see
 
84
        _clear_cached_state.
74
85
    """
75
86
    # this is really an instance variable - FIXME move it there
76
87
    # - RBC 20060112
90
101
        self._revision_id_to_revno_cache = None
91
102
        self._partial_revision_id_to_revno_cache = {}
92
103
        self._partial_revision_history_cache = []
 
104
        self._tags_bytes = None
93
105
        self._last_revision_info_cache = None
 
106
        self._master_branch_cache = None
94
107
        self._merge_sorted_revisions_cache = None
95
108
        self._open_hook()
96
109
        hooks = Branch.hooks['open']
102
115
 
103
116
    def _activate_fallback_location(self, url):
104
117
        """Activate the branch/repository from url as a fallback repository."""
 
118
        for existing_fallback_repo in self.repository._fallback_repositories:
 
119
            if existing_fallback_repo.user_url == url:
 
120
                # This fallback is already configured.  This probably only
 
121
                # happens because BzrDir.sprout is a horrible mess.  To avoid
 
122
                # confusing _unstack we don't add this a second time.
 
123
                mutter('duplicate activation of fallback %r on %r', url, self)
 
124
                return
105
125
        repo = self._get_fallback_repository(url)
106
126
        if repo.has_same_location(self.repository):
107
127
            raise errors.UnstackableLocationError(self.user_url, url)
197
217
        return self.supports_tags() and self.tags.get_tag_dict()
198
218
 
199
219
    def get_config(self):
 
220
        """Get a bzrlib.config.BranchConfig for this Branch.
 
221
 
 
222
        This can then be used to get and set configuration options for the
 
223
        branch.
 
224
 
 
225
        :return: A bzrlib.config.BranchConfig.
 
226
        """
200
227
        return BranchConfig(self)
201
228
 
202
229
    def _get_config(self):
218
245
            possible_transports=[self.bzrdir.root_transport])
219
246
        return a_branch.repository
220
247
 
 
248
    @needs_read_lock
221
249
    def _get_tags_bytes(self):
222
250
        """Get the bytes of a serialised tags dict.
223
251
 
230
258
        :return: The bytes of the tags file.
231
259
        :seealso: Branch._set_tags_bytes.
232
260
        """
233
 
        return self._transport.get_bytes('tags')
 
261
        if self._tags_bytes is None:
 
262
            self._tags_bytes = self._transport.get_bytes('tags')
 
263
        return self._tags_bytes
234
264
 
235
265
    def _get_nick(self, local=False, possible_transports=None):
236
266
        config = self.get_config()
238
268
        if not local and not config.has_explicit_nickname():
239
269
            try:
240
270
                master = self.get_master_branch(possible_transports)
 
271
                if master and self.user_url == master.user_url:
 
272
                    raise errors.RecursiveBind(self.user_url)
241
273
                if master is not None:
242
274
                    # return the master branch value
243
275
                    return master.nick
 
276
            except errors.RecursiveBind, e:
 
277
                raise e
244
278
            except errors.BzrError, e:
245
279
                # Silently fall back to local implicit nick if the master is
246
280
                # unavailable
283
317
        new_history.reverse()
284
318
        return new_history
285
319
 
286
 
    def lock_write(self):
 
320
    def lock_write(self, token=None):
 
321
        """Lock the branch for write operations.
 
322
 
 
323
        :param token: A token to permit reacquiring a previously held and
 
324
            preserved lock.
 
325
        :return: A BranchWriteLockResult.
 
326
        """
287
327
        raise NotImplementedError(self.lock_write)
288
328
 
289
329
    def lock_read(self):
 
330
        """Lock the branch for read operations.
 
331
 
 
332
        :return: A bzrlib.lock.LogicalLockResult.
 
333
        """
290
334
        raise NotImplementedError(self.lock_read)
291
335
 
292
336
    def unlock(self):
626
670
        raise errors.UnsupportedOperation(self.get_reference_info, self)
627
671
 
628
672
    @needs_write_lock
629
 
    def fetch(self, from_branch, last_revision=None, pb=None):
 
673
    def fetch(self, from_branch, last_revision=None, fetch_spec=None):
630
674
        """Copy revisions from from_branch into this branch.
631
675
 
632
676
        :param from_branch: Where to copy from.
633
677
        :param last_revision: What revision to stop at (None for at the end
634
678
                              of the branch.
635
 
        :param pb: An optional progress bar to use.
 
679
        :param fetch_spec: If specified, a SearchResult or
 
680
            PendingAncestryResult that describes which revisions to copy.  This
 
681
            allows copying multiple heads at once.  Mutually exclusive with
 
682
            last_revision.
636
683
        :return: None
637
684
        """
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()
 
685
        return InterBranch.get(from_branch, self).fetch(last_revision,
 
686
            fetch_spec)
654
687
 
655
688
    def get_bound_location(self):
656
689
        """Return the URL of the branch we are bound to.
767
800
 
768
801
    def _unstack(self):
769
802
        """Change a branch to be unstacked, copying data as needed.
770
 
        
 
803
 
771
804
        Don't call this directly, use set_stacked_on_url(None).
772
805
        """
773
806
        pb = ui.ui_factory.nested_progress_bar()
782
815
            old_repository = self.repository
783
816
            if len(old_repository._fallback_repositories) != 1:
784
817
                raise AssertionError("can't cope with fallback repositories "
785
 
                    "of %r" % (self.repository,))
786
 
            # unlock it, including unlocking the fallback
 
818
                    "of %r (fallbacks: %r)" % (old_repository,
 
819
                        old_repository._fallback_repositories))
 
820
            # Open the new repository object.
 
821
            # Repositories don't offer an interface to remove fallback
 
822
            # repositories today; take the conceptually simpler option and just
 
823
            # reopen it.  We reopen it starting from the URL so that we
 
824
            # get a separate connection for RemoteRepositories and can
 
825
            # stream from one of them to the other.  This does mean doing
 
826
            # separate SSH connection setup, but unstacking is not a
 
827
            # common operation so it's tolerable.
 
828
            new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
 
829
            new_repository = new_bzrdir.find_repository()
 
830
            if new_repository._fallback_repositories:
 
831
                raise AssertionError("didn't expect %r to have "
 
832
                    "fallback_repositories"
 
833
                    % (self.repository,))
 
834
            # Replace self.repository with the new repository.
 
835
            # Do our best to transfer the lock state (i.e. lock-tokens and
 
836
            # lock count) of self.repository to the new repository.
 
837
            lock_token = old_repository.lock_write().repository_token
 
838
            self.repository = new_repository
 
839
            if isinstance(self, remote.RemoteBranch):
 
840
                # Remote branches can have a second reference to the old
 
841
                # repository that need to be replaced.
 
842
                if self._real_branch is not None:
 
843
                    self._real_branch.repository = new_repository
 
844
            self.repository.lock_write(token=lock_token)
 
845
            if lock_token is not None:
 
846
                old_repository.leave_lock_in_place()
787
847
            old_repository.unlock()
 
848
            if lock_token is not None:
 
849
                # XXX: self.repository.leave_lock_in_place() before this
 
850
                # function will not be preserved.  Fortunately that doesn't
 
851
                # affect the current default format (2a), and would be a
 
852
                # corner-case anyway.
 
853
                #  - Andrew Bennetts, 2010/06/30
 
854
                self.repository.dont_leave_lock_in_place()
 
855
            old_lock_count = 0
 
856
            while True:
 
857
                try:
 
858
                    old_repository.unlock()
 
859
                except errors.LockNotHeld:
 
860
                    break
 
861
                old_lock_count += 1
 
862
            if old_lock_count == 0:
 
863
                raise AssertionError(
 
864
                    'old_repository should have been locked at least once.')
 
865
            for i in range(old_lock_count-1):
 
866
                self.repository.lock_write()
 
867
            # Fetch from the old repository into the new.
788
868
            old_repository.lock_read()
789
869
            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
870
                # XXX: If you unstack a branch while it has a working tree
809
871
                # with a pending merge, the pending-merged revisions will no
810
872
                # 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)
 
873
                try:
 
874
                    tags_to_fetch = set(self.tags.get_reverse_tag_dict())
 
875
                except errors.TagsNotSupported:
 
876
                    tags_to_fetch = set()
 
877
                fetch_spec = _mod_graph.NotInOtherForRevs(self.repository,
 
878
                    old_repository, required_ids=[self.last_revision()],
 
879
                    if_present_ids=tags_to_fetch, find_ghosts=True).execute()
 
880
                self.repository.fetch(old_repository, fetch_spec=fetch_spec)
818
881
            finally:
819
882
                old_repository.unlock()
820
883
        finally:
825
888
 
826
889
        :seealso: Branch._get_tags_bytes.
827
890
        """
828
 
        return _run_with_write_locked_target(self, self._transport.put_bytes,
829
 
            'tags', bytes)
 
891
        return _run_with_write_locked_target(self, self._set_tags_bytes_locked,
 
892
                bytes)
 
893
 
 
894
    def _set_tags_bytes_locked(self, bytes):
 
895
        self._tags_bytes = bytes
 
896
        return self._transport.put_bytes('tags', bytes)
830
897
 
831
898
    def _cache_revision_history(self, rev_history):
832
899
        """Set the cached revision history to rev_history.
859
926
        self._revision_history_cache = None
860
927
        self._revision_id_to_revno_cache = None
861
928
        self._last_revision_info_cache = None
 
929
        self._master_branch_cache = None
862
930
        self._merge_sorted_revisions_cache = None
863
931
        self._partial_revision_history_cache = []
864
932
        self._partial_revision_id_to_revno_cache = {}
 
933
        self._tags_bytes = None
865
934
 
866
935
    def _gen_revision_history(self):
867
936
        """Return sequence of revision hashes on to this branch.
928
997
        else:
929
998
            return (0, _mod_revision.NULL_REVISION)
930
999
 
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
955
1000
    def update_revisions(self, other, stop_revision=None, overwrite=False,
956
 
                         graph=None):
 
1001
                         graph=None, fetch_tags=True):
957
1002
        """Pull in new perfect-fit revisions.
958
1003
 
959
1004
        :param other: Another Branch to pull from
962
1007
            to see if it is a proper descendant.
963
1008
        :param graph: A Graph object that can be used to query history
964
1009
            information. This can be None.
 
1010
        :param fetch_tags: Flag that specifies if tags from other should be
 
1011
            fetched too.
965
1012
        :return: None
966
1013
        """
967
1014
        return InterBranch.get(other, self).update_revisions(stop_revision,
968
 
            overwrite, graph)
 
1015
            overwrite, graph, fetch_tags=fetch_tags)
969
1016
 
 
1017
    @deprecated_method(deprecated_in((2, 4, 0)))
970
1018
    def import_last_revision_info(self, source_repo, revno, revid):
971
1019
        """Set the last revision info, importing from another repo if necessary.
972
1020
 
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
1021
        :param source_repo: Source repository to optionally fetch from
977
1022
        :param revno: Revision number of the new tip
978
1023
        :param revid: Revision id of the new tip
981
1026
            self.repository.fetch(source_repo, revision_id=revid)
982
1027
        self.set_last_revision_info(revno, revid)
983
1028
 
 
1029
    def import_last_revision_info_and_tags(self, source, revno, revid):
 
1030
        """Set the last revision info, importing from another repo if necessary.
 
1031
 
 
1032
        This is used by the bound branch code to upload a revision to
 
1033
        the master branch first before updating the tip of the local branch.
 
1034
        Revisions referenced by source's tags are also transferred.
 
1035
 
 
1036
        :param source: Source branch to optionally fetch from
 
1037
        :param revno: Revision number of the new tip
 
1038
        :param revid: Revision id of the new tip
 
1039
        """
 
1040
        if not self.repository.has_same_location(source.repository):
 
1041
            try:
 
1042
                tags_to_fetch = set(source.tags.get_reverse_tag_dict())
 
1043
            except errors.TagsNotSupported:
 
1044
                tags_to_fetch = set()
 
1045
            fetch_spec = _mod_graph.NotInOtherForRevs(self.repository,
 
1046
                source.repository, [revid],
 
1047
                if_present_ids=tags_to_fetch).execute()
 
1048
            self.repository.fetch(source.repository, fetch_spec=fetch_spec)
 
1049
        self.set_last_revision_info(revno, revid)
 
1050
 
984
1051
    def revision_id_to_revno(self, revision_id):
985
1052
        """Given a revision id, return its revno"""
986
1053
        if _mod_revision.is_null(revision_id):
1006
1073
            self._extend_partial_history(distance_from_last)
1007
1074
        return self._partial_revision_history_cache[distance_from_last]
1008
1075
 
1009
 
    @needs_write_lock
1010
1076
    def pull(self, source, overwrite=False, stop_revision=None,
1011
1077
             possible_transports=None, *args, **kwargs):
1012
1078
        """Mirror source into this branch.
1208
1274
        return result
1209
1275
 
1210
1276
    @needs_read_lock
1211
 
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None):
 
1277
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None,
 
1278
            repository=None):
1212
1279
        """Create a new line of development from the branch, into to_bzrdir.
1213
1280
 
1214
1281
        to_bzrdir controls the branch format.
1219
1286
        if (repository_policy is not None and
1220
1287
            repository_policy.requires_stacking()):
1221
1288
            to_bzrdir._format.require_stacking(_skip_repo=True)
1222
 
        result = to_bzrdir.create_branch()
 
1289
        result = to_bzrdir.create_branch(repository=repository)
1223
1290
        result.lock_write()
1224
1291
        try:
1225
1292
            if repository_policy is not None:
1255
1322
                revno = 1
1256
1323
        destination.set_last_revision_info(revno, revision_id)
1257
1324
 
1258
 
    @needs_read_lock
1259
1325
    def copy_content_into(self, destination, revision_id=None):
1260
1326
        """Copy the content of self into destination.
1261
1327
 
1262
1328
        revision_id: if not None, the revision history in the new branch will
1263
1329
                     be truncated to end with revision_id.
1264
1330
        """
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)
 
1331
        return InterBranch.get(self, destination).copy_content_into(
 
1332
            revision_id=revision_id)
1276
1333
 
1277
1334
    def update_references(self, target):
1278
1335
        if not getattr(self._format, 'supports_reference_locations', False):
1323
1380
        """Return the most suitable metadir for a checkout of this branch.
1324
1381
        Weaves are used if this branch's repository uses weaves.
1325
1382
        """
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)
 
1383
        format = self.repository.bzrdir.checkout_metadir()
 
1384
        format.set_branch_format(self._format)
1333
1385
        return format
1334
1386
 
1335
1387
    def create_clone_on_transport(self, to_transport, revision_id=None,
1336
 
        stacked_on=None, create_prefix=False, use_existing_dir=False):
 
1388
        stacked_on=None, create_prefix=False, use_existing_dir=False,
 
1389
        no_tree=None):
1337
1390
        """Create a clone of this branch and its bzrdir.
1338
1391
 
1339
1392
        :param to_transport: The transport to clone onto.
1346
1399
        """
1347
1400
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1348
1401
        # clone call. Or something. 20090224 RBC/spiv.
 
1402
        # XXX: Should this perhaps clone colocated branches as well, 
 
1403
        # rather than just the default branch? 20100319 JRV
1349
1404
        if revision_id is None:
1350
1405
            revision_id = self.last_revision()
1351
1406
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1352
1407
            revision_id=revision_id, stacked_on=stacked_on,
1353
 
            create_prefix=create_prefix, use_existing_dir=use_existing_dir)
 
1408
            create_prefix=create_prefix, use_existing_dir=use_existing_dir,
 
1409
            no_tree=no_tree)
1354
1410
        return dir_to.open_branch()
1355
1411
 
1356
1412
    def create_checkout(self, to_location, revision_id=None,
1471
1527
        else:
1472
1528
            raise AssertionError("invalid heads: %r" % (heads,))
1473
1529
 
1474
 
 
1475
 
class BranchFormat(object):
 
1530
    def heads_to_fetch(self):
 
1531
        """Return the heads that must and that should be fetched to copy this
 
1532
        branch into another repo.
 
1533
 
 
1534
        :returns: a 2-tuple of (must_fetch, if_present_fetch).  must_fetch is a
 
1535
            set of heads that must be fetched.  if_present_fetch is a set of
 
1536
            heads that must be fetched if present, but no error is necessary if
 
1537
            they are not present.
 
1538
        """
 
1539
        # For bzr native formats must_fetch is just the tip, and if_present_fetch
 
1540
        # are the tags.
 
1541
        must_fetch = set([self.last_revision()])
 
1542
        try:
 
1543
            if_present_fetch = set(self.tags.get_reverse_tag_dict())
 
1544
        except errors.TagsNotSupported:
 
1545
            if_present_fetch = set()
 
1546
        must_fetch.discard(_mod_revision.NULL_REVISION)
 
1547
        if_present_fetch.discard(_mod_revision.NULL_REVISION)
 
1548
        return must_fetch, if_present_fetch
 
1549
 
 
1550
 
 
1551
class BranchFormat(controldir.ControlComponentFormat):
1476
1552
    """An encapsulation of the initialization and open routines for a format.
1477
1553
 
1478
1554
    Formats provide three things:
1481
1557
     * an open routine.
1482
1558
 
1483
1559
    Formats are placed in an dict by their format string for reference
1484
 
    during branch opening. Its not required that these be instances, they
 
1560
    during branch opening. It's not required that these be instances, they
1485
1561
    can be classes themselves with class methods - it simply depends on
1486
1562
    whether state is needed for a given format or not.
1487
1563
 
1490
1566
    object will be created every time regardless.
1491
1567
    """
1492
1568
 
1493
 
    _default_format = None
1494
 
    """The default format used for new branches."""
1495
 
 
1496
 
    _formats = {}
1497
 
    """The known formats."""
1498
 
 
1499
1569
    can_set_append_revisions_only = True
1500
1570
 
1501
1571
    def __eq__(self, other):
1510
1580
        try:
1511
1581
            transport = a_bzrdir.get_branch_transport(None, name=name)
1512
1582
            format_string = transport.get_bytes("format")
1513
 
            return klass._formats[format_string]
 
1583
            return format_registry.get(format_string)
1514
1584
        except errors.NoSuchFile:
1515
1585
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1516
1586
        except KeyError:
1517
1587
            raise errors.UnknownFormatError(format=format_string, kind='branch')
1518
1588
 
1519
1589
    @classmethod
 
1590
    @deprecated_method(deprecated_in((2, 4, 0)))
1520
1591
    def get_default_format(klass):
1521
1592
        """Return the current default format."""
1522
 
        return klass._default_format
1523
 
 
1524
 
    def get_reference(self, a_bzrdir):
 
1593
        return format_registry.get_default()
 
1594
 
 
1595
    @classmethod
 
1596
    @deprecated_method(deprecated_in((2, 4, 0)))
 
1597
    def get_formats(klass):
 
1598
        """Get all the known formats.
 
1599
 
 
1600
        Warning: This triggers a load of all lazy registered formats: do not
 
1601
        use except when that is desireed.
 
1602
        """
 
1603
        return format_registry._get_all()
 
1604
 
 
1605
    def get_reference(self, a_bzrdir, name=None):
1525
1606
        """Get the target reference of the branch in a_bzrdir.
1526
1607
 
1527
1608
        format probing must have been completed before calling
1529
1610
        in a_bzrdir is correct.
1530
1611
 
1531
1612
        :param a_bzrdir: The bzrdir to get the branch data from.
 
1613
        :param name: Name of the colocated branch to fetch
1532
1614
        :return: None if the branch is not a reference branch.
1533
1615
        """
1534
1616
        return None
1535
1617
 
1536
1618
    @classmethod
1537
 
    def set_reference(self, a_bzrdir, to_branch):
 
1619
    def set_reference(self, a_bzrdir, name, to_branch):
1538
1620
        """Set the target reference of the branch in a_bzrdir.
1539
1621
 
1540
1622
        format probing must have been completed before calling
1542
1624
        in a_bzrdir is correct.
1543
1625
 
1544
1626
        :param a_bzrdir: The bzrdir to set the branch reference for.
 
1627
        :param name: Name of colocated branch to set, None for default
1545
1628
        :param to_branch: branch that the checkout is to reference
1546
1629
        """
1547
1630
        raise NotImplementedError(self.set_reference)
1562
1645
        for hook in hooks:
1563
1646
            hook(params)
1564
1647
 
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):
 
1648
    def initialize(self, a_bzrdir, name=None, repository=None):
1611
1649
        """Create a branch of this format in a_bzrdir.
1612
1650
        
1613
1651
        :param name: Name of the colocated branch to create.
1647
1685
        """
1648
1686
        raise NotImplementedError(self.network_name)
1649
1687
 
1650
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1688
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
 
1689
            found_repository=None):
1651
1690
        """Return the branch object for a_bzrdir
1652
1691
 
1653
1692
        :param a_bzrdir: A BzrDir that contains a branch.
1660
1699
        raise NotImplementedError(self.open)
1661
1700
 
1662
1701
    @classmethod
 
1702
    @deprecated_method(deprecated_in((2, 4, 0)))
1663
1703
    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__)
 
1704
        """Register a metadir format.
 
1705
 
 
1706
        See MetaDirBranchFormatFactory for the ability to register a format
 
1707
        without loading the code the format needs until it is actually used.
 
1708
        """
 
1709
        format_registry.register(format)
1669
1710
 
1670
1711
    @classmethod
 
1712
    @deprecated_method(deprecated_in((2, 4, 0)))
1671
1713
    def set_default_format(klass, format):
1672
 
        klass._default_format = format
 
1714
        format_registry.set_default(format)
1673
1715
 
1674
1716
    def supports_set_append_revisions_only(self):
1675
1717
        """True if this format supports set_append_revisions_only."""
1679
1721
        """True if this format records a stacked-on branch."""
1680
1722
        return False
1681
1723
 
 
1724
    def supports_leaving_lock(self):
 
1725
        """True if this format supports leaving locks in place."""
 
1726
        return False # by default
 
1727
 
1682
1728
    @classmethod
 
1729
    @deprecated_method(deprecated_in((2, 4, 0)))
1683
1730
    def unregister_format(klass, format):
1684
 
        del klass._formats[format.get_format_string()]
 
1731
        format_registry.remove(format)
1685
1732
 
1686
1733
    def __str__(self):
1687
1734
        return self.get_format_description().rstrip()
1691
1738
        return False  # by default
1692
1739
 
1693
1740
 
 
1741
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
 
1742
    """A factory for a BranchFormat object, permitting simple lazy registration.
 
1743
    
 
1744
    While none of the built in BranchFormats are lazy registered yet,
 
1745
    bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
 
1746
    use it, and the bzr-loom plugin uses it as well (see
 
1747
    bzrlib.plugins.loom.formats).
 
1748
    """
 
1749
 
 
1750
    def __init__(self, format_string, module_name, member_name):
 
1751
        """Create a MetaDirBranchFormatFactory.
 
1752
 
 
1753
        :param format_string: The format string the format has.
 
1754
        :param module_name: Module to load the format class from.
 
1755
        :param member_name: Attribute name within the module for the format class.
 
1756
        """
 
1757
        registry._LazyObjectGetter.__init__(self, module_name, member_name)
 
1758
        self._format_string = format_string
 
1759
        
 
1760
    def get_format_string(self):
 
1761
        """See BranchFormat.get_format_string."""
 
1762
        return self._format_string
 
1763
 
 
1764
    def __call__(self):
 
1765
        """Used for network_format_registry support."""
 
1766
        return self.get_obj()()
 
1767
 
 
1768
 
1694
1769
class BranchHooks(Hooks):
1695
1770
    """A dictionary mapping hook name to a list of callables for branch hooks.
1696
1771
 
1704
1779
        These are all empty initially, because by default nothing should get
1705
1780
        notified.
1706
1781
        """
1707
 
        Hooks.__init__(self)
1708
 
        self.create_hook(HookPoint('set_rh',
 
1782
        Hooks.__init__(self, "bzrlib.branch", "Branch.hooks")
 
1783
        self.add_hook('set_rh',
1709
1784
            "Invoked whenever the revision history has been set via "
1710
1785
            "set_revision_history. The api signature is (branch, "
1711
1786
            "revision_history), and the branch will be write-locked. "
1712
1787
            "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',
 
1788
            "hook to use is Branch.post_change_branch_tip.", (0, 15))
 
1789
        self.add_hook('open',
1715
1790
            "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',
 
1791
            "branch is opened.", (1, 8))
 
1792
        self.add_hook('post_push',
1718
1793
            "Called after a push operation completes. post_push is called "
1719
1794
            "with a bzrlib.branch.BranchPushResult object and only runs in the "
1720
 
            "bzr client.", (0, 15), None))
1721
 
        self.create_hook(HookPoint('post_pull',
 
1795
            "bzr client.", (0, 15))
 
1796
        self.add_hook('post_pull',
1722
1797
            "Called after a pull operation completes. post_pull is called "
1723
1798
            "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 "
 
1799
            "bzr client.", (0, 15))
 
1800
        self.add_hook('pre_commit',
 
1801
            "Called after a commit is calculated but before it is "
1727
1802
            "completed. pre_commit is called with (local, master, old_revno, "
1728
1803
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
1729
1804
            "). old_revid is NULL_REVISION for the first commit to a branch, "
1731
1806
            "basis revision. hooks MUST NOT modify this delta. "
1732
1807
            " future_tree is an in-memory tree obtained from "
1733
1808
            "CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1734
 
            "tree.", (0,91), None))
1735
 
        self.create_hook(HookPoint('post_commit',
 
1809
            "tree.", (0,91))
 
1810
        self.add_hook('post_commit',
1736
1811
            "Called in the bzr client after a commit has completed. "
1737
1812
            "post_commit is called with (local, master, old_revno, old_revid, "
1738
1813
            "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',
 
1814
            "commit to a branch.", (0, 15))
 
1815
        self.add_hook('post_uncommit',
1741
1816
            "Called in the bzr client after an uncommit completes. "
1742
1817
            "post_uncommit is called with (local, master, old_revno, "
1743
1818
            "old_revid, new_revno, new_revid) where local is the local branch "
1744
1819
            "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',
 
1820
            "receives new_revno of 0, new_revid of None.", (0, 15))
 
1821
        self.add_hook('pre_change_branch_tip',
1747
1822
            "Called in bzr client and server before a change to the tip of a "
1748
1823
            "branch is made. pre_change_branch_tip is called with a "
1749
1824
            "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',
 
1825
            "commit, uncommit will all trigger this hook.", (1, 6))
 
1826
        self.add_hook('post_change_branch_tip',
1752
1827
            "Called in bzr client and server after a change to the tip of a "
1753
1828
            "branch is made. post_change_branch_tip is called with a "
1754
1829
            "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',
 
1830
            "commit, uncommit will all trigger this hook.", (1, 4))
 
1831
        self.add_hook('transform_fallback_location',
1757
1832
            "Called when a stacked branch is activating its fallback "
1758
1833
            "locations. transform_fallback_location is called with (branch, "
1759
1834
            "url), and should return a new url. Returning the same url "
1764
1839
            "fallback locations have not been activated. When there are "
1765
1840
            "multiple hooks installed for transform_fallback_location, "
1766
1841
            "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."
 
1842
            "The order is however undefined.", (1, 9))
 
1843
        self.add_hook('automatic_tag_name',
 
1844
            "Called to determine an automatic tag name for a revision. "
1770
1845
            "automatic_tag_name is called with (branch, revision_id) and "
1771
1846
            "should return a tag name or None if no tag name could be "
1772
1847
            "determined. The first non-None tag name returned will be used.",
1773
 
            (2, 2), None))
1774
 
        self.create_hook(HookPoint('post_branch_init',
 
1848
            (2, 2))
 
1849
        self.add_hook('post_branch_init',
1775
1850
            "Called after new branch initialization completes. "
1776
1851
            "post_branch_init is called with a "
1777
1852
            "bzrlib.branch.BranchInitHookParams. "
1778
1853
            "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',
 
1854
            "lightweight) will all trigger this hook.", (2, 2))
 
1855
        self.add_hook('post_switch',
1781
1856
            "Called after a checkout switches branch. "
1782
1857
            "post_switch is called with a "
1783
 
            "bzrlib.branch.SwitchHookParams.", (2, 2), None))
 
1858
            "bzrlib.branch.SwitchHookParams.", (2, 2))
1784
1859
 
1785
1860
 
1786
1861
 
1863
1938
        return self.__dict__ == other.__dict__
1864
1939
 
1865
1940
    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)
 
1941
        return "<%s of %s>" % (self.__class__.__name__, self.branch)
1872
1942
 
1873
1943
 
1874
1944
class SwitchHookParams(object):
1904
1974
            self.revision_id)
1905
1975
 
1906
1976
 
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
1977
class BranchFormatMetadir(BranchFormat):
1951
1978
    """Common logic for meta-dir based branch formats."""
1952
1979
 
1954
1981
        """What class to instantiate on open calls."""
1955
1982
        raise NotImplementedError(self._branch_class)
1956
1983
 
 
1984
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
 
1985
                           repository=None):
 
1986
        """Initialize a branch in a bzrdir, with specified files
 
1987
 
 
1988
        :param a_bzrdir: The bzrdir to initialize the branch in
 
1989
        :param utf8_files: The files to create as a list of
 
1990
            (filename, content) tuples
 
1991
        :param name: Name of colocated branch to create, if any
 
1992
        :return: a branch in this format
 
1993
        """
 
1994
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
 
1995
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
1996
        control_files = lockable_files.LockableFiles(branch_transport,
 
1997
            'lock', lockdir.LockDir)
 
1998
        control_files.create_lock()
 
1999
        control_files.lock_write()
 
2000
        try:
 
2001
            utf8_files += [('format', self.get_format_string())]
 
2002
            for (filename, content) in utf8_files:
 
2003
                branch_transport.put_bytes(
 
2004
                    filename, content,
 
2005
                    mode=a_bzrdir._get_file_mode())
 
2006
        finally:
 
2007
            control_files.unlock()
 
2008
        branch = self.open(a_bzrdir, name, _found=True,
 
2009
                found_repository=repository)
 
2010
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
 
2011
        return branch
 
2012
 
1957
2013
    def network_name(self):
1958
2014
        """A simple byte string uniquely identifying this format for RPC calls.
1959
2015
 
1961
2017
        """
1962
2018
        return self.get_format_string()
1963
2019
 
1964
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
2020
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
 
2021
            found_repository=None):
1965
2022
        """See BranchFormat.open()."""
1966
2023
        if not _found:
1967
2024
            format = BranchFormat.find_format(a_bzrdir, name=name)
1972
2029
        try:
1973
2030
            control_files = lockable_files.LockableFiles(transport, 'lock',
1974
2031
                                                         lockdir.LockDir)
 
2032
            if found_repository is None:
 
2033
                found_repository = a_bzrdir.find_repository()
1975
2034
            return self._branch_class()(_format=self,
1976
2035
                              _control_files=control_files,
1977
2036
                              name=name,
1978
2037
                              a_bzrdir=a_bzrdir,
1979
 
                              _repository=a_bzrdir.find_repository(),
 
2038
                              _repository=found_repository,
1980
2039
                              ignore_fallbacks=ignore_fallbacks)
1981
2040
        except errors.NoSuchFile:
1982
2041
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1989
2048
    def supports_tags(self):
1990
2049
        return True
1991
2050
 
 
2051
    def supports_leaving_lock(self):
 
2052
        return True
 
2053
 
1992
2054
 
1993
2055
class BzrBranchFormat5(BranchFormatMetadir):
1994
2056
    """Bzr branch format 5.
2014
2076
        """See BranchFormat.get_format_description()."""
2015
2077
        return "Branch format 5"
2016
2078
 
2017
 
    def initialize(self, a_bzrdir, name=None):
 
2079
    def initialize(self, a_bzrdir, name=None, repository=None):
2018
2080
        """Create a branch of this format in a_bzrdir."""
2019
2081
        utf8_files = [('revision-history', ''),
2020
2082
                      ('branch-name', ''),
2021
2083
                      ]
2022
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2084
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2023
2085
 
2024
2086
    def supports_tags(self):
2025
2087
        return False
2047
2109
        """See BranchFormat.get_format_description()."""
2048
2110
        return "Branch format 6"
2049
2111
 
2050
 
    def initialize(self, a_bzrdir, name=None):
 
2112
    def initialize(self, a_bzrdir, name=None, repository=None):
2051
2113
        """Create a branch of this format in a_bzrdir."""
2052
2114
        utf8_files = [('last-revision', '0 null:\n'),
2053
2115
                      ('branch.conf', ''),
2054
2116
                      ('tags', ''),
2055
2117
                      ]
2056
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2118
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2057
2119
 
2058
2120
    def make_tags(self, branch):
2059
2121
        """See bzrlib.branch.BranchFormat.make_tags()."""
2077
2139
        """See BranchFormat.get_format_description()."""
2078
2140
        return "Branch format 8"
2079
2141
 
2080
 
    def initialize(self, a_bzrdir, name=None):
 
2142
    def initialize(self, a_bzrdir, name=None, repository=None):
2081
2143
        """Create a branch of this format in a_bzrdir."""
2082
2144
        utf8_files = [('last-revision', '0 null:\n'),
2083
2145
                      ('branch.conf', ''),
2084
2146
                      ('tags', ''),
2085
2147
                      ('references', '')
2086
2148
                      ]
2087
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2149
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2088
2150
 
2089
2151
    def __init__(self):
2090
2152
        super(BzrBranchFormat8, self).__init__()
2104
2166
    supports_reference_locations = True
2105
2167
 
2106
2168
 
2107
 
class BzrBranchFormat7(BzrBranchFormat8):
 
2169
class BzrBranchFormat7(BranchFormatMetadir):
2108
2170
    """Branch format with last-revision, tags, and a stacked location pointer.
2109
2171
 
2110
2172
    The stacked location pointer is passed down to the repository and requires
2113
2175
    This format was introduced in bzr 1.6.
2114
2176
    """
2115
2177
 
2116
 
    def initialize(self, a_bzrdir, name=None):
 
2178
    def initialize(self, a_bzrdir, name=None, repository=None):
2117
2179
        """Create a branch of this format in a_bzrdir."""
2118
2180
        utf8_files = [('last-revision', '0 null:\n'),
2119
2181
                      ('branch.conf', ''),
2120
2182
                      ('tags', ''),
2121
2183
                      ]
2122
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2184
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2123
2185
 
2124
2186
    def _branch_class(self):
2125
2187
        return BzrBranch7
2135
2197
    def supports_set_append_revisions_only(self):
2136
2198
        return True
2137
2199
 
 
2200
    def supports_stacking(self):
 
2201
        return True
 
2202
 
2138
2203
    supports_reference_locations = False
2139
2204
 
2140
2205
 
2157
2222
        """See BranchFormat.get_format_description()."""
2158
2223
        return "Checkout reference format 1"
2159
2224
 
2160
 
    def get_reference(self, a_bzrdir):
 
2225
    def get_reference(self, a_bzrdir, name=None):
2161
2226
        """See BranchFormat.get_reference()."""
2162
 
        transport = a_bzrdir.get_branch_transport(None)
 
2227
        transport = a_bzrdir.get_branch_transport(None, name=name)
2163
2228
        return transport.get_bytes('location')
2164
2229
 
2165
 
    def set_reference(self, a_bzrdir, to_branch):
 
2230
    def set_reference(self, a_bzrdir, name, to_branch):
2166
2231
        """See BranchFormat.set_reference()."""
2167
 
        transport = a_bzrdir.get_branch_transport(None)
 
2232
        transport = a_bzrdir.get_branch_transport(None, name=name)
2168
2233
        location = transport.put_bytes('location', to_branch.base)
2169
2234
 
2170
 
    def initialize(self, a_bzrdir, name=None, target_branch=None):
 
2235
    def initialize(self, a_bzrdir, name=None, target_branch=None,
 
2236
            repository=None):
2171
2237
        """Create a branch of this format in a_bzrdir."""
2172
2238
        if target_branch is None:
2173
2239
            # this format does not implement branch itself, thus the implicit
2201
2267
        return clone
2202
2268
 
2203
2269
    def open(self, a_bzrdir, name=None, _found=False, location=None,
2204
 
             possible_transports=None, ignore_fallbacks=False):
 
2270
             possible_transports=None, ignore_fallbacks=False,
 
2271
             found_repository=None):
2205
2272
        """Return the branch that the branch reference in a_bzrdir points at.
2206
2273
 
2207
2274
        :param a_bzrdir: A BzrDir that contains a branch.
2221
2288
                raise AssertionError("wrong format %r found for %r" %
2222
2289
                    (format, self))
2223
2290
        if location is None:
2224
 
            location = self.get_reference(a_bzrdir)
 
2291
            location = self.get_reference(a_bzrdir, name)
2225
2292
        real_bzrdir = bzrdir.BzrDir.open(
2226
2293
            location, possible_transports=possible_transports)
2227
2294
        result = real_bzrdir.open_branch(name=name, 
2238
2305
        return result
2239
2306
 
2240
2307
 
 
2308
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
 
2309
    """Branch format registry."""
 
2310
 
 
2311
    def __init__(self, other_registry=None):
 
2312
        super(BranchFormatRegistry, self).__init__(other_registry)
 
2313
        self._default_format = None
 
2314
 
 
2315
    def set_default(self, format):
 
2316
        self._default_format = format
 
2317
 
 
2318
    def get_default(self):
 
2319
        return self._default_format
 
2320
 
 
2321
 
2241
2322
network_format_registry = registry.FormatRegistry()
2242
2323
"""Registry of formats indexed by their network name.
2243
2324
 
2246
2327
BranchFormat.network_name() for more detail.
2247
2328
"""
2248
2329
 
 
2330
format_registry = BranchFormatRegistry(network_format_registry)
 
2331
 
2249
2332
 
2250
2333
# formats which have no format string are not discoverable
2251
2334
# and not independently creatable, so are not registered.
2253
2336
__format6 = BzrBranchFormat6()
2254
2337
__format7 = BzrBranchFormat7()
2255
2338
__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__)
 
2339
format_registry.register(__format5)
 
2340
format_registry.register(BranchReferenceFormat())
 
2341
format_registry.register(__format6)
 
2342
format_registry.register(__format7)
 
2343
format_registry.register(__format8)
 
2344
format_registry.set_default(__format7)
 
2345
 
 
2346
 
 
2347
class BranchWriteLockResult(LogicalLockResult):
 
2348
    """The result of write locking a branch.
 
2349
 
 
2350
    :ivar branch_token: The token obtained from the underlying branch lock, or
 
2351
        None.
 
2352
    :ivar unlock: A callable which will unlock the lock.
 
2353
    """
 
2354
 
 
2355
    def __init__(self, unlock, branch_token):
 
2356
        LogicalLockResult.__init__(self, unlock)
 
2357
        self.branch_token = branch_token
 
2358
 
 
2359
    def __repr__(self):
 
2360
        return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
 
2361
            self.unlock)
2266
2362
 
2267
2363
 
2268
2364
class BzrBranch(Branch, _RelockDebugMixin):
2324
2420
        return self.control_files.is_locked()
2325
2421
 
2326
2422
    def lock_write(self, token=None):
 
2423
        """Lock the branch for write operations.
 
2424
 
 
2425
        :param token: A token to permit reacquiring a previously held and
 
2426
            preserved lock.
 
2427
        :return: A BranchWriteLockResult.
 
2428
        """
2327
2429
        if not self.is_locked():
2328
2430
            self._note_lock('w')
2329
2431
        # All-in-one needs to always unlock/lock.
2335
2437
        else:
2336
2438
            took_lock = False
2337
2439
        try:
2338
 
            return self.control_files.lock_write(token=token)
 
2440
            return BranchWriteLockResult(self.unlock,
 
2441
                self.control_files.lock_write(token=token))
2339
2442
        except:
2340
2443
            if took_lock:
2341
2444
                self.repository.unlock()
2342
2445
            raise
2343
2446
 
2344
2447
    def lock_read(self):
 
2448
        """Lock the branch for read operations.
 
2449
 
 
2450
        :return: A bzrlib.lock.LogicalLockResult.
 
2451
        """
2345
2452
        if not self.is_locked():
2346
2453
            self._note_lock('r')
2347
2454
        # All-in-one needs to always unlock/lock.
2354
2461
            took_lock = False
2355
2462
        try:
2356
2463
            self.control_files.lock_read()
 
2464
            return LogicalLockResult(self.unlock)
2357
2465
        except:
2358
2466
            if took_lock:
2359
2467
                self.repository.unlock()
2515
2623
        result.target_branch = target
2516
2624
        result.old_revno, result.old_revid = target.last_revision_info()
2517
2625
        self.update_references(target)
2518
 
        if result.old_revid != self.last_revision():
 
2626
        if result.old_revid != stop_revision:
2519
2627
            # We assume that during 'push' this repository is closer than
2520
2628
            # the target.
2521
2629
            graph = self.repository.get_graph(target.repository)
2522
2630
            target.update_revisions(self, stop_revision,
2523
2631
                overwrite=overwrite, graph=graph)
2524
2632
        if self._push_should_merge_tags():
2525
 
            result.tag_conflicts = self.tags.merge_to(target.tags,
2526
 
                overwrite)
 
2633
            result.tag_conflicts = self.tags.merge_to(target.tags, overwrite)
2527
2634
        result.new_revno, result.new_revid = target.last_revision_info()
2528
2635
        return result
2529
2636
 
2561
2668
        """Return the branch we are bound to.
2562
2669
 
2563
2670
        :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
2671
        """
 
2672
        if self._master_branch_cache is None:
 
2673
            self._master_branch_cache = self._get_master_branch(
 
2674
                possible_transports)
 
2675
        return self._master_branch_cache
 
2676
 
 
2677
    def _get_master_branch(self, possible_transports):
2570
2678
        bound_loc = self.get_bound_location()
2571
2679
        if not bound_loc:
2572
2680
            return None
2583
2691
 
2584
2692
        :param location: URL to the target branch
2585
2693
        """
 
2694
        self._master_branch_cache = None
2586
2695
        if location:
2587
2696
            self._transport.put_bytes('bound', location+'\n',
2588
2697
                mode=self.bzrdir._get_file_mode())
2840
2949
 
2841
2950
    def set_bound_location(self, location):
2842
2951
        """See Branch.set_push_location."""
 
2952
        self._master_branch_cache = None
2843
2953
        result = None
2844
2954
        config = self.get_config()
2845
2955
        if location is None:
2922
3032
        try:
2923
3033
            index = self._partial_revision_history_cache.index(revision_id)
2924
3034
        except ValueError:
2925
 
            self._extend_partial_history(stop_revision=revision_id)
 
3035
            try:
 
3036
                self._extend_partial_history(stop_revision=revision_id)
 
3037
            except errors.RevisionNotPresent, e:
 
3038
                raise errors.GhostRevisionsHaveNoRevno(revision_id, e.revision_id)
2926
3039
            index = len(self._partial_revision_history_cache) - 1
2927
3040
            if self._partial_revision_history_cache[index] != revision_id:
2928
3041
                raise errors.NoSuchRevision(self, revision_id)
2983
3096
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
2984
3097
    """
2985
3098
 
 
3099
    @deprecated_method(deprecated_in((2, 3, 0)))
2986
3100
    def __int__(self):
2987
 
        # DEPRECATED: pull used to return the change in revno
 
3101
        """Return the relative change in revno.
 
3102
 
 
3103
        :deprecated: Use `new_revno` and `old_revno` instead.
 
3104
        """
2988
3105
        return self.new_revno - self.old_revno
2989
3106
 
2990
3107
    def report(self, to_file):
3015
3132
        target, otherwise it will be None.
3016
3133
    """
3017
3134
 
 
3135
    @deprecated_method(deprecated_in((2, 3, 0)))
3018
3136
    def __int__(self):
3019
 
        # DEPRECATED: push used to return the change in revno
 
3137
        """Return the relative change in revno.
 
3138
 
 
3139
        :deprecated: Use `new_revno` and `old_revno` instead.
 
3140
        """
3020
3141
        return self.new_revno - self.old_revno
3021
3142
 
3022
3143
    def report(self, to_file):
3145
3266
    _optimisers = []
3146
3267
    """The available optimised InterBranch types."""
3147
3268
 
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)
 
3269
    @classmethod
 
3270
    def _get_branch_formats_to_test(klass):
 
3271
        """Return an iterable of format tuples for testing.
 
3272
        
 
3273
        :return: An iterable of (from_format, to_format) to use when testing
 
3274
            this InterBranch class. Each InterBranch class should define this
 
3275
            method itself.
 
3276
        """
 
3277
        raise NotImplementedError(klass._get_branch_formats_to_test)
3152
3278
 
 
3279
    @needs_write_lock
3153
3280
    def pull(self, overwrite=False, stop_revision=None,
3154
3281
             possible_transports=None, local=False):
3155
3282
        """Mirror source into target branch.
3160
3287
        """
3161
3288
        raise NotImplementedError(self.pull)
3162
3289
 
 
3290
    @needs_write_lock
3163
3291
    def update_revisions(self, stop_revision=None, overwrite=False,
3164
 
                         graph=None):
 
3292
                         graph=None, fetch_tags=True):
3165
3293
        """Pull in new perfect-fit revisions.
3166
3294
 
3167
3295
        :param stop_revision: Updated until the given revision
3169
3297
            to see if it is a proper descendant.
3170
3298
        :param graph: A Graph object that can be used to query history
3171
3299
            information. This can be None.
 
3300
        :param fetch_tags: Flag that specifies if tags from source should be
 
3301
            fetched too.
3172
3302
        :return: None
3173
3303
        """
3174
3304
        raise NotImplementedError(self.update_revisions)
3175
3305
 
 
3306
    @needs_write_lock
3176
3307
    def push(self, overwrite=False, stop_revision=None,
3177
3308
             _override_hook_source_branch=None):
3178
3309
        """Mirror the source branch into the target branch.
3181
3312
        """
3182
3313
        raise NotImplementedError(self.push)
3183
3314
 
 
3315
    @needs_write_lock
 
3316
    def copy_content_into(self, revision_id=None):
 
3317
        """Copy the content of source into target
 
3318
 
 
3319
        revision_id: if not None, the revision history in the new branch will
 
3320
                     be truncated to end with revision_id.
 
3321
        """
 
3322
        raise NotImplementedError(self.copy_content_into)
 
3323
 
 
3324
    @needs_write_lock
 
3325
    def fetch(self, stop_revision=None, fetch_spec=None):
 
3326
        """Fetch revisions.
 
3327
 
 
3328
        :param stop_revision: Last revision to fetch
 
3329
        :param fetch_spec: Fetch spec.
 
3330
        """
 
3331
        raise NotImplementedError(self.fetch)
 
3332
 
3184
3333
 
3185
3334
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
 
 
 
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, fetch_spec=None):
 
3374
        if fetch_spec is not None and stop_revision is not None:
 
3375
            raise AssertionError(
 
3376
                "fetch_spec and last_revision are mutually exclusive.")
 
3377
        if self.target.base == self.source.base:
 
3378
            return (0, [])
 
3379
        self.source.lock_read()
 
3380
        try:
 
3381
            if stop_revision is None and fetch_spec is None:
 
3382
                stop_revision = self.source.last_revision()
 
3383
                stop_revision = _mod_revision.ensure_null(stop_revision)
 
3384
            return self.target.repository.fetch(self.source.repository,
 
3385
                revision_id=stop_revision, fetch_spec=fetch_spec)
 
3386
        finally:
 
3387
            self.source.unlock()
 
3388
 
 
3389
    @needs_write_lock
3193
3390
    def update_revisions(self, stop_revision=None, overwrite=False,
3194
 
        graph=None):
 
3391
        graph=None, fetch_tags=True):
3195
3392
        """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
 
 
 
3393
        other_revno, other_last_revision = self.source.last_revision_info()
 
3394
        stop_revno = None # unknown
 
3395
        if stop_revision is None:
 
3396
            stop_revision = other_last_revision
 
3397
            if _mod_revision.is_null(stop_revision):
 
3398
                # if there are no commits, we're done.
 
3399
                return
 
3400
            stop_revno = other_revno
 
3401
 
 
3402
        # what's the current last revision, before we fetch [and change it
 
3403
        # possibly]
 
3404
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
3405
        # we fetch here so that we don't process data twice in the common
 
3406
        # case of having something to pull, and so that the check for
 
3407
        # already merged can operate on the just fetched graph, which will
 
3408
        # be cached in memory.
 
3409
        if fetch_tags:
 
3410
            fetch_spec_factory = fetch.FetchSpecFactory()
 
3411
            fetch_spec_factory.source_branch = self.source
 
3412
            fetch_spec_factory.source_branch_stop_revision_id = stop_revision
 
3413
            fetch_spec_factory.source_repo = self.source.repository
 
3414
            fetch_spec_factory.target_repo = self.target.repository
 
3415
            fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
 
3416
            fetch_spec = fetch_spec_factory.make_fetch_spec()
 
3417
        else:
 
3418
            fetch_spec = _mod_graph.NotInOtherForRevs(self.target.repository,
 
3419
                self.source.repository, revision_ids=[stop_revision]).execute()
 
3420
        self.target.fetch(self.source, fetch_spec=fetch_spec)
 
3421
        # Check to see if one is an ancestor of the other
 
3422
        if not overwrite:
 
3423
            if graph is None:
 
3424
                graph = self.target.repository.get_graph()
 
3425
            if self.target._check_if_descendant_or_diverged(
 
3426
                    stop_revision, last_rev, graph, self.source):
 
3427
                # stop_revision is a descendant of last_rev, but we aren't
 
3428
                # overwriting, so we're done.
 
3429
                return
 
3430
        if stop_revno is None:
 
3431
            if graph is None:
 
3432
                graph = self.target.repository.get_graph()
 
3433
            this_revno, this_last_revision = \
 
3434
                    self.target.last_revision_info()
 
3435
            stop_revno = graph.find_distance_to_null(stop_revision,
 
3436
                            [(other_last_revision, other_revno),
 
3437
                             (this_last_revision, this_revno)])
 
3438
        self.target.set_last_revision_info(stop_revno, stop_revision)
 
3439
 
 
3440
    @needs_write_lock
3236
3441
    def pull(self, overwrite=False, stop_revision=None,
3237
 
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3442
             possible_transports=None, run_hooks=True,
3238
3443
             _override_hook_target=None, local=False):
3239
 
        """See Branch.pull.
 
3444
        """Pull from source into self, updating my master if any.
3240
3445
 
3241
 
        :param _hook_master: Private parameter - set the branch to
3242
 
            be supplied as the master to pull hooks.
3243
3446
        :param run_hooks: Private parameter - if false, this branch
3244
3447
            is being called because it's the master of the primary branch,
3245
3448
            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
3449
        """
3250
 
        # This type of branch can't be bound.
3251
 
        if local:
 
3450
        bound_location = self.target.get_bound_location()
 
3451
        if local and not bound_location:
3252
3452
            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()
 
3453
        master_branch = None
 
3454
        source_is_master = (self.source.user_url == bound_location)
 
3455
        if not local and bound_location and not source_is_master:
 
3456
            # not pulling from master, so we need to update master.
 
3457
            master_branch = self.target.get_master_branch(possible_transports)
 
3458
            master_branch.lock_write()
3260
3459
        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)
 
3460
            if master_branch:
 
3461
                # pull from source into master.
 
3462
                master_branch.pull(self.source, overwrite, stop_revision,
 
3463
                    run_hooks=False)
 
3464
            return self._pull(overwrite,
 
3465
                stop_revision, _hook_master=master_branch,
 
3466
                run_hooks=run_hooks,
 
3467
                _override_hook_target=_override_hook_target,
 
3468
                merge_tags_to_master=not source_is_master)
3287
3469
        finally:
3288
 
            self.source.unlock()
3289
 
        return result
 
3470
            if master_branch:
 
3471
                master_branch.unlock()
3290
3472
 
3291
3473
    def push(self, overwrite=False, stop_revision=None,
3292
3474
             _override_hook_source_branch=None):
3332
3514
                # push into the master from the source branch.
3333
3515
                self.source._basic_push(master_branch, overwrite, stop_revision)
3334
3516
                # and push into the target branch from the source. Note that we
3335
 
                # push from the source branch again, because its considered the
 
3517
                # push from the source branch again, because it's considered the
3336
3518
                # highest bandwidth repository.
3337
3519
                result = self.source._basic_push(self.target, overwrite,
3338
3520
                    stop_revision)
3354
3536
            _run_hooks()
3355
3537
            return result
3356
3538
 
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
 
 
 
3539
    def _pull(self, overwrite=False, stop_revision=None,
 
3540
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3541
             _override_hook_target=None, local=False,
 
3542
             merge_tags_to_master=True):
 
3543
        """See Branch.pull.
 
3544
 
 
3545
        This function is the core worker, used by GenericInterBranch.pull to
 
3546
        avoid duplication when pulling source->master and source->local.
 
3547
 
 
3548
        :param _hook_master: Private parameter - set the branch to
 
3549
            be supplied as the master to pull hooks.
3374
3550
        :param run_hooks: Private parameter - if false, this branch
3375
3551
            is being called because it's the master of the primary branch,
3376
3552
            so it should not run its hooks.
 
3553
            is being called because it's the master of the primary branch,
 
3554
            so it should not run its hooks.
 
3555
        :param _override_hook_target: Private parameter - set the branch to be
 
3556
            supplied as the target_branch to pull hooks.
 
3557
        :param local: Only update the local branch, and not the bound branch.
3377
3558
        """
3378
 
        bound_location = self.target.get_bound_location()
3379
 
        if local and not bound_location:
 
3559
        # This type of branch can't be bound.
 
3560
        if local:
3380
3561
            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()
 
3562
        result = PullResult()
 
3563
        result.source_branch = self.source
 
3564
        if _override_hook_target is None:
 
3565
            result.target_branch = self.target
 
3566
        else:
 
3567
            result.target_branch = _override_hook_target
 
3568
        self.source.lock_read()
3386
3569
        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)
 
3570
            # We assume that during 'pull' the target repository is closer than
 
3571
            # the source one.
 
3572
            self.source.update_references(self.target)
 
3573
            graph = self.target.repository.get_graph(self.source.repository)
 
3574
            # TODO: Branch formats should have a flag that indicates 
 
3575
            # that revno's are expensive, and pull() should honor that flag.
 
3576
            # -- JRV20090506
 
3577
            result.old_revno, result.old_revid = \
 
3578
                self.target.last_revision_info()
 
3579
            self.target.update_revisions(self.source, stop_revision,
 
3580
                overwrite=overwrite, graph=graph)
 
3581
            # TODO: The old revid should be specified when merging tags, 
 
3582
            # so a tags implementation that versions tags can only 
 
3583
            # pull in the most recent changes. -- JRV20090506
 
3584
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
3585
                overwrite, ignore_master=not merge_tags_to_master)
 
3586
            result.new_revno, result.new_revid = self.target.last_revision_info()
 
3587
            if _hook_master:
 
3588
                result.master_branch = _hook_master
 
3589
                result.local_branch = result.target_branch
 
3590
            else:
 
3591
                result.master_branch = result.target_branch
 
3592
                result.local_branch = None
 
3593
            if run_hooks:
 
3594
                for hook in Branch.hooks['post_pull']:
 
3595
                    hook(result)
3395
3596
        finally:
3396
 
            if master_branch:
3397
 
                master_branch.unlock()
 
3597
            self.source.unlock()
 
3598
        return result
3398
3599
 
3399
3600
 
3400
3601
InterBranch.register_optimiser(GenericInterBranch)
3401
 
InterBranch.register_optimiser(InterToBranch5)