/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Jelmer Vernooij
  • Date: 2011-04-16 15:01:57 UTC
  • mfrom: (5791 +trunk)
  • mto: This revision was merged to the branch mainline in revision 5800.
  • Revision ID: jelmer@samba.org-20110416150157-5rgye9nnc8tic098
Merge bzr.dev.

Show diffs side-by-side

added added

removed removed

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