/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: John Arbash Meinel
  • Date: 2011-04-22 14:12:22 UTC
  • mfrom: (5809 +trunk)
  • mto: This revision was merged to the branch mainline in revision 5836.
  • Revision ID: john@arbash-meinel.com-20110422141222-nx2j0hbkihcb8j16
Merge newer bzr.dev and resolve conflicts.
Try to write some documentation about how the _dirblock_state works.
Fix up the tests so that they pass again.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005-2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
27
27
        config as _mod_config,
28
28
        debug,
29
29
        errors,
 
30
        fetch,
 
31
        graph as _mod_graph,
30
32
        lockdir,
31
33
        lockable_files,
 
34
        remote,
32
35
        repository,
33
36
        revision as _mod_revision,
34
37
        rio,
39
42
        urlutils,
40
43
        )
41
44
from bzrlib.config import BranchConfig, TransportConfig
42
 
from bzrlib.repofmt.pack_repo import RepositoryFormatKnitPack5RichRoot
43
45
from bzrlib.tag import (
44
46
    BasicTags,
45
47
    DisabledTags,
46
48
    )
47
49
""")
48
50
 
49
 
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
50
 
from bzrlib.hooks import HookPoint, Hooks
 
51
from bzrlib import (
 
52
    controldir,
 
53
    )
 
54
from bzrlib.decorators import (
 
55
    needs_read_lock,
 
56
    needs_write_lock,
 
57
    only_raises,
 
58
    )
 
59
from bzrlib.hooks import Hooks
51
60
from bzrlib.inter import InterObject
52
61
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
53
62
from bzrlib import registry
63
72
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
64
73
 
65
74
 
66
 
class Branch(bzrdir.ControlComponent):
 
75
class Branch(controldir.ControlComponent):
67
76
    """Branch holding a history of revisions.
68
77
 
69
78
    :ivar base:
70
79
        Base directory/url of the branch; using control_url and
71
80
        control_transport is more standardized.
72
 
 
73
 
    hooks: An instance of BranchHooks.
 
81
    :ivar hooks: An instance of BranchHooks.
 
82
    :ivar _master_branch_cache: cached result of get_master_branch, see
 
83
        _clear_cached_state.
74
84
    """
75
85
    # this is really an instance variable - FIXME move it there
76
86
    # - RBC 20060112
90
100
        self._revision_id_to_revno_cache = None
91
101
        self._partial_revision_id_to_revno_cache = {}
92
102
        self._partial_revision_history_cache = []
 
103
        self._tags_bytes = None
93
104
        self._last_revision_info_cache = None
 
105
        self._master_branch_cache = None
94
106
        self._merge_sorted_revisions_cache = None
95
107
        self._open_hook()
96
108
        hooks = Branch.hooks['open']
102
114
 
103
115
    def _activate_fallback_location(self, url):
104
116
        """Activate the branch/repository from url as a fallback repository."""
 
117
        for existing_fallback_repo in self.repository._fallback_repositories:
 
118
            if existing_fallback_repo.user_url == url:
 
119
                # This fallback is already configured.  This probably only
 
120
                # happens because BzrDir.sprout is a horrible mess.  To avoid
 
121
                # confusing _unstack we don't add this a second time.
 
122
                mutter('duplicate activation of fallback %r on %r', url, self)
 
123
                return
105
124
        repo = self._get_fallback_repository(url)
106
125
        if repo.has_same_location(self.repository):
107
126
            raise errors.UnstackableLocationError(self.user_url, url)
197
216
        return self.supports_tags() and self.tags.get_tag_dict()
198
217
 
199
218
    def get_config(self):
 
219
        """Get a bzrlib.config.BranchConfig for this Branch.
 
220
 
 
221
        This can then be used to get and set configuration options for the
 
222
        branch.
 
223
 
 
224
        :return: A bzrlib.config.BranchConfig.
 
225
        """
200
226
        return BranchConfig(self)
201
227
 
202
228
    def _get_config(self):
218
244
            possible_transports=[self.bzrdir.root_transport])
219
245
        return a_branch.repository
220
246
 
 
247
    @needs_read_lock
221
248
    def _get_tags_bytes(self):
222
249
        """Get the bytes of a serialised tags dict.
223
250
 
230
257
        :return: The bytes of the tags file.
231
258
        :seealso: Branch._set_tags_bytes.
232
259
        """
233
 
        return self._transport.get_bytes('tags')
 
260
        if self._tags_bytes is None:
 
261
            self._tags_bytes = self._transport.get_bytes('tags')
 
262
        return self._tags_bytes
234
263
 
235
264
    def _get_nick(self, local=False, possible_transports=None):
236
265
        config = self.get_config()
238
267
        if not local and not config.has_explicit_nickname():
239
268
            try:
240
269
                master = self.get_master_branch(possible_transports)
 
270
                if master and self.user_url == master.user_url:
 
271
                    raise errors.RecursiveBind(self.user_url)
241
272
                if master is not None:
242
273
                    # return the master branch value
243
274
                    return master.nick
 
275
            except errors.RecursiveBind, e:
 
276
                raise e
244
277
            except errors.BzrError, e:
245
278
                # Silently fall back to local implicit nick if the master is
246
279
                # unavailable
636
669
        raise errors.UnsupportedOperation(self.get_reference_info, self)
637
670
 
638
671
    @needs_write_lock
639
 
    def fetch(self, from_branch, last_revision=None, pb=None):
 
672
    def fetch(self, from_branch, last_revision=None, fetch_spec=None):
640
673
        """Copy revisions from from_branch into this branch.
641
674
 
642
675
        :param from_branch: Where to copy from.
643
676
        :param last_revision: What revision to stop at (None for at the end
644
677
                              of the branch.
645
 
        :param pb: An optional progress bar to use.
 
678
        :param fetch_spec: If specified, a SearchResult or
 
679
            PendingAncestryResult that describes which revisions to copy.  This
 
680
            allows copying multiple heads at once.  Mutually exclusive with
 
681
            last_revision.
646
682
        :return: None
647
683
        """
648
 
        if self.base == from_branch.base:
649
 
            return (0, [])
650
 
        if pb is not None:
651
 
            symbol_versioning.warn(
652
 
                symbol_versioning.deprecated_in((1, 14, 0))
653
 
                % "pb parameter to fetch()")
654
 
        from_branch.lock_read()
655
 
        try:
656
 
            if last_revision is None:
657
 
                last_revision = from_branch.last_revision()
658
 
                last_revision = _mod_revision.ensure_null(last_revision)
659
 
            return self.repository.fetch(from_branch.repository,
660
 
                                         revision_id=last_revision,
661
 
                                         pb=pb)
662
 
        finally:
663
 
            from_branch.unlock()
 
684
        return InterBranch.get(from_branch, self).fetch(last_revision,
 
685
            fetch_spec)
664
686
 
665
687
    def get_bound_location(self):
666
688
        """Return the URL of the branch we are bound to.
677
699
 
678
700
    def get_commit_builder(self, parents, config=None, timestamp=None,
679
701
                           timezone=None, committer=None, revprops=None,
680
 
                           revision_id=None):
 
702
                           revision_id=None, lossy=False):
681
703
        """Obtain a CommitBuilder for this branch.
682
704
 
683
705
        :param parents: Revision ids of the parents of the new revision.
687
709
        :param committer: Optional committer to set for commit.
688
710
        :param revprops: Optional dictionary of revision properties.
689
711
        :param revision_id: Optional revision id.
 
712
        :param lossy: Whether to discard data that can not be natively
 
713
            represented, when pushing to a foreign VCS 
690
714
        """
691
715
 
692
716
        if config is None:
693
717
            config = self.get_config()
694
718
 
695
719
        return self.repository.get_commit_builder(self, parents, config,
696
 
            timestamp, timezone, committer, revprops, revision_id)
 
720
            timestamp, timezone, committer, revprops, revision_id,
 
721
            lossy)
697
722
 
698
723
    def get_master_branch(self, possible_transports=None):
699
724
        """Return the branch we are bound to.
777
802
 
778
803
    def _unstack(self):
779
804
        """Change a branch to be unstacked, copying data as needed.
780
 
        
 
805
 
781
806
        Don't call this directly, use set_stacked_on_url(None).
782
807
        """
783
808
        pb = ui.ui_factory.nested_progress_bar()
792
817
            old_repository = self.repository
793
818
            if len(old_repository._fallback_repositories) != 1:
794
819
                raise AssertionError("can't cope with fallback repositories "
795
 
                    "of %r" % (self.repository,))
796
 
            # unlock it, including unlocking the fallback
 
820
                    "of %r (fallbacks: %r)" % (old_repository,
 
821
                        old_repository._fallback_repositories))
 
822
            # Open the new repository object.
 
823
            # Repositories don't offer an interface to remove fallback
 
824
            # repositories today; take the conceptually simpler option and just
 
825
            # reopen it.  We reopen it starting from the URL so that we
 
826
            # get a separate connection for RemoteRepositories and can
 
827
            # stream from one of them to the other.  This does mean doing
 
828
            # separate SSH connection setup, but unstacking is not a
 
829
            # common operation so it's tolerable.
 
830
            new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
 
831
            new_repository = new_bzrdir.find_repository()
 
832
            if new_repository._fallback_repositories:
 
833
                raise AssertionError("didn't expect %r to have "
 
834
                    "fallback_repositories"
 
835
                    % (self.repository,))
 
836
            # Replace self.repository with the new repository.
 
837
            # Do our best to transfer the lock state (i.e. lock-tokens and
 
838
            # lock count) of self.repository to the new repository.
 
839
            lock_token = old_repository.lock_write().repository_token
 
840
            self.repository = new_repository
 
841
            if isinstance(self, remote.RemoteBranch):
 
842
                # Remote branches can have a second reference to the old
 
843
                # repository that need to be replaced.
 
844
                if self._real_branch is not None:
 
845
                    self._real_branch.repository = new_repository
 
846
            self.repository.lock_write(token=lock_token)
 
847
            if lock_token is not None:
 
848
                old_repository.leave_lock_in_place()
797
849
            old_repository.unlock()
 
850
            if lock_token is not None:
 
851
                # XXX: self.repository.leave_lock_in_place() before this
 
852
                # function will not be preserved.  Fortunately that doesn't
 
853
                # affect the current default format (2a), and would be a
 
854
                # corner-case anyway.
 
855
                #  - Andrew Bennetts, 2010/06/30
 
856
                self.repository.dont_leave_lock_in_place()
 
857
            old_lock_count = 0
 
858
            while True:
 
859
                try:
 
860
                    old_repository.unlock()
 
861
                except errors.LockNotHeld:
 
862
                    break
 
863
                old_lock_count += 1
 
864
            if old_lock_count == 0:
 
865
                raise AssertionError(
 
866
                    'old_repository should have been locked at least once.')
 
867
            for i in range(old_lock_count-1):
 
868
                self.repository.lock_write()
 
869
            # Fetch from the old repository into the new.
798
870
            old_repository.lock_read()
799
871
            try:
800
 
                # Repositories don't offer an interface to remove fallback
801
 
                # repositories today; take the conceptually simpler option and just
802
 
                # reopen it.  We reopen it starting from the URL so that we
803
 
                # get a separate connection for RemoteRepositories and can
804
 
                # stream from one of them to the other.  This does mean doing
805
 
                # separate SSH connection setup, but unstacking is not a
806
 
                # common operation so it's tolerable.
807
 
                new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
808
 
                new_repository = new_bzrdir.find_repository()
809
 
                self.repository = new_repository
810
 
                if self.repository._fallback_repositories:
811
 
                    raise AssertionError("didn't expect %r to have "
812
 
                        "fallback_repositories"
813
 
                        % (self.repository,))
814
 
                # this is not paired with an unlock because it's just restoring
815
 
                # the previous state; the lock's released when set_stacked_on_url
816
 
                # returns
817
 
                self.repository.lock_write()
818
872
                # XXX: If you unstack a branch while it has a working tree
819
873
                # with a pending merge, the pending-merged revisions will no
820
874
                # longer be present.  You can (probably) revert and remerge.
821
 
                #
822
 
                # XXX: This only fetches up to the tip of the repository; it
823
 
                # doesn't bring across any tags.  That's fairly consistent
824
 
                # with how branch works, but perhaps not ideal.
825
 
                self.repository.fetch(old_repository,
826
 
                    revision_id=self.last_revision(),
827
 
                    find_ghosts=True)
 
875
                try:
 
876
                    tags_to_fetch = set(self.tags.get_reverse_tag_dict())
 
877
                except errors.TagsNotSupported:
 
878
                    tags_to_fetch = set()
 
879
                fetch_spec = _mod_graph.NotInOtherForRevs(self.repository,
 
880
                    old_repository, required_ids=[self.last_revision()],
 
881
                    if_present_ids=tags_to_fetch, find_ghosts=True).execute()
 
882
                self.repository.fetch(old_repository, fetch_spec=fetch_spec)
828
883
            finally:
829
884
                old_repository.unlock()
830
885
        finally:
835
890
 
836
891
        :seealso: Branch._get_tags_bytes.
837
892
        """
838
 
        return _run_with_write_locked_target(self, self._transport.put_bytes,
839
 
            'tags', bytes)
 
893
        return _run_with_write_locked_target(self, self._set_tags_bytes_locked,
 
894
                bytes)
 
895
 
 
896
    def _set_tags_bytes_locked(self, bytes):
 
897
        self._tags_bytes = bytes
 
898
        return self._transport.put_bytes('tags', bytes)
840
899
 
841
900
    def _cache_revision_history(self, rev_history):
842
901
        """Set the cached revision history to rev_history.
869
928
        self._revision_history_cache = None
870
929
        self._revision_id_to_revno_cache = None
871
930
        self._last_revision_info_cache = None
 
931
        self._master_branch_cache = None
872
932
        self._merge_sorted_revisions_cache = None
873
933
        self._partial_revision_history_cache = []
874
934
        self._partial_revision_id_to_revno_cache = {}
 
935
        self._tags_bytes = None
875
936
 
876
937
    def _gen_revision_history(self):
877
938
        """Return sequence of revision hashes on to this branch.
938
999
        else:
939
1000
            return (0, _mod_revision.NULL_REVISION)
940
1001
 
941
 
    @deprecated_method(deprecated_in((1, 6, 0)))
942
 
    def missing_revisions(self, other, stop_revision=None):
943
 
        """Return a list of new revisions that would perfectly fit.
944
 
 
945
 
        If self and other have not diverged, return a list of the revisions
946
 
        present in other, but missing from self.
947
 
        """
948
 
        self_history = self.revision_history()
949
 
        self_len = len(self_history)
950
 
        other_history = other.revision_history()
951
 
        other_len = len(other_history)
952
 
        common_index = min(self_len, other_len) -1
953
 
        if common_index >= 0 and \
954
 
            self_history[common_index] != other_history[common_index]:
955
 
            raise errors.DivergedBranches(self, other)
956
 
 
957
 
        if stop_revision is None:
958
 
            stop_revision = other_len
959
 
        else:
960
 
            if stop_revision > other_len:
961
 
                raise errors.NoSuchRevision(self, stop_revision)
962
 
        return other_history[self_len:stop_revision]
963
 
 
964
 
    @needs_write_lock
965
1002
    def update_revisions(self, other, stop_revision=None, overwrite=False,
966
 
                         graph=None):
 
1003
                         graph=None, fetch_tags=True):
967
1004
        """Pull in new perfect-fit revisions.
968
1005
 
969
1006
        :param other: Another Branch to pull from
972
1009
            to see if it is a proper descendant.
973
1010
        :param graph: A Graph object that can be used to query history
974
1011
            information. This can be None.
 
1012
        :param fetch_tags: Flag that specifies if tags from other should be
 
1013
            fetched too.
975
1014
        :return: None
976
1015
        """
977
1016
        return InterBranch.get(other, self).update_revisions(stop_revision,
978
 
            overwrite, graph)
 
1017
            overwrite, graph, fetch_tags=fetch_tags)
979
1018
 
 
1019
    @deprecated_method(deprecated_in((2, 4, 0)))
980
1020
    def import_last_revision_info(self, source_repo, revno, revid):
981
1021
        """Set the last revision info, importing from another repo if necessary.
982
1022
 
983
 
        This is used by the bound branch code to upload a revision to
984
 
        the master branch first before updating the tip of the local branch.
985
 
 
986
1023
        :param source_repo: Source repository to optionally fetch from
987
1024
        :param revno: Revision number of the new tip
988
1025
        :param revid: Revision id of the new tip
991
1028
            self.repository.fetch(source_repo, revision_id=revid)
992
1029
        self.set_last_revision_info(revno, revid)
993
1030
 
 
1031
    def import_last_revision_info_and_tags(self, source, revno, revid,
 
1032
                                           lossy=False):
 
1033
        """Set the last revision info, importing from another repo if necessary.
 
1034
 
 
1035
        This is used by the bound branch code to upload a revision to
 
1036
        the master branch first before updating the tip of the local branch.
 
1037
        Revisions referenced by source's tags are also transferred.
 
1038
 
 
1039
        :param source: Source branch to optionally fetch from
 
1040
        :param revno: Revision number of the new tip
 
1041
        :param revid: Revision id of the new tip
 
1042
        :param lossy: Whether to discard metadata that can not be
 
1043
            natively represented
 
1044
        :return: Tuple with the new revision number and revision id
 
1045
            (should only be different from the arguments when lossy=True)
 
1046
        """
 
1047
        if not self.repository.has_same_location(source.repository):
 
1048
            try:
 
1049
                tags_to_fetch = set(source.tags.get_reverse_tag_dict())
 
1050
            except errors.TagsNotSupported:
 
1051
                tags_to_fetch = set()
 
1052
            fetch_spec = _mod_graph.NotInOtherForRevs(self.repository,
 
1053
                source.repository, [revid],
 
1054
                if_present_ids=tags_to_fetch).execute()
 
1055
            self.repository.fetch(source.repository, fetch_spec=fetch_spec)
 
1056
        self.set_last_revision_info(revno, revid)
 
1057
        return (revno, revid)
 
1058
 
994
1059
    def revision_id_to_revno(self, revision_id):
995
1060
        """Given a revision id, return its revno"""
996
1061
        if _mod_revision.is_null(revision_id):
1016
1081
            self._extend_partial_history(distance_from_last)
1017
1082
        return self._partial_revision_history_cache[distance_from_last]
1018
1083
 
1019
 
    @needs_write_lock
1020
1084
    def pull(self, source, overwrite=False, stop_revision=None,
1021
1085
             possible_transports=None, *args, **kwargs):
1022
1086
        """Mirror source into this branch.
1218
1282
        return result
1219
1283
 
1220
1284
    @needs_read_lock
1221
 
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None):
 
1285
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None,
 
1286
            repository=None):
1222
1287
        """Create a new line of development from the branch, into to_bzrdir.
1223
1288
 
1224
1289
        to_bzrdir controls the branch format.
1229
1294
        if (repository_policy is not None and
1230
1295
            repository_policy.requires_stacking()):
1231
1296
            to_bzrdir._format.require_stacking(_skip_repo=True)
1232
 
        result = to_bzrdir.create_branch()
 
1297
        result = to_bzrdir.create_branch(repository=repository)
1233
1298
        result.lock_write()
1234
1299
        try:
1235
1300
            if repository_policy is not None:
1265
1330
                revno = 1
1266
1331
        destination.set_last_revision_info(revno, revision_id)
1267
1332
 
1268
 
    @needs_read_lock
1269
1333
    def copy_content_into(self, destination, revision_id=None):
1270
1334
        """Copy the content of self into destination.
1271
1335
 
1272
1336
        revision_id: if not None, the revision history in the new branch will
1273
1337
                     be truncated to end with revision_id.
1274
1338
        """
1275
 
        self.update_references(destination)
1276
 
        self._synchronize_history(destination, revision_id)
1277
 
        try:
1278
 
            parent = self.get_parent()
1279
 
        except errors.InaccessibleParent, e:
1280
 
            mutter('parent was not accessible to copy: %s', e)
1281
 
        else:
1282
 
            if parent:
1283
 
                destination.set_parent(parent)
1284
 
        if self._push_should_merge_tags():
1285
 
            self.tags.merge_to(destination.tags)
 
1339
        return InterBranch.get(self, destination).copy_content_into(
 
1340
            revision_id=revision_id)
1286
1341
 
1287
1342
    def update_references(self, target):
1288
1343
        if not getattr(self._format, 'supports_reference_locations', False):
1333
1388
        """Return the most suitable metadir for a checkout of this branch.
1334
1389
        Weaves are used if this branch's repository uses weaves.
1335
1390
        """
1336
 
        if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
1337
 
            from bzrlib.repofmt import weaverepo
1338
 
            format = bzrdir.BzrDirMetaFormat1()
1339
 
            format.repository_format = weaverepo.RepositoryFormat7()
1340
 
        else:
1341
 
            format = self.repository.bzrdir.checkout_metadir()
1342
 
            format.set_branch_format(self._format)
 
1391
        format = self.repository.bzrdir.checkout_metadir()
 
1392
        format.set_branch_format(self._format)
1343
1393
        return format
1344
1394
 
1345
1395
    def create_clone_on_transport(self, to_transport, revision_id=None,
1346
 
        stacked_on=None, create_prefix=False, use_existing_dir=False):
 
1396
        stacked_on=None, create_prefix=False, use_existing_dir=False,
 
1397
        no_tree=None):
1347
1398
        """Create a clone of this branch and its bzrdir.
1348
1399
 
1349
1400
        :param to_transport: The transport to clone onto.
1362
1413
            revision_id = self.last_revision()
1363
1414
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1364
1415
            revision_id=revision_id, stacked_on=stacked_on,
1365
 
            create_prefix=create_prefix, use_existing_dir=use_existing_dir)
 
1416
            create_prefix=create_prefix, use_existing_dir=use_existing_dir,
 
1417
            no_tree=no_tree)
1366
1418
        return dir_to.open_branch()
1367
1419
 
1368
1420
    def create_checkout(self, to_location, revision_id=None,
1483
1535
        else:
1484
1536
            raise AssertionError("invalid heads: %r" % (heads,))
1485
1537
 
1486
 
 
1487
 
class BranchFormat(object):
 
1538
    def heads_to_fetch(self):
 
1539
        """Return the heads that must and that should be fetched to copy this
 
1540
        branch into another repo.
 
1541
 
 
1542
        :returns: a 2-tuple of (must_fetch, if_present_fetch).  must_fetch is a
 
1543
            set of heads that must be fetched.  if_present_fetch is a set of
 
1544
            heads that must be fetched if present, but no error is necessary if
 
1545
            they are not present.
 
1546
        """
 
1547
        # For bzr native formats must_fetch is just the tip, and if_present_fetch
 
1548
        # are the tags.
 
1549
        must_fetch = set([self.last_revision()])
 
1550
        try:
 
1551
            if_present_fetch = set(self.tags.get_reverse_tag_dict())
 
1552
        except errors.TagsNotSupported:
 
1553
            if_present_fetch = set()
 
1554
        must_fetch.discard(_mod_revision.NULL_REVISION)
 
1555
        if_present_fetch.discard(_mod_revision.NULL_REVISION)
 
1556
        return must_fetch, if_present_fetch
 
1557
 
 
1558
 
 
1559
class BranchFormat(controldir.ControlComponentFormat):
1488
1560
    """An encapsulation of the initialization and open routines for a format.
1489
1561
 
1490
1562
    Formats provide three things:
1493
1565
     * an open routine.
1494
1566
 
1495
1567
    Formats are placed in an dict by their format string for reference
1496
 
    during branch opening. Its not required that these be instances, they
 
1568
    during branch opening. It's not required that these be instances, they
1497
1569
    can be classes themselves with class methods - it simply depends on
1498
1570
    whether state is needed for a given format or not.
1499
1571
 
1502
1574
    object will be created every time regardless.
1503
1575
    """
1504
1576
 
1505
 
    _default_format = None
1506
 
    """The default format used for new branches."""
1507
 
 
1508
 
    _formats = {}
1509
 
    """The known formats."""
1510
 
 
1511
1577
    can_set_append_revisions_only = True
1512
1578
 
1513
1579
    def __eq__(self, other):
1522
1588
        try:
1523
1589
            transport = a_bzrdir.get_branch_transport(None, name=name)
1524
1590
            format_string = transport.get_bytes("format")
1525
 
            return klass._formats[format_string]
 
1591
            return format_registry.get(format_string)
1526
1592
        except errors.NoSuchFile:
1527
1593
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1528
1594
        except KeyError:
1529
1595
            raise errors.UnknownFormatError(format=format_string, kind='branch')
1530
1596
 
1531
1597
    @classmethod
 
1598
    @deprecated_method(deprecated_in((2, 4, 0)))
1532
1599
    def get_default_format(klass):
1533
1600
        """Return the current default format."""
1534
 
        return klass._default_format
 
1601
        return format_registry.get_default()
 
1602
 
 
1603
    @classmethod
 
1604
    @deprecated_method(deprecated_in((2, 4, 0)))
 
1605
    def get_formats(klass):
 
1606
        """Get all the known formats.
 
1607
 
 
1608
        Warning: This triggers a load of all lazy registered formats: do not
 
1609
        use except when that is desireed.
 
1610
        """
 
1611
        return format_registry._get_all()
1535
1612
 
1536
1613
    def get_reference(self, a_bzrdir, name=None):
1537
1614
        """Get the target reference of the branch in a_bzrdir.
1576
1653
        for hook in hooks:
1577
1654
            hook(params)
1578
1655
 
1579
 
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
1580
 
                           lock_type='metadir', set_format=True):
1581
 
        """Initialize a branch in a bzrdir, with specified files
1582
 
 
1583
 
        :param a_bzrdir: The bzrdir to initialize the branch in
1584
 
        :param utf8_files: The files to create as a list of
1585
 
            (filename, content) tuples
1586
 
        :param name: Name of colocated branch to create, if any
1587
 
        :param set_format: If True, set the format with
1588
 
            self.get_format_string.  (BzrBranch4 has its format set
1589
 
            elsewhere)
1590
 
        :return: a branch in this format
1591
 
        """
1592
 
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
1593
 
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
1594
 
        lock_map = {
1595
 
            'metadir': ('lock', lockdir.LockDir),
1596
 
            'branch4': ('branch-lock', lockable_files.TransportLock),
1597
 
        }
1598
 
        lock_name, lock_class = lock_map[lock_type]
1599
 
        control_files = lockable_files.LockableFiles(branch_transport,
1600
 
            lock_name, lock_class)
1601
 
        control_files.create_lock()
1602
 
        try:
1603
 
            control_files.lock_write()
1604
 
        except errors.LockContention:
1605
 
            if lock_type != 'branch4':
1606
 
                raise
1607
 
            lock_taken = False
1608
 
        else:
1609
 
            lock_taken = True
1610
 
        if set_format:
1611
 
            utf8_files += [('format', self.get_format_string())]
1612
 
        try:
1613
 
            for (filename, content) in utf8_files:
1614
 
                branch_transport.put_bytes(
1615
 
                    filename, content,
1616
 
                    mode=a_bzrdir._get_file_mode())
1617
 
        finally:
1618
 
            if lock_taken:
1619
 
                control_files.unlock()
1620
 
        branch = self.open(a_bzrdir, name, _found=True)
1621
 
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
1622
 
        return branch
1623
 
 
1624
 
    def initialize(self, a_bzrdir, name=None):
 
1656
    def initialize(self, a_bzrdir, name=None, repository=None):
1625
1657
        """Create a branch of this format in a_bzrdir.
1626
1658
        
1627
1659
        :param name: Name of the colocated branch to create.
1661
1693
        """
1662
1694
        raise NotImplementedError(self.network_name)
1663
1695
 
1664
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1696
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
 
1697
            found_repository=None):
1665
1698
        """Return the branch object for a_bzrdir
1666
1699
 
1667
1700
        :param a_bzrdir: A BzrDir that contains a branch.
1674
1707
        raise NotImplementedError(self.open)
1675
1708
 
1676
1709
    @classmethod
 
1710
    @deprecated_method(deprecated_in((2, 4, 0)))
1677
1711
    def register_format(klass, format):
1678
 
        """Register a metadir format."""
1679
 
        klass._formats[format.get_format_string()] = format
1680
 
        # Metadir formats have a network name of their format string, and get
1681
 
        # registered as class factories.
1682
 
        network_format_registry.register(format.get_format_string(), format.__class__)
 
1712
        """Register a metadir format.
 
1713
 
 
1714
        See MetaDirBranchFormatFactory for the ability to register a format
 
1715
        without loading the code the format needs until it is actually used.
 
1716
        """
 
1717
        format_registry.register(format)
1683
1718
 
1684
1719
    @classmethod
 
1720
    @deprecated_method(deprecated_in((2, 4, 0)))
1685
1721
    def set_default_format(klass, format):
1686
 
        klass._default_format = format
 
1722
        format_registry.set_default(format)
1687
1723
 
1688
1724
    def supports_set_append_revisions_only(self):
1689
1725
        """True if this format supports set_append_revisions_only."""
1693
1729
        """True if this format records a stacked-on branch."""
1694
1730
        return False
1695
1731
 
 
1732
    def supports_leaving_lock(self):
 
1733
        """True if this format supports leaving locks in place."""
 
1734
        return False # by default
 
1735
 
1696
1736
    @classmethod
 
1737
    @deprecated_method(deprecated_in((2, 4, 0)))
1697
1738
    def unregister_format(klass, format):
1698
 
        del klass._formats[format.get_format_string()]
 
1739
        format_registry.remove(format)
1699
1740
 
1700
1741
    def __str__(self):
1701
1742
        return self.get_format_description().rstrip()
1705
1746
        return False  # by default
1706
1747
 
1707
1748
 
 
1749
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
 
1750
    """A factory for a BranchFormat object, permitting simple lazy registration.
 
1751
    
 
1752
    While none of the built in BranchFormats are lazy registered yet,
 
1753
    bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
 
1754
    use it, and the bzr-loom plugin uses it as well (see
 
1755
    bzrlib.plugins.loom.formats).
 
1756
    """
 
1757
 
 
1758
    def __init__(self, format_string, module_name, member_name):
 
1759
        """Create a MetaDirBranchFormatFactory.
 
1760
 
 
1761
        :param format_string: The format string the format has.
 
1762
        :param module_name: Module to load the format class from.
 
1763
        :param member_name: Attribute name within the module for the format class.
 
1764
        """
 
1765
        registry._LazyObjectGetter.__init__(self, module_name, member_name)
 
1766
        self._format_string = format_string
 
1767
        
 
1768
    def get_format_string(self):
 
1769
        """See BranchFormat.get_format_string."""
 
1770
        return self._format_string
 
1771
 
 
1772
    def __call__(self):
 
1773
        """Used for network_format_registry support."""
 
1774
        return self.get_obj()()
 
1775
 
 
1776
 
1708
1777
class BranchHooks(Hooks):
1709
1778
    """A dictionary mapping hook name to a list of callables for branch hooks.
1710
1779
 
1718
1787
        These are all empty initially, because by default nothing should get
1719
1788
        notified.
1720
1789
        """
1721
 
        Hooks.__init__(self)
1722
 
        self.create_hook(HookPoint('set_rh',
 
1790
        Hooks.__init__(self, "bzrlib.branch", "Branch.hooks")
 
1791
        self.add_hook('set_rh',
1723
1792
            "Invoked whenever the revision history has been set via "
1724
1793
            "set_revision_history. The api signature is (branch, "
1725
1794
            "revision_history), and the branch will be write-locked. "
1726
1795
            "The set_rh hook can be expensive for bzr to trigger, a better "
1727
 
            "hook to use is Branch.post_change_branch_tip.", (0, 15), None))
1728
 
        self.create_hook(HookPoint('open',
 
1796
            "hook to use is Branch.post_change_branch_tip.", (0, 15))
 
1797
        self.add_hook('open',
1729
1798
            "Called with the Branch object that has been opened after a "
1730
 
            "branch is opened.", (1, 8), None))
1731
 
        self.create_hook(HookPoint('post_push',
 
1799
            "branch is opened.", (1, 8))
 
1800
        self.add_hook('post_push',
1732
1801
            "Called after a push operation completes. post_push is called "
1733
1802
            "with a bzrlib.branch.BranchPushResult object and only runs in the "
1734
 
            "bzr client.", (0, 15), None))
1735
 
        self.create_hook(HookPoint('post_pull',
 
1803
            "bzr client.", (0, 15))
 
1804
        self.add_hook('post_pull',
1736
1805
            "Called after a pull operation completes. post_pull is called "
1737
1806
            "with a bzrlib.branch.PullResult object and only runs in the "
1738
 
            "bzr client.", (0, 15), None))
1739
 
        self.create_hook(HookPoint('pre_commit',
1740
 
            "Called after a commit is calculated but before it is is "
 
1807
            "bzr client.", (0, 15))
 
1808
        self.add_hook('pre_commit',
 
1809
            "Called after a commit is calculated but before it is "
1741
1810
            "completed. pre_commit is called with (local, master, old_revno, "
1742
1811
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
1743
1812
            "). old_revid is NULL_REVISION for the first commit to a branch, "
1745
1814
            "basis revision. hooks MUST NOT modify this delta. "
1746
1815
            " future_tree is an in-memory tree obtained from "
1747
1816
            "CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1748
 
            "tree.", (0,91), None))
1749
 
        self.create_hook(HookPoint('post_commit',
 
1817
            "tree.", (0,91))
 
1818
        self.add_hook('post_commit',
1750
1819
            "Called in the bzr client after a commit has completed. "
1751
1820
            "post_commit is called with (local, master, old_revno, old_revid, "
1752
1821
            "new_revno, new_revid). old_revid is NULL_REVISION for the first "
1753
 
            "commit to a branch.", (0, 15), None))
1754
 
        self.create_hook(HookPoint('post_uncommit',
 
1822
            "commit to a branch.", (0, 15))
 
1823
        self.add_hook('post_uncommit',
1755
1824
            "Called in the bzr client after an uncommit completes. "
1756
1825
            "post_uncommit is called with (local, master, old_revno, "
1757
1826
            "old_revid, new_revno, new_revid) where local is the local branch "
1758
1827
            "or None, master is the target branch, and an empty branch "
1759
 
            "receives new_revno of 0, new_revid of None.", (0, 15), None))
1760
 
        self.create_hook(HookPoint('pre_change_branch_tip',
 
1828
            "receives new_revno of 0, new_revid of None.", (0, 15))
 
1829
        self.add_hook('pre_change_branch_tip',
1761
1830
            "Called in bzr client and server before a change to the tip of a "
1762
1831
            "branch is made. pre_change_branch_tip is called with a "
1763
1832
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1764
 
            "commit, uncommit will all trigger this hook.", (1, 6), None))
1765
 
        self.create_hook(HookPoint('post_change_branch_tip',
 
1833
            "commit, uncommit will all trigger this hook.", (1, 6))
 
1834
        self.add_hook('post_change_branch_tip',
1766
1835
            "Called in bzr client and server after a change to the tip of a "
1767
1836
            "branch is made. post_change_branch_tip is called with a "
1768
1837
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1769
 
            "commit, uncommit will all trigger this hook.", (1, 4), None))
1770
 
        self.create_hook(HookPoint('transform_fallback_location',
 
1838
            "commit, uncommit will all trigger this hook.", (1, 4))
 
1839
        self.add_hook('transform_fallback_location',
1771
1840
            "Called when a stacked branch is activating its fallback "
1772
1841
            "locations. transform_fallback_location is called with (branch, "
1773
1842
            "url), and should return a new url. Returning the same url "
1778
1847
            "fallback locations have not been activated. When there are "
1779
1848
            "multiple hooks installed for transform_fallback_location, "
1780
1849
            "all are called with the url returned from the previous hook."
1781
 
            "The order is however undefined.", (1, 9), None))
1782
 
        self.create_hook(HookPoint('automatic_tag_name',
1783
 
            "Called to determine an automatic tag name for a revision."
 
1850
            "The order is however undefined.", (1, 9))
 
1851
        self.add_hook('automatic_tag_name',
 
1852
            "Called to determine an automatic tag name for a revision. "
1784
1853
            "automatic_tag_name is called with (branch, revision_id) and "
1785
1854
            "should return a tag name or None if no tag name could be "
1786
1855
            "determined. The first non-None tag name returned will be used.",
1787
 
            (2, 2), None))
1788
 
        self.create_hook(HookPoint('post_branch_init',
 
1856
            (2, 2))
 
1857
        self.add_hook('post_branch_init',
1789
1858
            "Called after new branch initialization completes. "
1790
1859
            "post_branch_init is called with a "
1791
1860
            "bzrlib.branch.BranchInitHookParams. "
1792
1861
            "Note that init, branch and checkout (both heavyweight and "
1793
 
            "lightweight) will all trigger this hook.", (2, 2), None))
1794
 
        self.create_hook(HookPoint('post_switch',
 
1862
            "lightweight) will all trigger this hook.", (2, 2))
 
1863
        self.add_hook('post_switch',
1795
1864
            "Called after a checkout switches branch. "
1796
1865
            "post_switch is called with a "
1797
 
            "bzrlib.branch.SwitchHookParams.", (2, 2), None))
 
1866
            "bzrlib.branch.SwitchHookParams.", (2, 2))
1798
1867
 
1799
1868
 
1800
1869
 
1877
1946
        return self.__dict__ == other.__dict__
1878
1947
 
1879
1948
    def __repr__(self):
1880
 
        if self.branch:
1881
 
            return "<%s of %s>" % (self.__class__.__name__, self.branch)
1882
 
        else:
1883
 
            return "<%s of format:%s bzrdir:%s>" % (
1884
 
                self.__class__.__name__, self.branch,
1885
 
                self.format, self.bzrdir)
 
1949
        return "<%s of %s>" % (self.__class__.__name__, self.branch)
1886
1950
 
1887
1951
 
1888
1952
class SwitchHookParams(object):
1918
1982
            self.revision_id)
1919
1983
 
1920
1984
 
1921
 
class BzrBranchFormat4(BranchFormat):
1922
 
    """Bzr branch format 4.
1923
 
 
1924
 
    This format has:
1925
 
     - a revision-history file.
1926
 
     - a branch-lock lock file [ to be shared with the bzrdir ]
1927
 
    """
1928
 
 
1929
 
    def get_format_description(self):
1930
 
        """See BranchFormat.get_format_description()."""
1931
 
        return "Branch format 4"
1932
 
 
1933
 
    def initialize(self, a_bzrdir, name=None):
1934
 
        """Create a branch of this format in a_bzrdir."""
1935
 
        utf8_files = [('revision-history', ''),
1936
 
                      ('branch-name', ''),
1937
 
                      ]
1938
 
        return self._initialize_helper(a_bzrdir, utf8_files, name=name,
1939
 
                                       lock_type='branch4', set_format=False)
1940
 
 
1941
 
    def __init__(self):
1942
 
        super(BzrBranchFormat4, self).__init__()
1943
 
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
1944
 
 
1945
 
    def network_name(self):
1946
 
        """The network name for this format is the control dirs disk label."""
1947
 
        return self._matchingbzrdir.get_format_string()
1948
 
 
1949
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
1950
 
        """See BranchFormat.open()."""
1951
 
        if not _found:
1952
 
            # we are being called directly and must probe.
1953
 
            raise NotImplementedError
1954
 
        return BzrBranch(_format=self,
1955
 
                         _control_files=a_bzrdir._control_files,
1956
 
                         a_bzrdir=a_bzrdir,
1957
 
                         name=name,
1958
 
                         _repository=a_bzrdir.open_repository())
1959
 
 
1960
 
    def __str__(self):
1961
 
        return "Bazaar-NG branch format 4"
1962
 
 
1963
 
 
1964
1985
class BranchFormatMetadir(BranchFormat):
1965
1986
    """Common logic for meta-dir based branch formats."""
1966
1987
 
1968
1989
        """What class to instantiate on open calls."""
1969
1990
        raise NotImplementedError(self._branch_class)
1970
1991
 
 
1992
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
 
1993
                           repository=None):
 
1994
        """Initialize a branch in a bzrdir, with specified files
 
1995
 
 
1996
        :param a_bzrdir: The bzrdir to initialize the branch in
 
1997
        :param utf8_files: The files to create as a list of
 
1998
            (filename, content) tuples
 
1999
        :param name: Name of colocated branch to create, if any
 
2000
        :return: a branch in this format
 
2001
        """
 
2002
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
 
2003
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
2004
        control_files = lockable_files.LockableFiles(branch_transport,
 
2005
            'lock', lockdir.LockDir)
 
2006
        control_files.create_lock()
 
2007
        control_files.lock_write()
 
2008
        try:
 
2009
            utf8_files += [('format', self.get_format_string())]
 
2010
            for (filename, content) in utf8_files:
 
2011
                branch_transport.put_bytes(
 
2012
                    filename, content,
 
2013
                    mode=a_bzrdir._get_file_mode())
 
2014
        finally:
 
2015
            control_files.unlock()
 
2016
        branch = self.open(a_bzrdir, name, _found=True,
 
2017
                found_repository=repository)
 
2018
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
 
2019
        return branch
 
2020
 
1971
2021
    def network_name(self):
1972
2022
        """A simple byte string uniquely identifying this format for RPC calls.
1973
2023
 
1975
2025
        """
1976
2026
        return self.get_format_string()
1977
2027
 
1978
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
2028
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
 
2029
            found_repository=None):
1979
2030
        """See BranchFormat.open()."""
1980
2031
        if not _found:
1981
2032
            format = BranchFormat.find_format(a_bzrdir, name=name)
1986
2037
        try:
1987
2038
            control_files = lockable_files.LockableFiles(transport, 'lock',
1988
2039
                                                         lockdir.LockDir)
 
2040
            if found_repository is None:
 
2041
                found_repository = a_bzrdir.find_repository()
1989
2042
            return self._branch_class()(_format=self,
1990
2043
                              _control_files=control_files,
1991
2044
                              name=name,
1992
2045
                              a_bzrdir=a_bzrdir,
1993
 
                              _repository=a_bzrdir.find_repository(),
 
2046
                              _repository=found_repository,
1994
2047
                              ignore_fallbacks=ignore_fallbacks)
1995
2048
        except errors.NoSuchFile:
1996
2049
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
2003
2056
    def supports_tags(self):
2004
2057
        return True
2005
2058
 
 
2059
    def supports_leaving_lock(self):
 
2060
        return True
 
2061
 
2006
2062
 
2007
2063
class BzrBranchFormat5(BranchFormatMetadir):
2008
2064
    """Bzr branch format 5.
2028
2084
        """See BranchFormat.get_format_description()."""
2029
2085
        return "Branch format 5"
2030
2086
 
2031
 
    def initialize(self, a_bzrdir, name=None):
 
2087
    def initialize(self, a_bzrdir, name=None, repository=None):
2032
2088
        """Create a branch of this format in a_bzrdir."""
2033
2089
        utf8_files = [('revision-history', ''),
2034
2090
                      ('branch-name', ''),
2035
2091
                      ]
2036
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2092
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2037
2093
 
2038
2094
    def supports_tags(self):
2039
2095
        return False
2061
2117
        """See BranchFormat.get_format_description()."""
2062
2118
        return "Branch format 6"
2063
2119
 
2064
 
    def initialize(self, a_bzrdir, name=None):
 
2120
    def initialize(self, a_bzrdir, name=None, repository=None):
2065
2121
        """Create a branch of this format in a_bzrdir."""
2066
2122
        utf8_files = [('last-revision', '0 null:\n'),
2067
2123
                      ('branch.conf', ''),
2068
2124
                      ('tags', ''),
2069
2125
                      ]
2070
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2126
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2071
2127
 
2072
2128
    def make_tags(self, branch):
2073
2129
        """See bzrlib.branch.BranchFormat.make_tags()."""
2091
2147
        """See BranchFormat.get_format_description()."""
2092
2148
        return "Branch format 8"
2093
2149
 
2094
 
    def initialize(self, a_bzrdir, name=None):
 
2150
    def initialize(self, a_bzrdir, name=None, repository=None):
2095
2151
        """Create a branch of this format in a_bzrdir."""
2096
2152
        utf8_files = [('last-revision', '0 null:\n'),
2097
2153
                      ('branch.conf', ''),
2098
2154
                      ('tags', ''),
2099
2155
                      ('references', '')
2100
2156
                      ]
2101
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
2102
 
 
2103
 
    def __init__(self):
2104
 
        super(BzrBranchFormat8, self).__init__()
2105
 
        self._matchingbzrdir.repository_format = \
2106
 
            RepositoryFormatKnitPack5RichRoot()
 
2157
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2107
2158
 
2108
2159
    def make_tags(self, branch):
2109
2160
        """See bzrlib.branch.BranchFormat.make_tags()."""
2118
2169
    supports_reference_locations = True
2119
2170
 
2120
2171
 
2121
 
class BzrBranchFormat7(BzrBranchFormat8):
 
2172
class BzrBranchFormat7(BranchFormatMetadir):
2122
2173
    """Branch format with last-revision, tags, and a stacked location pointer.
2123
2174
 
2124
2175
    The stacked location pointer is passed down to the repository and requires
2127
2178
    This format was introduced in bzr 1.6.
2128
2179
    """
2129
2180
 
2130
 
    def initialize(self, a_bzrdir, name=None):
 
2181
    def initialize(self, a_bzrdir, name=None, repository=None):
2131
2182
        """Create a branch of this format in a_bzrdir."""
2132
2183
        utf8_files = [('last-revision', '0 null:\n'),
2133
2184
                      ('branch.conf', ''),
2134
2185
                      ('tags', ''),
2135
2186
                      ]
2136
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2187
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2137
2188
 
2138
2189
    def _branch_class(self):
2139
2190
        return BzrBranch7
2149
2200
    def supports_set_append_revisions_only(self):
2150
2201
        return True
2151
2202
 
 
2203
    def supports_stacking(self):
 
2204
        return True
 
2205
 
 
2206
    def make_tags(self, branch):
 
2207
        """See bzrlib.branch.BranchFormat.make_tags()."""
 
2208
        return BasicTags(branch)
 
2209
 
2152
2210
    supports_reference_locations = False
2153
2211
 
2154
2212
 
2181
2239
        transport = a_bzrdir.get_branch_transport(None, name=name)
2182
2240
        location = transport.put_bytes('location', to_branch.base)
2183
2241
 
2184
 
    def initialize(self, a_bzrdir, name=None, target_branch=None):
 
2242
    def initialize(self, a_bzrdir, name=None, target_branch=None,
 
2243
            repository=None):
2185
2244
        """Create a branch of this format in a_bzrdir."""
2186
2245
        if target_branch is None:
2187
2246
            # this format does not implement branch itself, thus the implicit
2215
2274
        return clone
2216
2275
 
2217
2276
    def open(self, a_bzrdir, name=None, _found=False, location=None,
2218
 
             possible_transports=None, ignore_fallbacks=False):
 
2277
             possible_transports=None, ignore_fallbacks=False,
 
2278
             found_repository=None):
2219
2279
        """Return the branch that the branch reference in a_bzrdir points at.
2220
2280
 
2221
2281
        :param a_bzrdir: A BzrDir that contains a branch.
2252
2312
        return result
2253
2313
 
2254
2314
 
 
2315
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
 
2316
    """Branch format registry."""
 
2317
 
 
2318
    def __init__(self, other_registry=None):
 
2319
        super(BranchFormatRegistry, self).__init__(other_registry)
 
2320
        self._default_format = None
 
2321
 
 
2322
    def set_default(self, format):
 
2323
        self._default_format = format
 
2324
 
 
2325
    def get_default(self):
 
2326
        return self._default_format
 
2327
 
 
2328
 
2255
2329
network_format_registry = registry.FormatRegistry()
2256
2330
"""Registry of formats indexed by their network name.
2257
2331
 
2260
2334
BranchFormat.network_name() for more detail.
2261
2335
"""
2262
2336
 
 
2337
format_registry = BranchFormatRegistry(network_format_registry)
 
2338
 
2263
2339
 
2264
2340
# formats which have no format string are not discoverable
2265
2341
# and not independently creatable, so are not registered.
2267
2343
__format6 = BzrBranchFormat6()
2268
2344
__format7 = BzrBranchFormat7()
2269
2345
__format8 = BzrBranchFormat8()
2270
 
BranchFormat.register_format(__format5)
2271
 
BranchFormat.register_format(BranchReferenceFormat())
2272
 
BranchFormat.register_format(__format6)
2273
 
BranchFormat.register_format(__format7)
2274
 
BranchFormat.register_format(__format8)
2275
 
BranchFormat.set_default_format(__format7)
2276
 
_legacy_formats = [BzrBranchFormat4(),
2277
 
    ]
2278
 
network_format_registry.register(
2279
 
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
 
2346
format_registry.register(__format5)
 
2347
format_registry.register(BranchReferenceFormat())
 
2348
format_registry.register(__format6)
 
2349
format_registry.register(__format7)
 
2350
format_registry.register(__format8)
 
2351
format_registry.set_default(__format7)
2280
2352
 
2281
2353
 
2282
2354
class BranchWriteLockResult(LogicalLockResult):
2439
2511
            'revision-history', '\n'.join(history),
2440
2512
            mode=self.bzrdir._get_file_mode())
2441
2513
 
2442
 
    @needs_write_lock
 
2514
    @deprecated_method(deprecated_in((2, 4, 0)))
2443
2515
    def set_revision_history(self, rev_history):
2444
2516
        """See Branch.set_revision_history."""
 
2517
        self._set_revision_history(rev_history)
 
2518
 
 
2519
    @needs_write_lock
 
2520
    def _set_revision_history(self, rev_history):
2445
2521
        if 'evil' in debug.debug_flags:
2446
2522
            mutter_callsite(3, "set_revision_history scales with history.")
2447
2523
        check_not_reserved_id = _mod_revision.check_not_reserved_id
2491
2567
            except ValueError:
2492
2568
                rev = self.repository.get_revision(revision_id)
2493
2569
                new_history = rev.get_history(self.repository)[1:]
2494
 
        destination.set_revision_history(new_history)
 
2570
        destination._set_revision_history(new_history)
2495
2571
 
2496
2572
    @needs_write_lock
2497
2573
    def set_last_revision_info(self, revno, revision_id):
2505
2581
        configured to check constraints on history, in which case this may not
2506
2582
        be permitted.
2507
2583
        """
2508
 
        revision_id = _mod_revision.ensure_null(revision_id)
 
2584
        if not revision_id or not isinstance(revision_id, basestring):
 
2585
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2509
2586
        # this old format stores the full history, but this api doesn't
2510
2587
        # provide it, so we must generate, and might as well check it's
2511
2588
        # correct
2512
2589
        history = self._lefthand_history(revision_id)
2513
2590
        if len(history) != revno:
2514
2591
            raise AssertionError('%d != %d' % (len(history), revno))
2515
 
        self.set_revision_history(history)
 
2592
        self._set_revision_history(history)
2516
2593
 
2517
2594
    def _gen_revision_history(self):
2518
2595
        history = self._transport.get_bytes('revision-history').split('\n')
2532
2609
        :param other_branch: The other branch that DivergedBranches should
2533
2610
            raise with respect to.
2534
2611
        """
2535
 
        self.set_revision_history(self._lefthand_history(revision_id,
 
2612
        self._set_revision_history(self._lefthand_history(revision_id,
2536
2613
            last_rev, other_branch))
2537
2614
 
2538
2615
    def basis_tree(self):
2558
2635
        result.target_branch = target
2559
2636
        result.old_revno, result.old_revid = target.last_revision_info()
2560
2637
        self.update_references(target)
2561
 
        if result.old_revid != self.last_revision():
 
2638
        if result.old_revid != stop_revision:
2562
2639
            # We assume that during 'push' this repository is closer than
2563
2640
            # the target.
2564
2641
            graph = self.repository.get_graph(target.repository)
2565
2642
            target.update_revisions(self, stop_revision,
2566
2643
                overwrite=overwrite, graph=graph)
2567
2644
        if self._push_should_merge_tags():
2568
 
            result.tag_conflicts = self.tags.merge_to(target.tags,
2569
 
                overwrite)
 
2645
            result.tag_conflicts = self.tags.merge_to(target.tags, overwrite)
2570
2646
        result.new_revno, result.new_revid = target.last_revision_info()
2571
2647
        return result
2572
2648
 
2604
2680
        """Return the branch we are bound to.
2605
2681
 
2606
2682
        :return: Either a Branch, or None
2607
 
 
2608
 
        This could memoise the branch, but if thats done
2609
 
        it must be revalidated on each new lock.
2610
 
        So for now we just don't memoise it.
2611
 
        # RBC 20060304 review this decision.
2612
2683
        """
 
2684
        if self._master_branch_cache is None:
 
2685
            self._master_branch_cache = self._get_master_branch(
 
2686
                possible_transports)
 
2687
        return self._master_branch_cache
 
2688
 
 
2689
    def _get_master_branch(self, possible_transports):
2613
2690
        bound_loc = self.get_bound_location()
2614
2691
        if not bound_loc:
2615
2692
            return None
2626
2703
 
2627
2704
        :param location: URL to the target branch
2628
2705
        """
 
2706
        self._master_branch_cache = None
2629
2707
        if location:
2630
2708
            self._transport.put_bytes('bound', location+'\n',
2631
2709
                mode=self.bzrdir._get_file_mode())
2740
2818
 
2741
2819
    @needs_write_lock
2742
2820
    def set_last_revision_info(self, revno, revision_id):
2743
 
        revision_id = _mod_revision.ensure_null(revision_id)
 
2821
        if not revision_id or not isinstance(revision_id, basestring):
 
2822
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2744
2823
        old_revno, old_revid = self.last_revision_info()
2745
2824
        if self._get_append_revisions_only():
2746
2825
            self._check_history_violation(revision_id)
2883
2962
 
2884
2963
    def set_bound_location(self, location):
2885
2964
        """See Branch.set_push_location."""
 
2965
        self._master_branch_cache = None
2886
2966
        result = None
2887
2967
        config = self.get_config()
2888
2968
        if location is None:
2965
3045
        try:
2966
3046
            index = self._partial_revision_history_cache.index(revision_id)
2967
3047
        except ValueError:
2968
 
            self._extend_partial_history(stop_revision=revision_id)
 
3048
            try:
 
3049
                self._extend_partial_history(stop_revision=revision_id)
 
3050
            except errors.RevisionNotPresent, e:
 
3051
                raise errors.GhostRevisionsHaveNoRevno(revision_id, e.revision_id)
2969
3052
            index = len(self._partial_revision_history_cache) - 1
2970
3053
            if self._partial_revision_history_cache[index] != revision_id:
2971
3054
                raise errors.NoSuchRevision(self, revision_id)
3026
3109
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
3027
3110
    """
3028
3111
 
 
3112
    @deprecated_method(deprecated_in((2, 3, 0)))
3029
3113
    def __int__(self):
3030
 
        # DEPRECATED: pull used to return the change in revno
 
3114
        """Return the relative change in revno.
 
3115
 
 
3116
        :deprecated: Use `new_revno` and `old_revno` instead.
 
3117
        """
3031
3118
        return self.new_revno - self.old_revno
3032
3119
 
3033
3120
    def report(self, to_file):
3058
3145
        target, otherwise it will be None.
3059
3146
    """
3060
3147
 
 
3148
    @deprecated_method(deprecated_in((2, 3, 0)))
3061
3149
    def __int__(self):
3062
 
        # DEPRECATED: push used to return the change in revno
 
3150
        """Return the relative change in revno.
 
3151
 
 
3152
        :deprecated: Use `new_revno` and `old_revno` instead.
 
3153
        """
3063
3154
        return self.new_revno - self.old_revno
3064
3155
 
3065
3156
    def report(self, to_file):
3188
3279
    _optimisers = []
3189
3280
    """The available optimised InterBranch types."""
3190
3281
 
3191
 
    @staticmethod
3192
 
    def _get_branch_formats_to_test():
3193
 
        """Return a tuple with the Branch formats to use when testing."""
3194
 
        raise NotImplementedError(InterBranch._get_branch_formats_to_test)
 
3282
    @classmethod
 
3283
    def _get_branch_formats_to_test(klass):
 
3284
        """Return an iterable of format tuples for testing.
 
3285
        
 
3286
        :return: An iterable of (from_format, to_format) to use when testing
 
3287
            this InterBranch class. Each InterBranch class should define this
 
3288
            method itself.
 
3289
        """
 
3290
        raise NotImplementedError(klass._get_branch_formats_to_test)
3195
3291
 
 
3292
    @needs_write_lock
3196
3293
    def pull(self, overwrite=False, stop_revision=None,
3197
3294
             possible_transports=None, local=False):
3198
3295
        """Mirror source into target branch.
3203
3300
        """
3204
3301
        raise NotImplementedError(self.pull)
3205
3302
 
 
3303
    @needs_write_lock
3206
3304
    def update_revisions(self, stop_revision=None, overwrite=False,
3207
 
                         graph=None):
 
3305
                         graph=None, fetch_tags=True):
3208
3306
        """Pull in new perfect-fit revisions.
3209
3307
 
3210
3308
        :param stop_revision: Updated until the given revision
3212
3310
            to see if it is a proper descendant.
3213
3311
        :param graph: A Graph object that can be used to query history
3214
3312
            information. This can be None.
 
3313
        :param fetch_tags: Flag that specifies if tags from source should be
 
3314
            fetched too.
3215
3315
        :return: None
3216
3316
        """
3217
3317
        raise NotImplementedError(self.update_revisions)
3218
3318
 
 
3319
    @needs_write_lock
3219
3320
    def push(self, overwrite=False, stop_revision=None,
3220
3321
             _override_hook_source_branch=None):
3221
3322
        """Mirror the source branch into the target branch.
3224
3325
        """
3225
3326
        raise NotImplementedError(self.push)
3226
3327
 
 
3328
    @needs_write_lock
 
3329
    def copy_content_into(self, revision_id=None):
 
3330
        """Copy the content of source into target
 
3331
 
 
3332
        revision_id: if not None, the revision history in the new branch will
 
3333
                     be truncated to end with revision_id.
 
3334
        """
 
3335
        raise NotImplementedError(self.copy_content_into)
 
3336
 
 
3337
    @needs_write_lock
 
3338
    def fetch(self, stop_revision=None, fetch_spec=None):
 
3339
        """Fetch revisions.
 
3340
 
 
3341
        :param stop_revision: Last revision to fetch
 
3342
        :param fetch_spec: Fetch spec.
 
3343
        """
 
3344
        raise NotImplementedError(self.fetch)
 
3345
 
3227
3346
 
3228
3347
class GenericInterBranch(InterBranch):
3229
 
    """InterBranch implementation that uses public Branch functions.
3230
 
    """
3231
 
 
3232
 
    @staticmethod
3233
 
    def _get_branch_formats_to_test():
3234
 
        return BranchFormat._default_format, BranchFormat._default_format
3235
 
 
 
3348
    """InterBranch implementation that uses public Branch functions."""
 
3349
 
 
3350
    @classmethod
 
3351
    def is_compatible(klass, source, target):
 
3352
        # GenericBranch uses the public API, so always compatible
 
3353
        return True
 
3354
 
 
3355
    @classmethod
 
3356
    def _get_branch_formats_to_test(klass):
 
3357
        return [(format_registry.get_default(), format_registry.get_default())]
 
3358
 
 
3359
    @classmethod
 
3360
    def unwrap_format(klass, format):
 
3361
        if isinstance(format, remote.RemoteBranchFormat):
 
3362
            format._ensure_real()
 
3363
            return format._custom_format
 
3364
        return format
 
3365
 
 
3366
    @needs_write_lock
 
3367
    def copy_content_into(self, revision_id=None):
 
3368
        """Copy the content of source into target
 
3369
 
 
3370
        revision_id: if not None, the revision history in the new branch will
 
3371
                     be truncated to end with revision_id.
 
3372
        """
 
3373
        self.source.update_references(self.target)
 
3374
        self.source._synchronize_history(self.target, revision_id)
 
3375
        try:
 
3376
            parent = self.source.get_parent()
 
3377
        except errors.InaccessibleParent, e:
 
3378
            mutter('parent was not accessible to copy: %s', e)
 
3379
        else:
 
3380
            if parent:
 
3381
                self.target.set_parent(parent)
 
3382
        if self.source._push_should_merge_tags():
 
3383
            self.source.tags.merge_to(self.target.tags)
 
3384
 
 
3385
    @needs_write_lock
 
3386
    def fetch(self, stop_revision=None, fetch_spec=None):
 
3387
        if fetch_spec is not None and stop_revision is not None:
 
3388
            raise AssertionError(
 
3389
                "fetch_spec and last_revision are mutually exclusive.")
 
3390
        if self.target.base == self.source.base:
 
3391
            return (0, [])
 
3392
        self.source.lock_read()
 
3393
        try:
 
3394
            if stop_revision is None and fetch_spec is None:
 
3395
                stop_revision = self.source.last_revision()
 
3396
                stop_revision = _mod_revision.ensure_null(stop_revision)
 
3397
            return self.target.repository.fetch(self.source.repository,
 
3398
                revision_id=stop_revision, fetch_spec=fetch_spec)
 
3399
        finally:
 
3400
            self.source.unlock()
 
3401
 
 
3402
    @needs_write_lock
3236
3403
    def update_revisions(self, stop_revision=None, overwrite=False,
3237
 
        graph=None):
 
3404
        graph=None, fetch_tags=True):
3238
3405
        """See InterBranch.update_revisions()."""
3239
 
        self.source.lock_read()
3240
 
        try:
3241
 
            other_revno, other_last_revision = self.source.last_revision_info()
3242
 
            stop_revno = None # unknown
3243
 
            if stop_revision is None:
3244
 
                stop_revision = other_last_revision
3245
 
                if _mod_revision.is_null(stop_revision):
3246
 
                    # if there are no commits, we're done.
3247
 
                    return
3248
 
                stop_revno = other_revno
3249
 
 
3250
 
            # what's the current last revision, before we fetch [and change it
3251
 
            # possibly]
3252
 
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
3253
 
            # we fetch here so that we don't process data twice in the common
3254
 
            # case of having something to pull, and so that the check for
3255
 
            # already merged can operate on the just fetched graph, which will
3256
 
            # be cached in memory.
3257
 
            self.target.fetch(self.source, stop_revision)
3258
 
            # Check to see if one is an ancestor of the other
3259
 
            if not overwrite:
3260
 
                if graph is None:
3261
 
                    graph = self.target.repository.get_graph()
3262
 
                if self.target._check_if_descendant_or_diverged(
3263
 
                        stop_revision, last_rev, graph, self.source):
3264
 
                    # stop_revision is a descendant of last_rev, but we aren't
3265
 
                    # overwriting, so we're done.
3266
 
                    return
3267
 
            if stop_revno is None:
3268
 
                if graph is None:
3269
 
                    graph = self.target.repository.get_graph()
3270
 
                this_revno, this_last_revision = \
3271
 
                        self.target.last_revision_info()
3272
 
                stop_revno = graph.find_distance_to_null(stop_revision,
3273
 
                                [(other_last_revision, other_revno),
3274
 
                                 (this_last_revision, this_revno)])
3275
 
            self.target.set_last_revision_info(stop_revno, stop_revision)
3276
 
        finally:
3277
 
            self.source.unlock()
3278
 
 
 
3406
        other_revno, other_last_revision = self.source.last_revision_info()
 
3407
        stop_revno = None # unknown
 
3408
        if stop_revision is None:
 
3409
            stop_revision = other_last_revision
 
3410
            if _mod_revision.is_null(stop_revision):
 
3411
                # if there are no commits, we're done.
 
3412
                return
 
3413
            stop_revno = other_revno
 
3414
 
 
3415
        # what's the current last revision, before we fetch [and change it
 
3416
        # possibly]
 
3417
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
3418
        # we fetch here so that we don't process data twice in the common
 
3419
        # case of having something to pull, and so that the check for
 
3420
        # already merged can operate on the just fetched graph, which will
 
3421
        # be cached in memory.
 
3422
        if fetch_tags:
 
3423
            fetch_spec_factory = fetch.FetchSpecFactory()
 
3424
            fetch_spec_factory.source_branch = self.source
 
3425
            fetch_spec_factory.source_branch_stop_revision_id = stop_revision
 
3426
            fetch_spec_factory.source_repo = self.source.repository
 
3427
            fetch_spec_factory.target_repo = self.target.repository
 
3428
            fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
 
3429
            fetch_spec = fetch_spec_factory.make_fetch_spec()
 
3430
        else:
 
3431
            fetch_spec = _mod_graph.NotInOtherForRevs(self.target.repository,
 
3432
                self.source.repository, revision_ids=[stop_revision]).execute()
 
3433
        self.target.fetch(self.source, fetch_spec=fetch_spec)
 
3434
        # Check to see if one is an ancestor of the other
 
3435
        if not overwrite:
 
3436
            if graph is None:
 
3437
                graph = self.target.repository.get_graph()
 
3438
            if self.target._check_if_descendant_or_diverged(
 
3439
                    stop_revision, last_rev, graph, self.source):
 
3440
                # stop_revision is a descendant of last_rev, but we aren't
 
3441
                # overwriting, so we're done.
 
3442
                return
 
3443
        if stop_revno is None:
 
3444
            if graph is None:
 
3445
                graph = self.target.repository.get_graph()
 
3446
            this_revno, this_last_revision = \
 
3447
                    self.target.last_revision_info()
 
3448
            stop_revno = graph.find_distance_to_null(stop_revision,
 
3449
                            [(other_last_revision, other_revno),
 
3450
                             (this_last_revision, this_revno)])
 
3451
        self.target.set_last_revision_info(stop_revno, stop_revision)
 
3452
 
 
3453
    @needs_write_lock
3279
3454
    def pull(self, overwrite=False, stop_revision=None,
3280
 
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3455
             possible_transports=None, run_hooks=True,
3281
3456
             _override_hook_target=None, local=False):
3282
 
        """See Branch.pull.
 
3457
        """Pull from source into self, updating my master if any.
3283
3458
 
3284
 
        :param _hook_master: Private parameter - set the branch to
3285
 
            be supplied as the master to pull hooks.
3286
3459
        :param run_hooks: Private parameter - if false, this branch
3287
3460
            is being called because it's the master of the primary branch,
3288
3461
            so it should not run its hooks.
3289
 
        :param _override_hook_target: Private parameter - set the branch to be
3290
 
            supplied as the target_branch to pull hooks.
3291
 
        :param local: Only update the local branch, and not the bound branch.
3292
3462
        """
3293
 
        # This type of branch can't be bound.
3294
 
        if local:
 
3463
        bound_location = self.target.get_bound_location()
 
3464
        if local and not bound_location:
3295
3465
            raise errors.LocalRequiresBoundBranch()
3296
 
        result = PullResult()
3297
 
        result.source_branch = self.source
3298
 
        if _override_hook_target is None:
3299
 
            result.target_branch = self.target
3300
 
        else:
3301
 
            result.target_branch = _override_hook_target
3302
 
        self.source.lock_read()
 
3466
        master_branch = None
 
3467
        source_is_master = (self.source.user_url == bound_location)
 
3468
        if not local and bound_location and not source_is_master:
 
3469
            # not pulling from master, so we need to update master.
 
3470
            master_branch = self.target.get_master_branch(possible_transports)
 
3471
            master_branch.lock_write()
3303
3472
        try:
3304
 
            # We assume that during 'pull' the target repository is closer than
3305
 
            # the source one.
3306
 
            self.source.update_references(self.target)
3307
 
            graph = self.target.repository.get_graph(self.source.repository)
3308
 
            # TODO: Branch formats should have a flag that indicates 
3309
 
            # that revno's are expensive, and pull() should honor that flag.
3310
 
            # -- JRV20090506
3311
 
            result.old_revno, result.old_revid = \
3312
 
                self.target.last_revision_info()
3313
 
            self.target.update_revisions(self.source, stop_revision,
3314
 
                overwrite=overwrite, graph=graph)
3315
 
            # TODO: The old revid should be specified when merging tags, 
3316
 
            # so a tags implementation that versions tags can only 
3317
 
            # pull in the most recent changes. -- JRV20090506
3318
 
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3319
 
                overwrite)
3320
 
            result.new_revno, result.new_revid = self.target.last_revision_info()
3321
 
            if _hook_master:
3322
 
                result.master_branch = _hook_master
3323
 
                result.local_branch = result.target_branch
3324
 
            else:
3325
 
                result.master_branch = result.target_branch
3326
 
                result.local_branch = None
3327
 
            if run_hooks:
3328
 
                for hook in Branch.hooks['post_pull']:
3329
 
                    hook(result)
 
3473
            if master_branch:
 
3474
                # pull from source into master.
 
3475
                master_branch.pull(self.source, overwrite, stop_revision,
 
3476
                    run_hooks=False)
 
3477
            return self._pull(overwrite,
 
3478
                stop_revision, _hook_master=master_branch,
 
3479
                run_hooks=run_hooks,
 
3480
                _override_hook_target=_override_hook_target,
 
3481
                merge_tags_to_master=not source_is_master)
3330
3482
        finally:
3331
 
            self.source.unlock()
3332
 
        return result
 
3483
            if master_branch:
 
3484
                master_branch.unlock()
3333
3485
 
3334
3486
    def push(self, overwrite=False, stop_revision=None,
3335
3487
             _override_hook_source_branch=None):
3375
3527
                # push into the master from the source branch.
3376
3528
                self.source._basic_push(master_branch, overwrite, stop_revision)
3377
3529
                # and push into the target branch from the source. Note that we
3378
 
                # push from the source branch again, because its considered the
 
3530
                # push from the source branch again, because it's considered the
3379
3531
                # highest bandwidth repository.
3380
3532
                result = self.source._basic_push(self.target, overwrite,
3381
3533
                    stop_revision)
3397
3549
            _run_hooks()
3398
3550
            return result
3399
3551
 
3400
 
    @classmethod
3401
 
    def is_compatible(self, source, target):
3402
 
        # GenericBranch uses the public API, so always compatible
3403
 
        return True
3404
 
 
3405
 
 
3406
 
class InterToBranch5(GenericInterBranch):
3407
 
 
3408
 
    @staticmethod
3409
 
    def _get_branch_formats_to_test():
3410
 
        return BranchFormat._default_format, BzrBranchFormat5()
3411
 
 
3412
 
    def pull(self, overwrite=False, stop_revision=None,
3413
 
             possible_transports=None, run_hooks=True,
3414
 
             _override_hook_target=None, local=False):
3415
 
        """Pull from source into self, updating my master if any.
3416
 
 
 
3552
    def _pull(self, overwrite=False, stop_revision=None,
 
3553
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3554
             _override_hook_target=None, local=False,
 
3555
             merge_tags_to_master=True):
 
3556
        """See Branch.pull.
 
3557
 
 
3558
        This function is the core worker, used by GenericInterBranch.pull to
 
3559
        avoid duplication when pulling source->master and source->local.
 
3560
 
 
3561
        :param _hook_master: Private parameter - set the branch to
 
3562
            be supplied as the master to pull hooks.
3417
3563
        :param run_hooks: Private parameter - if false, this branch
3418
3564
            is being called because it's the master of the primary branch,
3419
3565
            so it should not run its hooks.
 
3566
            is being called because it's the master of the primary branch,
 
3567
            so it should not run its hooks.
 
3568
        :param _override_hook_target: Private parameter - set the branch to be
 
3569
            supplied as the target_branch to pull hooks.
 
3570
        :param local: Only update the local branch, and not the bound branch.
3420
3571
        """
3421
 
        bound_location = self.target.get_bound_location()
3422
 
        if local and not bound_location:
 
3572
        # This type of branch can't be bound.
 
3573
        if local:
3423
3574
            raise errors.LocalRequiresBoundBranch()
3424
 
        master_branch = None
3425
 
        if not local and bound_location and self.source.user_url != bound_location:
3426
 
            # not pulling from master, so we need to update master.
3427
 
            master_branch = self.target.get_master_branch(possible_transports)
3428
 
            master_branch.lock_write()
 
3575
        result = PullResult()
 
3576
        result.source_branch = self.source
 
3577
        if _override_hook_target is None:
 
3578
            result.target_branch = self.target
 
3579
        else:
 
3580
            result.target_branch = _override_hook_target
 
3581
        self.source.lock_read()
3429
3582
        try:
3430
 
            if master_branch:
3431
 
                # pull from source into master.
3432
 
                master_branch.pull(self.source, overwrite, stop_revision,
3433
 
                    run_hooks=False)
3434
 
            return super(InterToBranch5, self).pull(overwrite,
3435
 
                stop_revision, _hook_master=master_branch,
3436
 
                run_hooks=run_hooks,
3437
 
                _override_hook_target=_override_hook_target)
 
3583
            # We assume that during 'pull' the target repository is closer than
 
3584
            # the source one.
 
3585
            self.source.update_references(self.target)
 
3586
            graph = self.target.repository.get_graph(self.source.repository)
 
3587
            # TODO: Branch formats should have a flag that indicates 
 
3588
            # that revno's are expensive, and pull() should honor that flag.
 
3589
            # -- JRV20090506
 
3590
            result.old_revno, result.old_revid = \
 
3591
                self.target.last_revision_info()
 
3592
            self.target.update_revisions(self.source, stop_revision,
 
3593
                overwrite=overwrite, graph=graph)
 
3594
            # TODO: The old revid should be specified when merging tags, 
 
3595
            # so a tags implementation that versions tags can only 
 
3596
            # pull in the most recent changes. -- JRV20090506
 
3597
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
3598
                overwrite, ignore_master=not merge_tags_to_master)
 
3599
            result.new_revno, result.new_revid = self.target.last_revision_info()
 
3600
            if _hook_master:
 
3601
                result.master_branch = _hook_master
 
3602
                result.local_branch = result.target_branch
 
3603
            else:
 
3604
                result.master_branch = result.target_branch
 
3605
                result.local_branch = None
 
3606
            if run_hooks:
 
3607
                for hook in Branch.hooks['post_pull']:
 
3608
                    hook(result)
3438
3609
        finally:
3439
 
            if master_branch:
3440
 
                master_branch.unlock()
 
3610
            self.source.unlock()
 
3611
        return result
3441
3612
 
3442
3613
 
3443
3614
InterBranch.register_optimiser(GenericInterBranch)
3444
 
InterBranch.register_optimiser(InterToBranch5)