~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

(jameinel) Fix bug #397739,
 resolve 'lp:foo' locally as long as we have a launchpad-login to use
 bzr+ssh. (John A Meinel)

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,
46
49
    )
47
50
""")
48
51
 
49
 
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
 
52
from bzrlib import (
 
53
    controldir,
 
54
    )
 
55
from bzrlib.decorators import (
 
56
    needs_read_lock,
 
57
    needs_write_lock,
 
58
    only_raises,
 
59
    )
50
60
from bzrlib.hooks import HookPoint, 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
295
329
    def lock_read(self):
296
330
        """Lock the branch for read operations.
297
331
 
298
 
        :return: An object with an unlock method which will release the lock
299
 
            obtained.
 
332
        :return: A bzrlib.lock.LogicalLockResult.
300
333
        """
301
334
        raise NotImplementedError(self.lock_read)
302
335
 
637
670
        raise errors.UnsupportedOperation(self.get_reference_info, self)
638
671
 
639
672
    @needs_write_lock
640
 
    def fetch(self, from_branch, last_revision=None, pb=None):
 
673
    def fetch(self, from_branch, last_revision=None, fetch_spec=None):
641
674
        """Copy revisions from from_branch into this branch.
642
675
 
643
676
        :param from_branch: Where to copy from.
644
677
        :param last_revision: What revision to stop at (None for at the end
645
678
                              of the branch.
646
 
        :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.
647
683
        :return: None
648
684
        """
 
685
        if fetch_spec is not None and last_revision is not None:
 
686
            raise AssertionError(
 
687
                "fetch_spec and last_revision are mutually exclusive.")
649
688
        if self.base == from_branch.base:
650
689
            return (0, [])
651
 
        if pb is not None:
652
 
            symbol_versioning.warn(
653
 
                symbol_versioning.deprecated_in((1, 14, 0))
654
 
                % "pb parameter to fetch()")
655
690
        from_branch.lock_read()
656
691
        try:
657
 
            if last_revision is None:
 
692
            if last_revision is None and fetch_spec is None:
658
693
                last_revision = from_branch.last_revision()
659
694
                last_revision = _mod_revision.ensure_null(last_revision)
660
695
            return self.repository.fetch(from_branch.repository,
661
696
                                         revision_id=last_revision,
662
 
                                         pb=pb)
 
697
                                         fetch_spec=fetch_spec)
663
698
        finally:
664
699
            from_branch.unlock()
665
700
 
778
813
 
779
814
    def _unstack(self):
780
815
        """Change a branch to be unstacked, copying data as needed.
781
 
        
 
816
 
782
817
        Don't call this directly, use set_stacked_on_url(None).
783
818
        """
784
819
        pb = ui.ui_factory.nested_progress_bar()
793
828
            old_repository = self.repository
794
829
            if len(old_repository._fallback_repositories) != 1:
795
830
                raise AssertionError("can't cope with fallback repositories "
796
 
                    "of %r" % (self.repository,))
797
 
            # unlock it, including unlocking the fallback
 
831
                    "of %r (fallbacks: %r)" % (old_repository,
 
832
                        old_repository._fallback_repositories))
 
833
            # Open the new repository object.
 
834
            # Repositories don't offer an interface to remove fallback
 
835
            # repositories today; take the conceptually simpler option and just
 
836
            # reopen it.  We reopen it starting from the URL so that we
 
837
            # get a separate connection for RemoteRepositories and can
 
838
            # stream from one of them to the other.  This does mean doing
 
839
            # separate SSH connection setup, but unstacking is not a
 
840
            # common operation so it's tolerable.
 
841
            new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
 
842
            new_repository = new_bzrdir.find_repository()
 
843
            if new_repository._fallback_repositories:
 
844
                raise AssertionError("didn't expect %r to have "
 
845
                    "fallback_repositories"
 
846
                    % (self.repository,))
 
847
            # Replace self.repository with the new repository.
 
848
            # Do our best to transfer the lock state (i.e. lock-tokens and
 
849
            # lock count) of self.repository to the new repository.
 
850
            lock_token = old_repository.lock_write().repository_token
 
851
            self.repository = new_repository
 
852
            if isinstance(self, remote.RemoteBranch):
 
853
                # Remote branches can have a second reference to the old
 
854
                # repository that need to be replaced.
 
855
                if self._real_branch is not None:
 
856
                    self._real_branch.repository = new_repository
 
857
            self.repository.lock_write(token=lock_token)
 
858
            if lock_token is not None:
 
859
                old_repository.leave_lock_in_place()
798
860
            old_repository.unlock()
 
861
            if lock_token is not None:
 
862
                # XXX: self.repository.leave_lock_in_place() before this
 
863
                # function will not be preserved.  Fortunately that doesn't
 
864
                # affect the current default format (2a), and would be a
 
865
                # corner-case anyway.
 
866
                #  - Andrew Bennetts, 2010/06/30
 
867
                self.repository.dont_leave_lock_in_place()
 
868
            old_lock_count = 0
 
869
            while True:
 
870
                try:
 
871
                    old_repository.unlock()
 
872
                except errors.LockNotHeld:
 
873
                    break
 
874
                old_lock_count += 1
 
875
            if old_lock_count == 0:
 
876
                raise AssertionError(
 
877
                    'old_repository should have been locked at least once.')
 
878
            for i in range(old_lock_count-1):
 
879
                self.repository.lock_write()
 
880
            # Fetch from the old repository into the new.
799
881
            old_repository.lock_read()
800
882
            try:
801
 
                # Repositories don't offer an interface to remove fallback
802
 
                # repositories today; take the conceptually simpler option and just
803
 
                # reopen it.  We reopen it starting from the URL so that we
804
 
                # get a separate connection for RemoteRepositories and can
805
 
                # stream from one of them to the other.  This does mean doing
806
 
                # separate SSH connection setup, but unstacking is not a
807
 
                # common operation so it's tolerable.
808
 
                new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
809
 
                new_repository = new_bzrdir.find_repository()
810
 
                self.repository = new_repository
811
 
                if self.repository._fallback_repositories:
812
 
                    raise AssertionError("didn't expect %r to have "
813
 
                        "fallback_repositories"
814
 
                        % (self.repository,))
815
 
                # this is not paired with an unlock because it's just restoring
816
 
                # the previous state; the lock's released when set_stacked_on_url
817
 
                # returns
818
 
                self.repository.lock_write()
819
883
                # XXX: If you unstack a branch while it has a working tree
820
884
                # with a pending merge, the pending-merged revisions will no
821
885
                # longer be present.  You can (probably) revert and remerge.
822
 
                #
823
 
                # XXX: This only fetches up to the tip of the repository; it
824
 
                # doesn't bring across any tags.  That's fairly consistent
825
 
                # with how branch works, but perhaps not ideal.
826
 
                self.repository.fetch(old_repository,
827
 
                    revision_id=self.last_revision(),
828
 
                    find_ghosts=True)
 
886
                try:
 
887
                    tags_to_fetch = set(self.tags.get_reverse_tag_dict())
 
888
                except errors.TagsNotSupported:
 
889
                    tags_to_fetch = set()
 
890
                fetch_spec = _mod_graph.NotInOtherForRevs(self.repository,
 
891
                    old_repository, required_ids=[self.last_revision()],
 
892
                    if_present_ids=tags_to_fetch, find_ghosts=True).execute()
 
893
                self.repository.fetch(old_repository, fetch_spec=fetch_spec)
829
894
            finally:
830
895
                old_repository.unlock()
831
896
        finally:
836
901
 
837
902
        :seealso: Branch._get_tags_bytes.
838
903
        """
839
 
        return _run_with_write_locked_target(self, self._transport.put_bytes,
840
 
            'tags', bytes)
 
904
        return _run_with_write_locked_target(self, self._set_tags_bytes_locked,
 
905
                bytes)
 
906
 
 
907
    def _set_tags_bytes_locked(self, bytes):
 
908
        self._tags_bytes = bytes
 
909
        return self._transport.put_bytes('tags', bytes)
841
910
 
842
911
    def _cache_revision_history(self, rev_history):
843
912
        """Set the cached revision history to rev_history.
870
939
        self._revision_history_cache = None
871
940
        self._revision_id_to_revno_cache = None
872
941
        self._last_revision_info_cache = None
 
942
        self._master_branch_cache = None
873
943
        self._merge_sorted_revisions_cache = None
874
944
        self._partial_revision_history_cache = []
875
945
        self._partial_revision_id_to_revno_cache = {}
 
946
        self._tags_bytes = None
876
947
 
877
948
    def _gen_revision_history(self):
878
949
        """Return sequence of revision hashes on to this branch.
939
1010
        else:
940
1011
            return (0, _mod_revision.NULL_REVISION)
941
1012
 
942
 
    @deprecated_method(deprecated_in((1, 6, 0)))
943
 
    def missing_revisions(self, other, stop_revision=None):
944
 
        """Return a list of new revisions that would perfectly fit.
945
 
 
946
 
        If self and other have not diverged, return a list of the revisions
947
 
        present in other, but missing from self.
948
 
        """
949
 
        self_history = self.revision_history()
950
 
        self_len = len(self_history)
951
 
        other_history = other.revision_history()
952
 
        other_len = len(other_history)
953
 
        common_index = min(self_len, other_len) -1
954
 
        if common_index >= 0 and \
955
 
            self_history[common_index] != other_history[common_index]:
956
 
            raise errors.DivergedBranches(self, other)
957
 
 
958
 
        if stop_revision is None:
959
 
            stop_revision = other_len
960
 
        else:
961
 
            if stop_revision > other_len:
962
 
                raise errors.NoSuchRevision(self, stop_revision)
963
 
        return other_history[self_len:stop_revision]
964
 
 
965
 
    @needs_write_lock
966
1013
    def update_revisions(self, other, stop_revision=None, overwrite=False,
967
 
                         graph=None):
 
1014
                         graph=None, fetch_tags=True):
968
1015
        """Pull in new perfect-fit revisions.
969
1016
 
970
1017
        :param other: Another Branch to pull from
973
1020
            to see if it is a proper descendant.
974
1021
        :param graph: A Graph object that can be used to query history
975
1022
            information. This can be None.
 
1023
        :param fetch_tags: Flag that specifies if tags from other should be
 
1024
            fetched too.
976
1025
        :return: None
977
1026
        """
978
1027
        return InterBranch.get(other, self).update_revisions(stop_revision,
979
 
            overwrite, graph)
 
1028
            overwrite, graph, fetch_tags=fetch_tags)
980
1029
 
 
1030
    @deprecated_method(deprecated_in((2, 4, 0)))
981
1031
    def import_last_revision_info(self, source_repo, revno, revid):
982
1032
        """Set the last revision info, importing from another repo if necessary.
983
1033
 
984
 
        This is used by the bound branch code to upload a revision to
985
 
        the master branch first before updating the tip of the local branch.
986
 
 
987
1034
        :param source_repo: Source repository to optionally fetch from
988
1035
        :param revno: Revision number of the new tip
989
1036
        :param revid: Revision id of the new tip
992
1039
            self.repository.fetch(source_repo, revision_id=revid)
993
1040
        self.set_last_revision_info(revno, revid)
994
1041
 
 
1042
    def import_last_revision_info_and_tags(self, source, revno, revid):
 
1043
        """Set the last revision info, importing from another repo if necessary.
 
1044
 
 
1045
        This is used by the bound branch code to upload a revision to
 
1046
        the master branch first before updating the tip of the local branch.
 
1047
        Revisions referenced by source's tags are also transferred.
 
1048
 
 
1049
        :param source: Source branch to optionally fetch from
 
1050
        :param revno: Revision number of the new tip
 
1051
        :param revid: Revision id of the new tip
 
1052
        """
 
1053
        if not self.repository.has_same_location(source.repository):
 
1054
            try:
 
1055
                tags_to_fetch = set(source.tags.get_reverse_tag_dict())
 
1056
            except errors.TagsNotSupported:
 
1057
                tags_to_fetch = set()
 
1058
            fetch_spec = _mod_graph.NotInOtherForRevs(self.repository,
 
1059
                source.repository, [revid],
 
1060
                if_present_ids=tags_to_fetch).execute()
 
1061
            self.repository.fetch(source.repository, fetch_spec=fetch_spec)
 
1062
        self.set_last_revision_info(revno, revid)
 
1063
 
995
1064
    def revision_id_to_revno(self, revision_id):
996
1065
        """Given a revision id, return its revno"""
997
1066
        if _mod_revision.is_null(revision_id):
1017
1086
            self._extend_partial_history(distance_from_last)
1018
1087
        return self._partial_revision_history_cache[distance_from_last]
1019
1088
 
1020
 
    @needs_write_lock
1021
1089
    def pull(self, source, overwrite=False, stop_revision=None,
1022
1090
             possible_transports=None, *args, **kwargs):
1023
1091
        """Mirror source into this branch.
1219
1287
        return result
1220
1288
 
1221
1289
    @needs_read_lock
1222
 
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None):
 
1290
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None,
 
1291
            repository=None):
1223
1292
        """Create a new line of development from the branch, into to_bzrdir.
1224
1293
 
1225
1294
        to_bzrdir controls the branch format.
1230
1299
        if (repository_policy is not None and
1231
1300
            repository_policy.requires_stacking()):
1232
1301
            to_bzrdir._format.require_stacking(_skip_repo=True)
1233
 
        result = to_bzrdir.create_branch()
 
1302
        result = to_bzrdir.create_branch(repository=repository)
1234
1303
        result.lock_write()
1235
1304
        try:
1236
1305
            if repository_policy is not None:
1266
1335
                revno = 1
1267
1336
        destination.set_last_revision_info(revno, revision_id)
1268
1337
 
1269
 
    @needs_read_lock
1270
1338
    def copy_content_into(self, destination, revision_id=None):
1271
1339
        """Copy the content of self into destination.
1272
1340
 
1273
1341
        revision_id: if not None, the revision history in the new branch will
1274
1342
                     be truncated to end with revision_id.
1275
1343
        """
1276
 
        self.update_references(destination)
1277
 
        self._synchronize_history(destination, revision_id)
1278
 
        try:
1279
 
            parent = self.get_parent()
1280
 
        except errors.InaccessibleParent, e:
1281
 
            mutter('parent was not accessible to copy: %s', e)
1282
 
        else:
1283
 
            if parent:
1284
 
                destination.set_parent(parent)
1285
 
        if self._push_should_merge_tags():
1286
 
            self.tags.merge_to(destination.tags)
 
1344
        return InterBranch.get(self, destination).copy_content_into(
 
1345
            revision_id=revision_id)
1287
1346
 
1288
1347
    def update_references(self, target):
1289
1348
        if not getattr(self._format, 'supports_reference_locations', False):
1334
1393
        """Return the most suitable metadir for a checkout of this branch.
1335
1394
        Weaves are used if this branch's repository uses weaves.
1336
1395
        """
1337
 
        if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
1338
 
            from bzrlib.repofmt import weaverepo
1339
 
            format = bzrdir.BzrDirMetaFormat1()
1340
 
            format.repository_format = weaverepo.RepositoryFormat7()
1341
 
        else:
1342
 
            format = self.repository.bzrdir.checkout_metadir()
1343
 
            format.set_branch_format(self._format)
 
1396
        format = self.repository.bzrdir.checkout_metadir()
 
1397
        format.set_branch_format(self._format)
1344
1398
        return format
1345
1399
 
1346
1400
    def create_clone_on_transport(self, to_transport, revision_id=None,
1347
 
        stacked_on=None, create_prefix=False, use_existing_dir=False):
 
1401
        stacked_on=None, create_prefix=False, use_existing_dir=False,
 
1402
        no_tree=None):
1348
1403
        """Create a clone of this branch and its bzrdir.
1349
1404
 
1350
1405
        :param to_transport: The transport to clone onto.
1357
1412
        """
1358
1413
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1359
1414
        # clone call. Or something. 20090224 RBC/spiv.
 
1415
        # XXX: Should this perhaps clone colocated branches as well, 
 
1416
        # rather than just the default branch? 20100319 JRV
1360
1417
        if revision_id is None:
1361
1418
            revision_id = self.last_revision()
1362
1419
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1363
1420
            revision_id=revision_id, stacked_on=stacked_on,
1364
 
            create_prefix=create_prefix, use_existing_dir=use_existing_dir)
 
1421
            create_prefix=create_prefix, use_existing_dir=use_existing_dir,
 
1422
            no_tree=no_tree)
1365
1423
        return dir_to.open_branch()
1366
1424
 
1367
1425
    def create_checkout(self, to_location, revision_id=None,
1482
1540
        else:
1483
1541
            raise AssertionError("invalid heads: %r" % (heads,))
1484
1542
 
1485
 
 
1486
 
class BranchFormat(object):
 
1543
    def heads_to_fetch(self):
 
1544
        """Return the heads that must and that should be fetched to copy this
 
1545
        branch into another repo.
 
1546
 
 
1547
        :returns: a 2-tuple of (must_fetch, if_present_fetch).  must_fetch is a
 
1548
            set of heads that must be fetched.  if_present_fetch is a set of
 
1549
            heads that must be fetched if present, but no error is necessary if
 
1550
            they are not present.
 
1551
        """
 
1552
        # For bzr native formats must_fetch is just the tip, and if_present_fetch
 
1553
        # are the tags.
 
1554
        must_fetch = set([self.last_revision()])
 
1555
        try:
 
1556
            if_present_fetch = set(self.tags.get_reverse_tag_dict())
 
1557
        except errors.TagsNotSupported:
 
1558
            if_present_fetch = set()
 
1559
        must_fetch.discard(_mod_revision.NULL_REVISION)
 
1560
        if_present_fetch.discard(_mod_revision.NULL_REVISION)
 
1561
        return must_fetch, if_present_fetch
 
1562
 
 
1563
 
 
1564
class BranchFormat(controldir.ControlComponentFormat):
1487
1565
    """An encapsulation of the initialization and open routines for a format.
1488
1566
 
1489
1567
    Formats provide three things:
1492
1570
     * an open routine.
1493
1571
 
1494
1572
    Formats are placed in an dict by their format string for reference
1495
 
    during branch opening. Its not required that these be instances, they
 
1573
    during branch opening. It's not required that these be instances, they
1496
1574
    can be classes themselves with class methods - it simply depends on
1497
1575
    whether state is needed for a given format or not.
1498
1576
 
1501
1579
    object will be created every time regardless.
1502
1580
    """
1503
1581
 
1504
 
    _default_format = None
1505
 
    """The default format used for new branches."""
1506
 
 
1507
 
    _formats = {}
1508
 
    """The known formats."""
1509
 
 
1510
1582
    can_set_append_revisions_only = True
1511
1583
 
1512
1584
    def __eq__(self, other):
1521
1593
        try:
1522
1594
            transport = a_bzrdir.get_branch_transport(None, name=name)
1523
1595
            format_string = transport.get_bytes("format")
1524
 
            return klass._formats[format_string]
 
1596
            return format_registry.get(format_string)
1525
1597
        except errors.NoSuchFile:
1526
1598
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1527
1599
        except KeyError:
1528
1600
            raise errors.UnknownFormatError(format=format_string, kind='branch')
1529
1601
 
1530
1602
    @classmethod
 
1603
    @deprecated_method(deprecated_in((2, 4, 0)))
1531
1604
    def get_default_format(klass):
1532
1605
        """Return the current default format."""
1533
 
        return klass._default_format
1534
 
 
1535
 
    def get_reference(self, a_bzrdir):
 
1606
        return format_registry.get_default()
 
1607
 
 
1608
    @classmethod
 
1609
    @deprecated_method(deprecated_in((2, 4, 0)))
 
1610
    def get_formats(klass):
 
1611
        """Get all the known formats.
 
1612
 
 
1613
        Warning: This triggers a load of all lazy registered formats: do not
 
1614
        use except when that is desireed.
 
1615
        """
 
1616
        return format_registry._get_all()
 
1617
 
 
1618
    def get_reference(self, a_bzrdir, name=None):
1536
1619
        """Get the target reference of the branch in a_bzrdir.
1537
1620
 
1538
1621
        format probing must have been completed before calling
1540
1623
        in a_bzrdir is correct.
1541
1624
 
1542
1625
        :param a_bzrdir: The bzrdir to get the branch data from.
 
1626
        :param name: Name of the colocated branch to fetch
1543
1627
        :return: None if the branch is not a reference branch.
1544
1628
        """
1545
1629
        return None
1546
1630
 
1547
1631
    @classmethod
1548
 
    def set_reference(self, a_bzrdir, to_branch):
 
1632
    def set_reference(self, a_bzrdir, name, to_branch):
1549
1633
        """Set the target reference of the branch in a_bzrdir.
1550
1634
 
1551
1635
        format probing must have been completed before calling
1553
1637
        in a_bzrdir is correct.
1554
1638
 
1555
1639
        :param a_bzrdir: The bzrdir to set the branch reference for.
 
1640
        :param name: Name of colocated branch to set, None for default
1556
1641
        :param to_branch: branch that the checkout is to reference
1557
1642
        """
1558
1643
        raise NotImplementedError(self.set_reference)
1574
1659
            hook(params)
1575
1660
 
1576
1661
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
1577
 
                           lock_type='metadir', set_format=True):
 
1662
                           repository=None):
1578
1663
        """Initialize a branch in a bzrdir, with specified files
1579
1664
 
1580
1665
        :param a_bzrdir: The bzrdir to initialize the branch in
1581
1666
        :param utf8_files: The files to create as a list of
1582
1667
            (filename, content) tuples
1583
1668
        :param name: Name of colocated branch to create, if any
1584
 
        :param set_format: If True, set the format with
1585
 
            self.get_format_string.  (BzrBranch4 has its format set
1586
 
            elsewhere)
1587
1669
        :return: a branch in this format
1588
1670
        """
1589
1671
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
1590
1672
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
1591
 
        lock_map = {
1592
 
            'metadir': ('lock', lockdir.LockDir),
1593
 
            'branch4': ('branch-lock', lockable_files.TransportLock),
1594
 
        }
1595
 
        lock_name, lock_class = lock_map[lock_type]
1596
1673
        control_files = lockable_files.LockableFiles(branch_transport,
1597
 
            lock_name, lock_class)
 
1674
            'lock', lockdir.LockDir)
1598
1675
        control_files.create_lock()
 
1676
        control_files.lock_write()
1599
1677
        try:
1600
 
            control_files.lock_write()
1601
 
        except errors.LockContention:
1602
 
            if lock_type != 'branch4':
1603
 
                raise
1604
 
            lock_taken = False
1605
 
        else:
1606
 
            lock_taken = True
1607
 
        if set_format:
1608
1678
            utf8_files += [('format', self.get_format_string())]
1609
 
        try:
1610
1679
            for (filename, content) in utf8_files:
1611
1680
                branch_transport.put_bytes(
1612
1681
                    filename, content,
1613
1682
                    mode=a_bzrdir._get_file_mode())
1614
1683
        finally:
1615
 
            if lock_taken:
1616
 
                control_files.unlock()
1617
 
        branch = self.open(a_bzrdir, name, _found=True)
 
1684
            control_files.unlock()
 
1685
        branch = self.open(a_bzrdir, name, _found=True,
 
1686
                found_repository=repository)
1618
1687
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
1619
1688
        return branch
1620
1689
 
1621
 
    def initialize(self, a_bzrdir, name=None):
 
1690
    def initialize(self, a_bzrdir, name=None, repository=None):
1622
1691
        """Create a branch of this format in a_bzrdir.
1623
1692
        
1624
1693
        :param name: Name of the colocated branch to create.
1658
1727
        """
1659
1728
        raise NotImplementedError(self.network_name)
1660
1729
 
1661
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1730
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
 
1731
            found_repository=None):
1662
1732
        """Return the branch object for a_bzrdir
1663
1733
 
1664
1734
        :param a_bzrdir: A BzrDir that contains a branch.
1671
1741
        raise NotImplementedError(self.open)
1672
1742
 
1673
1743
    @classmethod
 
1744
    @deprecated_method(deprecated_in((2, 4, 0)))
1674
1745
    def register_format(klass, format):
1675
 
        """Register a metadir format."""
1676
 
        klass._formats[format.get_format_string()] = format
1677
 
        # Metadir formats have a network name of their format string, and get
1678
 
        # registered as class factories.
1679
 
        network_format_registry.register(format.get_format_string(), format.__class__)
 
1746
        """Register a metadir format.
 
1747
 
 
1748
        See MetaDirBranchFormatFactory for the ability to register a format
 
1749
        without loading the code the format needs until it is actually used.
 
1750
        """
 
1751
        format_registry.register(format)
1680
1752
 
1681
1753
    @classmethod
 
1754
    @deprecated_method(deprecated_in((2, 4, 0)))
1682
1755
    def set_default_format(klass, format):
1683
 
        klass._default_format = format
 
1756
        format_registry.set_default(format)
1684
1757
 
1685
1758
    def supports_set_append_revisions_only(self):
1686
1759
        """True if this format supports set_append_revisions_only."""
1690
1763
        """True if this format records a stacked-on branch."""
1691
1764
        return False
1692
1765
 
 
1766
    def supports_leaving_lock(self):
 
1767
        """True if this format supports leaving locks in place."""
 
1768
        return False # by default
 
1769
 
1693
1770
    @classmethod
 
1771
    @deprecated_method(deprecated_in((2, 4, 0)))
1694
1772
    def unregister_format(klass, format):
1695
 
        del klass._formats[format.get_format_string()]
 
1773
        format_registry.remove(format)
1696
1774
 
1697
1775
    def __str__(self):
1698
1776
        return self.get_format_description().rstrip()
1702
1780
        return False  # by default
1703
1781
 
1704
1782
 
 
1783
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
 
1784
    """A factory for a BranchFormat object, permitting simple lazy registration.
 
1785
    
 
1786
    While none of the built in BranchFormats are lazy registered yet,
 
1787
    bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
 
1788
    use it, and the bzr-loom plugin uses it as well (see
 
1789
    bzrlib.plugins.loom.formats).
 
1790
    """
 
1791
 
 
1792
    def __init__(self, format_string, module_name, member_name):
 
1793
        """Create a MetaDirBranchFormatFactory.
 
1794
 
 
1795
        :param format_string: The format string the format has.
 
1796
        :param module_name: Module to load the format class from.
 
1797
        :param member_name: Attribute name within the module for the format class.
 
1798
        """
 
1799
        registry._LazyObjectGetter.__init__(self, module_name, member_name)
 
1800
        self._format_string = format_string
 
1801
        
 
1802
    def get_format_string(self):
 
1803
        """See BranchFormat.get_format_string."""
 
1804
        return self._format_string
 
1805
 
 
1806
    def __call__(self):
 
1807
        """Used for network_format_registry support."""
 
1808
        return self.get_obj()()
 
1809
 
 
1810
 
1705
1811
class BranchHooks(Hooks):
1706
1812
    """A dictionary mapping hook name to a list of callables for branch hooks.
1707
1813
 
1734
1840
            "with a bzrlib.branch.PullResult object and only runs in the "
1735
1841
            "bzr client.", (0, 15), None))
1736
1842
        self.create_hook(HookPoint('pre_commit',
1737
 
            "Called after a commit is calculated but before it is is "
 
1843
            "Called after a commit is calculated but before it is "
1738
1844
            "completed. pre_commit is called with (local, master, old_revno, "
1739
1845
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
1740
1846
            "). old_revid is NULL_REVISION for the first commit to a branch, "
1777
1883
            "all are called with the url returned from the previous hook."
1778
1884
            "The order is however undefined.", (1, 9), None))
1779
1885
        self.create_hook(HookPoint('automatic_tag_name',
1780
 
            "Called to determine an automatic tag name for a revision."
 
1886
            "Called to determine an automatic tag name for a revision. "
1781
1887
            "automatic_tag_name is called with (branch, revision_id) and "
1782
1888
            "should return a tag name or None if no tag name could be "
1783
1889
            "determined. The first non-None tag name returned will be used.",
1874
1980
        return self.__dict__ == other.__dict__
1875
1981
 
1876
1982
    def __repr__(self):
1877
 
        if self.branch:
1878
 
            return "<%s of %s>" % (self.__class__.__name__, self.branch)
1879
 
        else:
1880
 
            return "<%s of format:%s bzrdir:%s>" % (
1881
 
                self.__class__.__name__, self.branch,
1882
 
                self.format, self.bzrdir)
 
1983
        return "<%s of %s>" % (self.__class__.__name__, self.branch)
1883
1984
 
1884
1985
 
1885
1986
class SwitchHookParams(object):
1915
2016
            self.revision_id)
1916
2017
 
1917
2018
 
1918
 
class BzrBranchFormat4(BranchFormat):
1919
 
    """Bzr branch format 4.
1920
 
 
1921
 
    This format has:
1922
 
     - a revision-history file.
1923
 
     - a branch-lock lock file [ to be shared with the bzrdir ]
1924
 
    """
1925
 
 
1926
 
    def get_format_description(self):
1927
 
        """See BranchFormat.get_format_description()."""
1928
 
        return "Branch format 4"
1929
 
 
1930
 
    def initialize(self, a_bzrdir, name=None):
1931
 
        """Create a branch of this format in a_bzrdir."""
1932
 
        utf8_files = [('revision-history', ''),
1933
 
                      ('branch-name', ''),
1934
 
                      ]
1935
 
        return self._initialize_helper(a_bzrdir, utf8_files, name=name,
1936
 
                                       lock_type='branch4', set_format=False)
1937
 
 
1938
 
    def __init__(self):
1939
 
        super(BzrBranchFormat4, self).__init__()
1940
 
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
1941
 
 
1942
 
    def network_name(self):
1943
 
        """The network name for this format is the control dirs disk label."""
1944
 
        return self._matchingbzrdir.get_format_string()
1945
 
 
1946
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
1947
 
        """See BranchFormat.open()."""
1948
 
        if not _found:
1949
 
            # we are being called directly and must probe.
1950
 
            raise NotImplementedError
1951
 
        return BzrBranch(_format=self,
1952
 
                         _control_files=a_bzrdir._control_files,
1953
 
                         a_bzrdir=a_bzrdir,
1954
 
                         name=name,
1955
 
                         _repository=a_bzrdir.open_repository())
1956
 
 
1957
 
    def __str__(self):
1958
 
        return "Bazaar-NG branch format 4"
1959
 
 
1960
 
 
1961
2019
class BranchFormatMetadir(BranchFormat):
1962
2020
    """Common logic for meta-dir based branch formats."""
1963
2021
 
1972
2030
        """
1973
2031
        return self.get_format_string()
1974
2032
 
1975
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
2033
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
 
2034
            found_repository=None):
1976
2035
        """See BranchFormat.open()."""
1977
2036
        if not _found:
1978
2037
            format = BranchFormat.find_format(a_bzrdir, name=name)
1983
2042
        try:
1984
2043
            control_files = lockable_files.LockableFiles(transport, 'lock',
1985
2044
                                                         lockdir.LockDir)
 
2045
            if found_repository is None:
 
2046
                found_repository = a_bzrdir.find_repository()
1986
2047
            return self._branch_class()(_format=self,
1987
2048
                              _control_files=control_files,
1988
2049
                              name=name,
1989
2050
                              a_bzrdir=a_bzrdir,
1990
 
                              _repository=a_bzrdir.find_repository(),
 
2051
                              _repository=found_repository,
1991
2052
                              ignore_fallbacks=ignore_fallbacks)
1992
2053
        except errors.NoSuchFile:
1993
2054
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
2000
2061
    def supports_tags(self):
2001
2062
        return True
2002
2063
 
 
2064
    def supports_leaving_lock(self):
 
2065
        return True
 
2066
 
2003
2067
 
2004
2068
class BzrBranchFormat5(BranchFormatMetadir):
2005
2069
    """Bzr branch format 5.
2025
2089
        """See BranchFormat.get_format_description()."""
2026
2090
        return "Branch format 5"
2027
2091
 
2028
 
    def initialize(self, a_bzrdir, name=None):
 
2092
    def initialize(self, a_bzrdir, name=None, repository=None):
2029
2093
        """Create a branch of this format in a_bzrdir."""
2030
2094
        utf8_files = [('revision-history', ''),
2031
2095
                      ('branch-name', ''),
2032
2096
                      ]
2033
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2097
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2034
2098
 
2035
2099
    def supports_tags(self):
2036
2100
        return False
2058
2122
        """See BranchFormat.get_format_description()."""
2059
2123
        return "Branch format 6"
2060
2124
 
2061
 
    def initialize(self, a_bzrdir, name=None):
 
2125
    def initialize(self, a_bzrdir, name=None, repository=None):
2062
2126
        """Create a branch of this format in a_bzrdir."""
2063
2127
        utf8_files = [('last-revision', '0 null:\n'),
2064
2128
                      ('branch.conf', ''),
2065
2129
                      ('tags', ''),
2066
2130
                      ]
2067
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2131
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2068
2132
 
2069
2133
    def make_tags(self, branch):
2070
2134
        """See bzrlib.branch.BranchFormat.make_tags()."""
2088
2152
        """See BranchFormat.get_format_description()."""
2089
2153
        return "Branch format 8"
2090
2154
 
2091
 
    def initialize(self, a_bzrdir, name=None):
 
2155
    def initialize(self, a_bzrdir, name=None, repository=None):
2092
2156
        """Create a branch of this format in a_bzrdir."""
2093
2157
        utf8_files = [('last-revision', '0 null:\n'),
2094
2158
                      ('branch.conf', ''),
2095
2159
                      ('tags', ''),
2096
2160
                      ('references', '')
2097
2161
                      ]
2098
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2162
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2099
2163
 
2100
2164
    def __init__(self):
2101
2165
        super(BzrBranchFormat8, self).__init__()
2124
2188
    This format was introduced in bzr 1.6.
2125
2189
    """
2126
2190
 
2127
 
    def initialize(self, a_bzrdir, name=None):
 
2191
    def initialize(self, a_bzrdir, name=None, repository=None):
2128
2192
        """Create a branch of this format in a_bzrdir."""
2129
2193
        utf8_files = [('last-revision', '0 null:\n'),
2130
2194
                      ('branch.conf', ''),
2131
2195
                      ('tags', ''),
2132
2196
                      ]
2133
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2197
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2134
2198
 
2135
2199
    def _branch_class(self):
2136
2200
        return BzrBranch7
2168
2232
        """See BranchFormat.get_format_description()."""
2169
2233
        return "Checkout reference format 1"
2170
2234
 
2171
 
    def get_reference(self, a_bzrdir):
 
2235
    def get_reference(self, a_bzrdir, name=None):
2172
2236
        """See BranchFormat.get_reference()."""
2173
 
        transport = a_bzrdir.get_branch_transport(None)
 
2237
        transport = a_bzrdir.get_branch_transport(None, name=name)
2174
2238
        return transport.get_bytes('location')
2175
2239
 
2176
 
    def set_reference(self, a_bzrdir, to_branch):
 
2240
    def set_reference(self, a_bzrdir, name, to_branch):
2177
2241
        """See BranchFormat.set_reference()."""
2178
 
        transport = a_bzrdir.get_branch_transport(None)
 
2242
        transport = a_bzrdir.get_branch_transport(None, name=name)
2179
2243
        location = transport.put_bytes('location', to_branch.base)
2180
2244
 
2181
 
    def initialize(self, a_bzrdir, name=None, target_branch=None):
 
2245
    def initialize(self, a_bzrdir, name=None, target_branch=None,
 
2246
            repository=None):
2182
2247
        """Create a branch of this format in a_bzrdir."""
2183
2248
        if target_branch is None:
2184
2249
            # this format does not implement branch itself, thus the implicit
2212
2277
        return clone
2213
2278
 
2214
2279
    def open(self, a_bzrdir, name=None, _found=False, location=None,
2215
 
             possible_transports=None, ignore_fallbacks=False):
 
2280
             possible_transports=None, ignore_fallbacks=False,
 
2281
             found_repository=None):
2216
2282
        """Return the branch that the branch reference in a_bzrdir points at.
2217
2283
 
2218
2284
        :param a_bzrdir: A BzrDir that contains a branch.
2232
2298
                raise AssertionError("wrong format %r found for %r" %
2233
2299
                    (format, self))
2234
2300
        if location is None:
2235
 
            location = self.get_reference(a_bzrdir)
 
2301
            location = self.get_reference(a_bzrdir, name)
2236
2302
        real_bzrdir = bzrdir.BzrDir.open(
2237
2303
            location, possible_transports=possible_transports)
2238
2304
        result = real_bzrdir.open_branch(name=name, 
2249
2315
        return result
2250
2316
 
2251
2317
 
 
2318
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
 
2319
    """Branch format registry."""
 
2320
 
 
2321
    def __init__(self, other_registry=None):
 
2322
        super(BranchFormatRegistry, self).__init__(other_registry)
 
2323
        self._default_format = None
 
2324
 
 
2325
    def set_default(self, format):
 
2326
        self._default_format = format
 
2327
 
 
2328
    def get_default(self):
 
2329
        return self._default_format
 
2330
 
 
2331
 
2252
2332
network_format_registry = registry.FormatRegistry()
2253
2333
"""Registry of formats indexed by their network name.
2254
2334
 
2257
2337
BranchFormat.network_name() for more detail.
2258
2338
"""
2259
2339
 
 
2340
format_registry = BranchFormatRegistry(network_format_registry)
 
2341
 
2260
2342
 
2261
2343
# formats which have no format string are not discoverable
2262
2344
# and not independently creatable, so are not registered.
2264
2346
__format6 = BzrBranchFormat6()
2265
2347
__format7 = BzrBranchFormat7()
2266
2348
__format8 = BzrBranchFormat8()
2267
 
BranchFormat.register_format(__format5)
2268
 
BranchFormat.register_format(BranchReferenceFormat())
2269
 
BranchFormat.register_format(__format6)
2270
 
BranchFormat.register_format(__format7)
2271
 
BranchFormat.register_format(__format8)
2272
 
BranchFormat.set_default_format(__format7)
2273
 
_legacy_formats = [BzrBranchFormat4(),
2274
 
    ]
2275
 
network_format_registry.register(
2276
 
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
2277
 
 
2278
 
 
2279
 
class BranchWriteLockResult(object):
 
2349
format_registry.register(__format5)
 
2350
format_registry.register(BranchReferenceFormat())
 
2351
format_registry.register(__format6)
 
2352
format_registry.register(__format7)
 
2353
format_registry.register(__format8)
 
2354
format_registry.set_default(__format7)
 
2355
 
 
2356
 
 
2357
class BranchWriteLockResult(LogicalLockResult):
2280
2358
    """The result of write locking a branch.
2281
2359
 
2282
2360
    :ivar branch_token: The token obtained from the underlying branch lock, or
2285
2363
    """
2286
2364
 
2287
2365
    def __init__(self, unlock, branch_token):
 
2366
        LogicalLockResult.__init__(self, unlock)
2288
2367
        self.branch_token = branch_token
2289
 
        self.unlock = unlock
2290
2368
 
2291
 
    def __str__(self):
 
2369
    def __repr__(self):
2292
2370
        return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
2293
2371
            self.unlock)
2294
2372
 
2379
2457
    def lock_read(self):
2380
2458
        """Lock the branch for read operations.
2381
2459
 
2382
 
        :return: An object with an unlock method which will release the lock
2383
 
            obtained.
 
2460
        :return: A bzrlib.lock.LogicalLockResult.
2384
2461
        """
2385
2462
        if not self.is_locked():
2386
2463
            self._note_lock('r')
2394
2471
            took_lock = False
2395
2472
        try:
2396
2473
            self.control_files.lock_read()
2397
 
            return self
 
2474
            return LogicalLockResult(self.unlock)
2398
2475
        except:
2399
2476
            if took_lock:
2400
2477
                self.repository.unlock()
2556
2633
        result.target_branch = target
2557
2634
        result.old_revno, result.old_revid = target.last_revision_info()
2558
2635
        self.update_references(target)
2559
 
        if result.old_revid != self.last_revision():
 
2636
        if result.old_revid != stop_revision:
2560
2637
            # We assume that during 'push' this repository is closer than
2561
2638
            # the target.
2562
2639
            graph = self.repository.get_graph(target.repository)
2563
2640
            target.update_revisions(self, stop_revision,
2564
2641
                overwrite=overwrite, graph=graph)
2565
2642
        if self._push_should_merge_tags():
2566
 
            result.tag_conflicts = self.tags.merge_to(target.tags,
2567
 
                overwrite)
 
2643
            result.tag_conflicts = self.tags.merge_to(target.tags, overwrite)
2568
2644
        result.new_revno, result.new_revid = target.last_revision_info()
2569
2645
        return result
2570
2646
 
2602
2678
        """Return the branch we are bound to.
2603
2679
 
2604
2680
        :return: Either a Branch, or None
2605
 
 
2606
 
        This could memoise the branch, but if thats done
2607
 
        it must be revalidated on each new lock.
2608
 
        So for now we just don't memoise it.
2609
 
        # RBC 20060304 review this decision.
2610
2681
        """
 
2682
        if self._master_branch_cache is None:
 
2683
            self._master_branch_cache = self._get_master_branch(
 
2684
                possible_transports)
 
2685
        return self._master_branch_cache
 
2686
 
 
2687
    def _get_master_branch(self, possible_transports):
2611
2688
        bound_loc = self.get_bound_location()
2612
2689
        if not bound_loc:
2613
2690
            return None
2624
2701
 
2625
2702
        :param location: URL to the target branch
2626
2703
        """
 
2704
        self._master_branch_cache = None
2627
2705
        if location:
2628
2706
            self._transport.put_bytes('bound', location+'\n',
2629
2707
                mode=self.bzrdir._get_file_mode())
2881
2959
 
2882
2960
    def set_bound_location(self, location):
2883
2961
        """See Branch.set_push_location."""
 
2962
        self._master_branch_cache = None
2884
2963
        result = None
2885
2964
        config = self.get_config()
2886
2965
        if location is None:
2963
3042
        try:
2964
3043
            index = self._partial_revision_history_cache.index(revision_id)
2965
3044
        except ValueError:
2966
 
            self._extend_partial_history(stop_revision=revision_id)
 
3045
            try:
 
3046
                self._extend_partial_history(stop_revision=revision_id)
 
3047
            except errors.RevisionNotPresent, e:
 
3048
                raise errors.GhostRevisionsHaveNoRevno(revision_id, e.revision_id)
2967
3049
            index = len(self._partial_revision_history_cache) - 1
2968
3050
            if self._partial_revision_history_cache[index] != revision_id:
2969
3051
                raise errors.NoSuchRevision(self, revision_id)
3024
3106
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
3025
3107
    """
3026
3108
 
 
3109
    @deprecated_method(deprecated_in((2, 3, 0)))
3027
3110
    def __int__(self):
3028
 
        # DEPRECATED: pull used to return the change in revno
 
3111
        """Return the relative change in revno.
 
3112
 
 
3113
        :deprecated: Use `new_revno` and `old_revno` instead.
 
3114
        """
3029
3115
        return self.new_revno - self.old_revno
3030
3116
 
3031
3117
    def report(self, to_file):
3056
3142
        target, otherwise it will be None.
3057
3143
    """
3058
3144
 
 
3145
    @deprecated_method(deprecated_in((2, 3, 0)))
3059
3146
    def __int__(self):
3060
 
        # DEPRECATED: push used to return the change in revno
 
3147
        """Return the relative change in revno.
 
3148
 
 
3149
        :deprecated: Use `new_revno` and `old_revno` instead.
 
3150
        """
3061
3151
        return self.new_revno - self.old_revno
3062
3152
 
3063
3153
    def report(self, to_file):
3186
3276
    _optimisers = []
3187
3277
    """The available optimised InterBranch types."""
3188
3278
 
3189
 
    @staticmethod
3190
 
    def _get_branch_formats_to_test():
3191
 
        """Return a tuple with the Branch formats to use when testing."""
3192
 
        raise NotImplementedError(InterBranch._get_branch_formats_to_test)
 
3279
    @classmethod
 
3280
    def _get_branch_formats_to_test(klass):
 
3281
        """Return an iterable of format tuples for testing.
 
3282
        
 
3283
        :return: An iterable of (from_format, to_format) to use when testing
 
3284
            this InterBranch class. Each InterBranch class should define this
 
3285
            method itself.
 
3286
        """
 
3287
        raise NotImplementedError(klass._get_branch_formats_to_test)
3193
3288
 
 
3289
    @needs_write_lock
3194
3290
    def pull(self, overwrite=False, stop_revision=None,
3195
3291
             possible_transports=None, local=False):
3196
3292
        """Mirror source into target branch.
3201
3297
        """
3202
3298
        raise NotImplementedError(self.pull)
3203
3299
 
 
3300
    @needs_write_lock
3204
3301
    def update_revisions(self, stop_revision=None, overwrite=False,
3205
 
                         graph=None):
 
3302
                         graph=None, fetch_tags=True):
3206
3303
        """Pull in new perfect-fit revisions.
3207
3304
 
3208
3305
        :param stop_revision: Updated until the given revision
3210
3307
            to see if it is a proper descendant.
3211
3308
        :param graph: A Graph object that can be used to query history
3212
3309
            information. This can be None.
 
3310
        :param fetch_tags: Flag that specifies if tags from source should be
 
3311
            fetched too.
3213
3312
        :return: None
3214
3313
        """
3215
3314
        raise NotImplementedError(self.update_revisions)
3216
3315
 
 
3316
    @needs_write_lock
3217
3317
    def push(self, overwrite=False, stop_revision=None,
3218
3318
             _override_hook_source_branch=None):
3219
3319
        """Mirror the source branch into the target branch.
3222
3322
        """
3223
3323
        raise NotImplementedError(self.push)
3224
3324
 
 
3325
    @needs_write_lock
 
3326
    def copy_content_into(self, revision_id=None):
 
3327
        """Copy the content of source into target
 
3328
 
 
3329
        revision_id: if not None, the revision history in the new branch will
 
3330
                     be truncated to end with revision_id.
 
3331
        """
 
3332
        raise NotImplementedError(self.copy_content_into)
 
3333
 
3225
3334
 
3226
3335
class GenericInterBranch(InterBranch):
3227
 
    """InterBranch implementation that uses public Branch functions.
3228
 
    """
3229
 
 
3230
 
    @staticmethod
3231
 
    def _get_branch_formats_to_test():
3232
 
        return BranchFormat._default_format, BranchFormat._default_format
3233
 
 
 
3336
    """InterBranch implementation that uses public Branch functions."""
 
3337
 
 
3338
    @classmethod
 
3339
    def is_compatible(klass, source, target):
 
3340
        # GenericBranch uses the public API, so always compatible
 
3341
        return True
 
3342
 
 
3343
    @classmethod
 
3344
    def _get_branch_formats_to_test(klass):
 
3345
        return [(format_registry.get_default(), format_registry.get_default())]
 
3346
 
 
3347
    @classmethod
 
3348
    def unwrap_format(klass, format):
 
3349
        if isinstance(format, remote.RemoteBranchFormat):
 
3350
            format._ensure_real()
 
3351
            return format._custom_format
 
3352
        return format
 
3353
 
 
3354
    @needs_write_lock
 
3355
    def copy_content_into(self, revision_id=None):
 
3356
        """Copy the content of source into target
 
3357
 
 
3358
        revision_id: if not None, the revision history in the new branch will
 
3359
                     be truncated to end with revision_id.
 
3360
        """
 
3361
        self.source.update_references(self.target)
 
3362
        self.source._synchronize_history(self.target, revision_id)
 
3363
        try:
 
3364
            parent = self.source.get_parent()
 
3365
        except errors.InaccessibleParent, e:
 
3366
            mutter('parent was not accessible to copy: %s', e)
 
3367
        else:
 
3368
            if parent:
 
3369
                self.target.set_parent(parent)
 
3370
        if self.source._push_should_merge_tags():
 
3371
            self.source.tags.merge_to(self.target.tags)
 
3372
 
 
3373
    @needs_write_lock
3234
3374
    def update_revisions(self, stop_revision=None, overwrite=False,
3235
 
        graph=None):
 
3375
        graph=None, fetch_tags=True):
3236
3376
        """See InterBranch.update_revisions()."""
3237
 
        self.source.lock_read()
3238
 
        try:
3239
 
            other_revno, other_last_revision = self.source.last_revision_info()
3240
 
            stop_revno = None # unknown
3241
 
            if stop_revision is None:
3242
 
                stop_revision = other_last_revision
3243
 
                if _mod_revision.is_null(stop_revision):
3244
 
                    # if there are no commits, we're done.
3245
 
                    return
3246
 
                stop_revno = other_revno
3247
 
 
3248
 
            # what's the current last revision, before we fetch [and change it
3249
 
            # possibly]
3250
 
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
3251
 
            # we fetch here so that we don't process data twice in the common
3252
 
            # case of having something to pull, and so that the check for
3253
 
            # already merged can operate on the just fetched graph, which will
3254
 
            # be cached in memory.
3255
 
            self.target.fetch(self.source, stop_revision)
3256
 
            # Check to see if one is an ancestor of the other
3257
 
            if not overwrite:
3258
 
                if graph is None:
3259
 
                    graph = self.target.repository.get_graph()
3260
 
                if self.target._check_if_descendant_or_diverged(
3261
 
                        stop_revision, last_rev, graph, self.source):
3262
 
                    # stop_revision is a descendant of last_rev, but we aren't
3263
 
                    # overwriting, so we're done.
3264
 
                    return
3265
 
            if stop_revno is None:
3266
 
                if graph is None:
3267
 
                    graph = self.target.repository.get_graph()
3268
 
                this_revno, this_last_revision = \
3269
 
                        self.target.last_revision_info()
3270
 
                stop_revno = graph.find_distance_to_null(stop_revision,
3271
 
                                [(other_last_revision, other_revno),
3272
 
                                 (this_last_revision, this_revno)])
3273
 
            self.target.set_last_revision_info(stop_revno, stop_revision)
3274
 
        finally:
3275
 
            self.source.unlock()
3276
 
 
 
3377
        other_revno, other_last_revision = self.source.last_revision_info()
 
3378
        stop_revno = None # unknown
 
3379
        if stop_revision is None:
 
3380
            stop_revision = other_last_revision
 
3381
            if _mod_revision.is_null(stop_revision):
 
3382
                # if there are no commits, we're done.
 
3383
                return
 
3384
            stop_revno = other_revno
 
3385
 
 
3386
        # what's the current last revision, before we fetch [and change it
 
3387
        # possibly]
 
3388
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
3389
        # we fetch here so that we don't process data twice in the common
 
3390
        # case of having something to pull, and so that the check for
 
3391
        # already merged can operate on the just fetched graph, which will
 
3392
        # be cached in memory.
 
3393
        if fetch_tags:
 
3394
            fetch_spec_factory = fetch.FetchSpecFactory()
 
3395
            fetch_spec_factory.source_branch = self.source
 
3396
            fetch_spec_factory.source_branch_stop_revision_id = stop_revision
 
3397
            fetch_spec_factory.source_repo = self.source.repository
 
3398
            fetch_spec_factory.target_repo = self.target.repository
 
3399
            fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
 
3400
            fetch_spec = fetch_spec_factory.make_fetch_spec()
 
3401
        else:
 
3402
            fetch_spec = _mod_graph.NotInOtherForRevs(self.target.repository,
 
3403
                self.source.repository, revision_ids=[stop_revision]).execute()
 
3404
        self.target.fetch(self.source, fetch_spec=fetch_spec)
 
3405
        # Check to see if one is an ancestor of the other
 
3406
        if not overwrite:
 
3407
            if graph is None:
 
3408
                graph = self.target.repository.get_graph()
 
3409
            if self.target._check_if_descendant_or_diverged(
 
3410
                    stop_revision, last_rev, graph, self.source):
 
3411
                # stop_revision is a descendant of last_rev, but we aren't
 
3412
                # overwriting, so we're done.
 
3413
                return
 
3414
        if stop_revno is None:
 
3415
            if graph is None:
 
3416
                graph = self.target.repository.get_graph()
 
3417
            this_revno, this_last_revision = \
 
3418
                    self.target.last_revision_info()
 
3419
            stop_revno = graph.find_distance_to_null(stop_revision,
 
3420
                            [(other_last_revision, other_revno),
 
3421
                             (this_last_revision, this_revno)])
 
3422
        self.target.set_last_revision_info(stop_revno, stop_revision)
 
3423
 
 
3424
    @needs_write_lock
3277
3425
    def pull(self, overwrite=False, stop_revision=None,
3278
 
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3426
             possible_transports=None, run_hooks=True,
3279
3427
             _override_hook_target=None, local=False):
3280
 
        """See Branch.pull.
 
3428
        """Pull from source into self, updating my master if any.
3281
3429
 
3282
 
        :param _hook_master: Private parameter - set the branch to
3283
 
            be supplied as the master to pull hooks.
3284
3430
        :param run_hooks: Private parameter - if false, this branch
3285
3431
            is being called because it's the master of the primary branch,
3286
3432
            so it should not run its hooks.
3287
 
        :param _override_hook_target: Private parameter - set the branch to be
3288
 
            supplied as the target_branch to pull hooks.
3289
 
        :param local: Only update the local branch, and not the bound branch.
3290
3433
        """
3291
 
        # This type of branch can't be bound.
3292
 
        if local:
 
3434
        bound_location = self.target.get_bound_location()
 
3435
        if local and not bound_location:
3293
3436
            raise errors.LocalRequiresBoundBranch()
3294
 
        result = PullResult()
3295
 
        result.source_branch = self.source
3296
 
        if _override_hook_target is None:
3297
 
            result.target_branch = self.target
3298
 
        else:
3299
 
            result.target_branch = _override_hook_target
3300
 
        self.source.lock_read()
 
3437
        master_branch = None
 
3438
        source_is_master = (self.source.user_url == bound_location)
 
3439
        if not local and bound_location and not source_is_master:
 
3440
            # not pulling from master, so we need to update master.
 
3441
            master_branch = self.target.get_master_branch(possible_transports)
 
3442
            master_branch.lock_write()
3301
3443
        try:
3302
 
            # We assume that during 'pull' the target repository is closer than
3303
 
            # the source one.
3304
 
            self.source.update_references(self.target)
3305
 
            graph = self.target.repository.get_graph(self.source.repository)
3306
 
            # TODO: Branch formats should have a flag that indicates 
3307
 
            # that revno's are expensive, and pull() should honor that flag.
3308
 
            # -- JRV20090506
3309
 
            result.old_revno, result.old_revid = \
3310
 
                self.target.last_revision_info()
3311
 
            self.target.update_revisions(self.source, stop_revision,
3312
 
                overwrite=overwrite, graph=graph)
3313
 
            # TODO: The old revid should be specified when merging tags, 
3314
 
            # so a tags implementation that versions tags can only 
3315
 
            # pull in the most recent changes. -- JRV20090506
3316
 
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3317
 
                overwrite)
3318
 
            result.new_revno, result.new_revid = self.target.last_revision_info()
3319
 
            if _hook_master:
3320
 
                result.master_branch = _hook_master
3321
 
                result.local_branch = result.target_branch
3322
 
            else:
3323
 
                result.master_branch = result.target_branch
3324
 
                result.local_branch = None
3325
 
            if run_hooks:
3326
 
                for hook in Branch.hooks['post_pull']:
3327
 
                    hook(result)
 
3444
            if master_branch:
 
3445
                # pull from source into master.
 
3446
                master_branch.pull(self.source, overwrite, stop_revision,
 
3447
                    run_hooks=False)
 
3448
            return self._pull(overwrite,
 
3449
                stop_revision, _hook_master=master_branch,
 
3450
                run_hooks=run_hooks,
 
3451
                _override_hook_target=_override_hook_target,
 
3452
                merge_tags_to_master=not source_is_master)
3328
3453
        finally:
3329
 
            self.source.unlock()
3330
 
        return result
 
3454
            if master_branch:
 
3455
                master_branch.unlock()
3331
3456
 
3332
3457
    def push(self, overwrite=False, stop_revision=None,
3333
3458
             _override_hook_source_branch=None):
3373
3498
                # push into the master from the source branch.
3374
3499
                self.source._basic_push(master_branch, overwrite, stop_revision)
3375
3500
                # and push into the target branch from the source. Note that we
3376
 
                # push from the source branch again, because its considered the
 
3501
                # push from the source branch again, because it's considered the
3377
3502
                # highest bandwidth repository.
3378
3503
                result = self.source._basic_push(self.target, overwrite,
3379
3504
                    stop_revision)
3395
3520
            _run_hooks()
3396
3521
            return result
3397
3522
 
3398
 
    @classmethod
3399
 
    def is_compatible(self, source, target):
3400
 
        # GenericBranch uses the public API, so always compatible
3401
 
        return True
3402
 
 
3403
 
 
3404
 
class InterToBranch5(GenericInterBranch):
3405
 
 
3406
 
    @staticmethod
3407
 
    def _get_branch_formats_to_test():
3408
 
        return BranchFormat._default_format, BzrBranchFormat5()
3409
 
 
3410
 
    def pull(self, overwrite=False, stop_revision=None,
3411
 
             possible_transports=None, run_hooks=True,
3412
 
             _override_hook_target=None, local=False):
3413
 
        """Pull from source into self, updating my master if any.
3414
 
 
 
3523
    def _pull(self, overwrite=False, stop_revision=None,
 
3524
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3525
             _override_hook_target=None, local=False,
 
3526
             merge_tags_to_master=True):
 
3527
        """See Branch.pull.
 
3528
 
 
3529
        This function is the core worker, used by GenericInterBranch.pull to
 
3530
        avoid duplication when pulling source->master and source->local.
 
3531
 
 
3532
        :param _hook_master: Private parameter - set the branch to
 
3533
            be supplied as the master to pull hooks.
3415
3534
        :param run_hooks: Private parameter - if false, this branch
3416
3535
            is being called because it's the master of the primary branch,
3417
3536
            so it should not run its hooks.
 
3537
            is being called because it's the master of the primary branch,
 
3538
            so it should not run its hooks.
 
3539
        :param _override_hook_target: Private parameter - set the branch to be
 
3540
            supplied as the target_branch to pull hooks.
 
3541
        :param local: Only update the local branch, and not the bound branch.
3418
3542
        """
3419
 
        bound_location = self.target.get_bound_location()
3420
 
        if local and not bound_location:
 
3543
        # This type of branch can't be bound.
 
3544
        if local:
3421
3545
            raise errors.LocalRequiresBoundBranch()
3422
 
        master_branch = None
3423
 
        if not local and bound_location and self.source.user_url != bound_location:
3424
 
            # not pulling from master, so we need to update master.
3425
 
            master_branch = self.target.get_master_branch(possible_transports)
3426
 
            master_branch.lock_write()
 
3546
        result = PullResult()
 
3547
        result.source_branch = self.source
 
3548
        if _override_hook_target is None:
 
3549
            result.target_branch = self.target
 
3550
        else:
 
3551
            result.target_branch = _override_hook_target
 
3552
        self.source.lock_read()
3427
3553
        try:
3428
 
            if master_branch:
3429
 
                # pull from source into master.
3430
 
                master_branch.pull(self.source, overwrite, stop_revision,
3431
 
                    run_hooks=False)
3432
 
            return super(InterToBranch5, self).pull(overwrite,
3433
 
                stop_revision, _hook_master=master_branch,
3434
 
                run_hooks=run_hooks,
3435
 
                _override_hook_target=_override_hook_target)
 
3554
            # We assume that during 'pull' the target repository is closer than
 
3555
            # the source one.
 
3556
            self.source.update_references(self.target)
 
3557
            graph = self.target.repository.get_graph(self.source.repository)
 
3558
            # TODO: Branch formats should have a flag that indicates 
 
3559
            # that revno's are expensive, and pull() should honor that flag.
 
3560
            # -- JRV20090506
 
3561
            result.old_revno, result.old_revid = \
 
3562
                self.target.last_revision_info()
 
3563
            self.target.update_revisions(self.source, stop_revision,
 
3564
                overwrite=overwrite, graph=graph)
 
3565
            # TODO: The old revid should be specified when merging tags, 
 
3566
            # so a tags implementation that versions tags can only 
 
3567
            # pull in the most recent changes. -- JRV20090506
 
3568
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
3569
                overwrite, ignore_master=not merge_tags_to_master)
 
3570
            result.new_revno, result.new_revid = self.target.last_revision_info()
 
3571
            if _hook_master:
 
3572
                result.master_branch = _hook_master
 
3573
                result.local_branch = result.target_branch
 
3574
            else:
 
3575
                result.master_branch = result.target_branch
 
3576
                result.local_branch = None
 
3577
            if run_hooks:
 
3578
                for hook in Branch.hooks['post_pull']:
 
3579
                    hook(result)
3436
3580
        finally:
3437
 
            if master_branch:
3438
 
                master_branch.unlock()
 
3581
            self.source.unlock()
 
3582
        return result
3439
3583
 
3440
3584
 
3441
3585
InterBranch.register_optimiser(GenericInterBranch)
3442
 
InterBranch.register_optimiser(InterToBranch5)