/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: Robert Collins
  • Date: 2010-05-06 11:08:10 UTC
  • mto: This revision was merged to the branch mainline in revision 5223.
  • Revision ID: robertc@robertcollins.net-20100506110810-h3j07fh5gmw54s25
Cleaner matcher matching revised unlocking protocol.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005-2010 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,
32
30
        lockdir,
33
31
        lockable_files,
34
 
        remote,
35
32
        repository,
36
33
        revision as _mod_revision,
37
34
        rio,
42
39
        urlutils,
43
40
        )
44
41
from bzrlib.config import BranchConfig, TransportConfig
 
42
from bzrlib.repofmt.pack_repo import RepositoryFormatKnitPack5RichRoot
45
43
from bzrlib.tag import (
46
44
    BasicTags,
47
45
    DisabledTags,
48
46
    )
49
47
""")
50
48
 
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
 
49
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
 
50
from bzrlib.hooks import HookPoint, Hooks
60
51
from bzrlib.inter import InterObject
61
 
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
 
52
from bzrlib.lock import _RelockDebugMixin
62
53
from bzrlib import registry
63
54
from bzrlib.symbol_versioning import (
64
55
    deprecated_in,
72
63
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
73
64
 
74
65
 
75
 
class Branch(controldir.ControlComponent):
 
66
class Branch(bzrdir.ControlComponent):
76
67
    """Branch holding a history of revisions.
77
68
 
78
69
    :ivar base:
79
70
        Base directory/url of the branch; using control_url and
80
71
        control_transport is more standardized.
81
 
    :ivar hooks: An instance of BranchHooks.
82
 
    :ivar _master_branch_cache: cached result of get_master_branch, see
83
 
        _clear_cached_state.
 
72
 
 
73
    hooks: An instance of BranchHooks.
84
74
    """
85
75
    # this is really an instance variable - FIXME move it there
86
76
    # - RBC 20060112
100
90
        self._revision_id_to_revno_cache = None
101
91
        self._partial_revision_id_to_revno_cache = {}
102
92
        self._partial_revision_history_cache = []
103
 
        self._tags_bytes = None
104
93
        self._last_revision_info_cache = None
105
 
        self._master_branch_cache = None
106
94
        self._merge_sorted_revisions_cache = None
107
95
        self._open_hook()
108
96
        hooks = Branch.hooks['open']
114
102
 
115
103
    def _activate_fallback_location(self, url):
116
104
        """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
124
105
        repo = self._get_fallback_repository(url)
125
106
        if repo.has_same_location(self.repository):
126
107
            raise errors.UnstackableLocationError(self.user_url, url)
216
197
        return self.supports_tags() and self.tags.get_tag_dict()
217
198
 
218
199
    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
 
        """
226
200
        return BranchConfig(self)
227
201
 
228
202
    def _get_config(self):
244
218
            possible_transports=[self.bzrdir.root_transport])
245
219
        return a_branch.repository
246
220
 
247
 
    @needs_read_lock
248
221
    def _get_tags_bytes(self):
249
222
        """Get the bytes of a serialised tags dict.
250
223
 
257
230
        :return: The bytes of the tags file.
258
231
        :seealso: Branch._set_tags_bytes.
259
232
        """
260
 
        if self._tags_bytes is None:
261
 
            self._tags_bytes = self._transport.get_bytes('tags')
262
 
        return self._tags_bytes
 
233
        return self._transport.get_bytes('tags')
263
234
 
264
235
    def _get_nick(self, local=False, possible_transports=None):
265
236
        config = self.get_config()
267
238
        if not local and not config.has_explicit_nickname():
268
239
            try:
269
240
                master = self.get_master_branch(possible_transports)
270
 
                if master and self.user_url == master.user_url:
271
 
                    raise errors.RecursiveBind(self.user_url)
272
241
                if master is not None:
273
242
                    # return the master branch value
274
243
                    return master.nick
275
 
            except errors.RecursiveBind, e:
276
 
                raise e
277
244
            except errors.BzrError, e:
278
245
                # Silently fall back to local implicit nick if the master is
279
246
                # unavailable
316
283
        new_history.reverse()
317
284
        return new_history
318
285
 
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
 
        """
 
286
    def lock_write(self):
326
287
        raise NotImplementedError(self.lock_write)
327
288
 
328
289
    def lock_read(self):
329
 
        """Lock the branch for read operations.
330
 
 
331
 
        :return: A bzrlib.lock.LogicalLockResult.
332
 
        """
333
290
        raise NotImplementedError(self.lock_read)
334
291
 
335
292
    def unlock(self):
669
626
        raise errors.UnsupportedOperation(self.get_reference_info, self)
670
627
 
671
628
    @needs_write_lock
672
 
    def fetch(self, from_branch, last_revision=None, fetch_spec=None):
 
629
    def fetch(self, from_branch, last_revision=None, pb=None):
673
630
        """Copy revisions from from_branch into this branch.
674
631
 
675
632
        :param from_branch: Where to copy from.
676
633
        :param last_revision: What revision to stop at (None for at the end
677
634
                              of the branch.
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.
 
635
        :param pb: An optional progress bar to use.
682
636
        :return: None
683
637
        """
684
 
        return InterBranch.get(from_branch, self).fetch(last_revision,
685
 
            fetch_spec)
 
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()
686
654
 
687
655
    def get_bound_location(self):
688
656
        """Return the URL of the branch we are bound to.
699
667
 
700
668
    def get_commit_builder(self, parents, config=None, timestamp=None,
701
669
                           timezone=None, committer=None, revprops=None,
702
 
                           revision_id=None, lossy=False):
 
670
                           revision_id=None):
703
671
        """Obtain a CommitBuilder for this branch.
704
672
 
705
673
        :param parents: Revision ids of the parents of the new revision.
709
677
        :param committer: Optional committer to set for commit.
710
678
        :param revprops: Optional dictionary of revision properties.
711
679
        :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 
714
680
        """
715
681
 
716
682
        if config is None:
717
683
            config = self.get_config()
718
684
 
719
685
        return self.repository.get_commit_builder(self, parents, config,
720
 
            timestamp, timezone, committer, revprops, revision_id,
721
 
            lossy)
 
686
            timestamp, timezone, committer, revprops, revision_id)
722
687
 
723
688
    def get_master_branch(self, possible_transports=None):
724
689
        """Return the branch we are bound to.
802
767
 
803
768
    def _unstack(self):
804
769
        """Change a branch to be unstacked, copying data as needed.
805
 
 
 
770
        
806
771
        Don't call this directly, use set_stacked_on_url(None).
807
772
        """
808
773
        pb = ui.ui_factory.nested_progress_bar()
817
782
            old_repository = self.repository
818
783
            if len(old_repository._fallback_repositories) != 1:
819
784
                raise AssertionError("can't cope with fallback repositories "
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()
 
785
                    "of %r" % (self.repository,))
 
786
            # unlock it, including unlocking the fallback
849
787
            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):
 
788
            old_repository.lock_read()
 
789
            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
868
807
                self.repository.lock_write()
869
 
            # Fetch from the old repository into the new.
870
 
            old_repository.lock_read()
871
 
            try:
872
808
                # XXX: If you unstack a branch while it has a working tree
873
809
                # with a pending merge, the pending-merged revisions will no
874
810
                # longer be present.  You can (probably) revert and remerge.
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)
 
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)
883
818
            finally:
884
819
                old_repository.unlock()
885
820
        finally:
890
825
 
891
826
        :seealso: Branch._get_tags_bytes.
892
827
        """
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)
 
828
        return _run_with_write_locked_target(self, self._transport.put_bytes,
 
829
            'tags', bytes)
899
830
 
900
831
    def _cache_revision_history(self, rev_history):
901
832
        """Set the cached revision history to rev_history.
928
859
        self._revision_history_cache = None
929
860
        self._revision_id_to_revno_cache = None
930
861
        self._last_revision_info_cache = None
931
 
        self._master_branch_cache = None
932
862
        self._merge_sorted_revisions_cache = None
933
863
        self._partial_revision_history_cache = []
934
864
        self._partial_revision_id_to_revno_cache = {}
935
 
        self._tags_bytes = None
936
865
 
937
866
    def _gen_revision_history(self):
938
867
        """Return sequence of revision hashes on to this branch.
999
928
        else:
1000
929
            return (0, _mod_revision.NULL_REVISION)
1001
930
 
 
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
1002
955
    def update_revisions(self, other, stop_revision=None, overwrite=False,
1003
 
                         graph=None, fetch_tags=True):
 
956
                         graph=None):
1004
957
        """Pull in new perfect-fit revisions.
1005
958
 
1006
959
        :param other: Another Branch to pull from
1009
962
            to see if it is a proper descendant.
1010
963
        :param graph: A Graph object that can be used to query history
1011
964
            information. This can be None.
1012
 
        :param fetch_tags: Flag that specifies if tags from other should be
1013
 
            fetched too.
1014
965
        :return: None
1015
966
        """
1016
967
        return InterBranch.get(other, self).update_revisions(stop_revision,
1017
 
            overwrite, graph, fetch_tags=fetch_tags)
 
968
            overwrite, graph)
1018
969
 
1019
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1020
970
    def import_last_revision_info(self, source_repo, revno, revid):
1021
971
        """Set the last revision info, importing from another repo if necessary.
1022
972
 
 
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
 
1023
976
        :param source_repo: Source repository to optionally fetch from
1024
977
        :param revno: Revision number of the new tip
1025
978
        :param revid: Revision id of the new tip
1028
981
            self.repository.fetch(source_repo, revision_id=revid)
1029
982
        self.set_last_revision_info(revno, revid)
1030
983
 
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
 
 
1059
984
    def revision_id_to_revno(self, revision_id):
1060
985
        """Given a revision id, return its revno"""
1061
986
        if _mod_revision.is_null(revision_id):
1081
1006
            self._extend_partial_history(distance_from_last)
1082
1007
        return self._partial_revision_history_cache[distance_from_last]
1083
1008
 
 
1009
    @needs_write_lock
1084
1010
    def pull(self, source, overwrite=False, stop_revision=None,
1085
1011
             possible_transports=None, *args, **kwargs):
1086
1012
        """Mirror source into this branch.
1282
1208
        return result
1283
1209
 
1284
1210
    @needs_read_lock
1285
 
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None,
1286
 
            repository=None):
 
1211
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None):
1287
1212
        """Create a new line of development from the branch, into to_bzrdir.
1288
1213
 
1289
1214
        to_bzrdir controls the branch format.
1294
1219
        if (repository_policy is not None and
1295
1220
            repository_policy.requires_stacking()):
1296
1221
            to_bzrdir._format.require_stacking(_skip_repo=True)
1297
 
        result = to_bzrdir.create_branch(repository=repository)
 
1222
        result = to_bzrdir.create_branch()
1298
1223
        result.lock_write()
1299
1224
        try:
1300
1225
            if repository_policy is not None:
1330
1255
                revno = 1
1331
1256
        destination.set_last_revision_info(revno, revision_id)
1332
1257
 
 
1258
    @needs_read_lock
1333
1259
    def copy_content_into(self, destination, revision_id=None):
1334
1260
        """Copy the content of self into destination.
1335
1261
 
1336
1262
        revision_id: if not None, the revision history in the new branch will
1337
1263
                     be truncated to end with revision_id.
1338
1264
        """
1339
 
        return InterBranch.get(self, destination).copy_content_into(
1340
 
            revision_id=revision_id)
 
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)
1341
1276
 
1342
1277
    def update_references(self, target):
1343
1278
        if not getattr(self._format, 'supports_reference_locations', False):
1388
1323
        """Return the most suitable metadir for a checkout of this branch.
1389
1324
        Weaves are used if this branch's repository uses weaves.
1390
1325
        """
1391
 
        format = self.repository.bzrdir.checkout_metadir()
1392
 
        format.set_branch_format(self._format)
 
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)
1393
1333
        return format
1394
1334
 
1395
1335
    def create_clone_on_transport(self, to_transport, revision_id=None,
1396
 
        stacked_on=None, create_prefix=False, use_existing_dir=False,
1397
 
        no_tree=None):
 
1336
        stacked_on=None, create_prefix=False, use_existing_dir=False):
1398
1337
        """Create a clone of this branch and its bzrdir.
1399
1338
 
1400
1339
        :param to_transport: The transport to clone onto.
1407
1346
        """
1408
1347
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1409
1348
        # clone call. Or something. 20090224 RBC/spiv.
1410
 
        # XXX: Should this perhaps clone colocated branches as well, 
1411
 
        # rather than just the default branch? 20100319 JRV
1412
1349
        if revision_id is None:
1413
1350
            revision_id = self.last_revision()
1414
1351
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1415
1352
            revision_id=revision_id, stacked_on=stacked_on,
1416
 
            create_prefix=create_prefix, use_existing_dir=use_existing_dir,
1417
 
            no_tree=no_tree)
 
1353
            create_prefix=create_prefix, use_existing_dir=use_existing_dir)
1418
1354
        return dir_to.open_branch()
1419
1355
 
1420
1356
    def create_checkout(self, to_location, revision_id=None,
1535
1471
        else:
1536
1472
            raise AssertionError("invalid heads: %r" % (heads,))
1537
1473
 
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):
 
1474
 
 
1475
class BranchFormat(object):
1560
1476
    """An encapsulation of the initialization and open routines for a format.
1561
1477
 
1562
1478
    Formats provide three things:
1565
1481
     * an open routine.
1566
1482
 
1567
1483
    Formats are placed in an dict by their format string for reference
1568
 
    during branch opening. It's not required that these be instances, they
 
1484
    during branch opening. Its not required that these be instances, they
1569
1485
    can be classes themselves with class methods - it simply depends on
1570
1486
    whether state is needed for a given format or not.
1571
1487
 
1574
1490
    object will be created every time regardless.
1575
1491
    """
1576
1492
 
 
1493
    _default_format = None
 
1494
    """The default format used for new branches."""
 
1495
 
 
1496
    _formats = {}
 
1497
    """The known formats."""
 
1498
 
1577
1499
    can_set_append_revisions_only = True
1578
1500
 
1579
1501
    def __eq__(self, other):
1588
1510
        try:
1589
1511
            transport = a_bzrdir.get_branch_transport(None, name=name)
1590
1512
            format_string = transport.get_bytes("format")
1591
 
            return format_registry.get(format_string)
 
1513
            return klass._formats[format_string]
1592
1514
        except errors.NoSuchFile:
1593
1515
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1594
1516
        except KeyError:
1595
1517
            raise errors.UnknownFormatError(format=format_string, kind='branch')
1596
1518
 
1597
1519
    @classmethod
1598
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1599
1520
    def get_default_format(klass):
1600
1521
        """Return the current 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()
1612
 
 
1613
 
    def get_reference(self, a_bzrdir, name=None):
 
1522
        return klass._default_format
 
1523
 
 
1524
    def get_reference(self, a_bzrdir):
1614
1525
        """Get the target reference of the branch in a_bzrdir.
1615
1526
 
1616
1527
        format probing must have been completed before calling
1618
1529
        in a_bzrdir is correct.
1619
1530
 
1620
1531
        :param a_bzrdir: The bzrdir to get the branch data from.
1621
 
        :param name: Name of the colocated branch to fetch
1622
1532
        :return: None if the branch is not a reference branch.
1623
1533
        """
1624
1534
        return None
1625
1535
 
1626
1536
    @classmethod
1627
 
    def set_reference(self, a_bzrdir, name, to_branch):
 
1537
    def set_reference(self, a_bzrdir, to_branch):
1628
1538
        """Set the target reference of the branch in a_bzrdir.
1629
1539
 
1630
1540
        format probing must have been completed before calling
1632
1542
        in a_bzrdir is correct.
1633
1543
 
1634
1544
        :param a_bzrdir: The bzrdir to set the branch reference for.
1635
 
        :param name: Name of colocated branch to set, None for default
1636
1545
        :param to_branch: branch that the checkout is to reference
1637
1546
        """
1638
1547
        raise NotImplementedError(self.set_reference)
1653
1562
        for hook in hooks:
1654
1563
            hook(params)
1655
1564
 
1656
 
    def initialize(self, a_bzrdir, name=None, repository=None):
 
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):
1657
1611
        """Create a branch of this format in a_bzrdir.
1658
1612
        
1659
1613
        :param name: Name of the colocated branch to create.
1693
1647
        """
1694
1648
        raise NotImplementedError(self.network_name)
1695
1649
 
1696
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
1697
 
            found_repository=None):
 
1650
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
1698
1651
        """Return the branch object for a_bzrdir
1699
1652
 
1700
1653
        :param a_bzrdir: A BzrDir that contains a branch.
1707
1660
        raise NotImplementedError(self.open)
1708
1661
 
1709
1662
    @classmethod
1710
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1711
1663
    def register_format(klass, format):
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)
 
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__)
1718
1669
 
1719
1670
    @classmethod
1720
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1721
1671
    def set_default_format(klass, format):
1722
 
        format_registry.set_default(format)
 
1672
        klass._default_format = format
1723
1673
 
1724
1674
    def supports_set_append_revisions_only(self):
1725
1675
        """True if this format supports set_append_revisions_only."""
1729
1679
        """True if this format records a stacked-on branch."""
1730
1680
        return False
1731
1681
 
1732
 
    def supports_leaving_lock(self):
1733
 
        """True if this format supports leaving locks in place."""
1734
 
        return False # by default
1735
 
 
1736
1682
    @classmethod
1737
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1738
1683
    def unregister_format(klass, format):
1739
 
        format_registry.remove(format)
 
1684
        del klass._formats[format.get_format_string()]
1740
1685
 
1741
1686
    def __str__(self):
1742
1687
        return self.get_format_description().rstrip()
1746
1691
        return False  # by default
1747
1692
 
1748
1693
 
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
 
 
1777
1694
class BranchHooks(Hooks):
1778
1695
    """A dictionary mapping hook name to a list of callables for branch hooks.
1779
1696
 
1787
1704
        These are all empty initially, because by default nothing should get
1788
1705
        notified.
1789
1706
        """
1790
 
        Hooks.__init__(self, "bzrlib.branch", "Branch.hooks")
1791
 
        self.add_hook('set_rh',
 
1707
        Hooks.__init__(self)
 
1708
        self.create_hook(HookPoint('set_rh',
1792
1709
            "Invoked whenever the revision history has been set via "
1793
1710
            "set_revision_history. The api signature is (branch, "
1794
1711
            "revision_history), and the branch will be write-locked. "
1795
1712
            "The set_rh hook can be expensive for bzr to trigger, a better "
1796
 
            "hook to use is Branch.post_change_branch_tip.", (0, 15))
1797
 
        self.add_hook('open',
 
1713
            "hook to use is Branch.post_change_branch_tip.", (0, 15), None))
 
1714
        self.create_hook(HookPoint('open',
1798
1715
            "Called with the Branch object that has been opened after a "
1799
 
            "branch is opened.", (1, 8))
1800
 
        self.add_hook('post_push',
 
1716
            "branch is opened.", (1, 8), None))
 
1717
        self.create_hook(HookPoint('post_push',
1801
1718
            "Called after a push operation completes. post_push is called "
1802
1719
            "with a bzrlib.branch.BranchPushResult object and only runs in the "
1803
 
            "bzr client.", (0, 15))
1804
 
        self.add_hook('post_pull',
 
1720
            "bzr client.", (0, 15), None))
 
1721
        self.create_hook(HookPoint('post_pull',
1805
1722
            "Called after a pull operation completes. post_pull is called "
1806
1723
            "with a bzrlib.branch.PullResult object and only runs in the "
1807
 
            "bzr client.", (0, 15))
1808
 
        self.add_hook('pre_commit',
1809
 
            "Called after a commit is calculated but before it is "
 
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 "
1810
1727
            "completed. pre_commit is called with (local, master, old_revno, "
1811
1728
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
1812
1729
            "). old_revid is NULL_REVISION for the first commit to a branch, "
1814
1731
            "basis revision. hooks MUST NOT modify this delta. "
1815
1732
            " future_tree is an in-memory tree obtained from "
1816
1733
            "CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1817
 
            "tree.", (0,91))
1818
 
        self.add_hook('post_commit',
 
1734
            "tree.", (0,91), None))
 
1735
        self.create_hook(HookPoint('post_commit',
1819
1736
            "Called in the bzr client after a commit has completed. "
1820
1737
            "post_commit is called with (local, master, old_revno, old_revid, "
1821
1738
            "new_revno, new_revid). old_revid is NULL_REVISION for the first "
1822
 
            "commit to a branch.", (0, 15))
1823
 
        self.add_hook('post_uncommit',
 
1739
            "commit to a branch.", (0, 15), None))
 
1740
        self.create_hook(HookPoint('post_uncommit',
1824
1741
            "Called in the bzr client after an uncommit completes. "
1825
1742
            "post_uncommit is called with (local, master, old_revno, "
1826
1743
            "old_revid, new_revno, new_revid) where local is the local branch "
1827
1744
            "or None, master is the target branch, and an empty branch "
1828
 
            "receives new_revno of 0, new_revid of None.", (0, 15))
1829
 
        self.add_hook('pre_change_branch_tip',
 
1745
            "receives new_revno of 0, new_revid of None.", (0, 15), None))
 
1746
        self.create_hook(HookPoint('pre_change_branch_tip',
1830
1747
            "Called in bzr client and server before a change to the tip of a "
1831
1748
            "branch is made. pre_change_branch_tip is called with a "
1832
1749
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1833
 
            "commit, uncommit will all trigger this hook.", (1, 6))
1834
 
        self.add_hook('post_change_branch_tip',
 
1750
            "commit, uncommit will all trigger this hook.", (1, 6), None))
 
1751
        self.create_hook(HookPoint('post_change_branch_tip',
1835
1752
            "Called in bzr client and server after a change to the tip of a "
1836
1753
            "branch is made. post_change_branch_tip is called with a "
1837
1754
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1838
 
            "commit, uncommit will all trigger this hook.", (1, 4))
1839
 
        self.add_hook('transform_fallback_location',
 
1755
            "commit, uncommit will all trigger this hook.", (1, 4), None))
 
1756
        self.create_hook(HookPoint('transform_fallback_location',
1840
1757
            "Called when a stacked branch is activating its fallback "
1841
1758
            "locations. transform_fallback_location is called with (branch, "
1842
1759
            "url), and should return a new url. Returning the same url "
1847
1764
            "fallback locations have not been activated. When there are "
1848
1765
            "multiple hooks installed for transform_fallback_location, "
1849
1766
            "all are called with the url returned from the previous hook."
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. "
 
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."
1853
1770
            "automatic_tag_name is called with (branch, revision_id) and "
1854
1771
            "should return a tag name or None if no tag name could be "
1855
1772
            "determined. The first non-None tag name returned will be used.",
1856
 
            (2, 2))
1857
 
        self.add_hook('post_branch_init',
 
1773
            (2, 2), None))
 
1774
        self.create_hook(HookPoint('post_branch_init',
1858
1775
            "Called after new branch initialization completes. "
1859
1776
            "post_branch_init is called with a "
1860
1777
            "bzrlib.branch.BranchInitHookParams. "
1861
1778
            "Note that init, branch and checkout (both heavyweight and "
1862
 
            "lightweight) will all trigger this hook.", (2, 2))
1863
 
        self.add_hook('post_switch',
 
1779
            "lightweight) will all trigger this hook.", (2, 2), None))
 
1780
        self.create_hook(HookPoint('post_switch',
1864
1781
            "Called after a checkout switches branch. "
1865
1782
            "post_switch is called with a "
1866
 
            "bzrlib.branch.SwitchHookParams.", (2, 2))
 
1783
            "bzrlib.branch.SwitchHookParams.", (2, 2), None))
1867
1784
 
1868
1785
 
1869
1786
 
1946
1863
        return self.__dict__ == other.__dict__
1947
1864
 
1948
1865
    def __repr__(self):
1949
 
        return "<%s of %s>" % (self.__class__.__name__, self.branch)
 
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)
1950
1872
 
1951
1873
 
1952
1874
class SwitchHookParams(object):
1982
1904
            self.revision_id)
1983
1905
 
1984
1906
 
 
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
 
1985
1950
class BranchFormatMetadir(BranchFormat):
1986
1951
    """Common logic for meta-dir based branch formats."""
1987
1952
 
1989
1954
        """What class to instantiate on open calls."""
1990
1955
        raise NotImplementedError(self._branch_class)
1991
1956
 
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
 
 
2021
1957
    def network_name(self):
2022
1958
        """A simple byte string uniquely identifying this format for RPC calls.
2023
1959
 
2025
1961
        """
2026
1962
        return self.get_format_string()
2027
1963
 
2028
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
2029
 
            found_repository=None):
 
1964
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
2030
1965
        """See BranchFormat.open()."""
2031
1966
        if not _found:
2032
1967
            format = BranchFormat.find_format(a_bzrdir, name=name)
2037
1972
        try:
2038
1973
            control_files = lockable_files.LockableFiles(transport, 'lock',
2039
1974
                                                         lockdir.LockDir)
2040
 
            if found_repository is None:
2041
 
                found_repository = a_bzrdir.find_repository()
2042
1975
            return self._branch_class()(_format=self,
2043
1976
                              _control_files=control_files,
2044
1977
                              name=name,
2045
1978
                              a_bzrdir=a_bzrdir,
2046
 
                              _repository=found_repository,
 
1979
                              _repository=a_bzrdir.find_repository(),
2047
1980
                              ignore_fallbacks=ignore_fallbacks)
2048
1981
        except errors.NoSuchFile:
2049
1982
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
2056
1989
    def supports_tags(self):
2057
1990
        return True
2058
1991
 
2059
 
    def supports_leaving_lock(self):
2060
 
        return True
2061
 
 
2062
1992
 
2063
1993
class BzrBranchFormat5(BranchFormatMetadir):
2064
1994
    """Bzr branch format 5.
2084
2014
        """See BranchFormat.get_format_description()."""
2085
2015
        return "Branch format 5"
2086
2016
 
2087
 
    def initialize(self, a_bzrdir, name=None, repository=None):
 
2017
    def initialize(self, a_bzrdir, name=None):
2088
2018
        """Create a branch of this format in a_bzrdir."""
2089
2019
        utf8_files = [('revision-history', ''),
2090
2020
                      ('branch-name', ''),
2091
2021
                      ]
2092
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
2022
        return self._initialize_helper(a_bzrdir, utf8_files, name)
2093
2023
 
2094
2024
    def supports_tags(self):
2095
2025
        return False
2117
2047
        """See BranchFormat.get_format_description()."""
2118
2048
        return "Branch format 6"
2119
2049
 
2120
 
    def initialize(self, a_bzrdir, name=None, repository=None):
 
2050
    def initialize(self, a_bzrdir, name=None):
2121
2051
        """Create a branch of this format in a_bzrdir."""
2122
2052
        utf8_files = [('last-revision', '0 null:\n'),
2123
2053
                      ('branch.conf', ''),
2124
2054
                      ('tags', ''),
2125
2055
                      ]
2126
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
2056
        return self._initialize_helper(a_bzrdir, utf8_files, name)
2127
2057
 
2128
2058
    def make_tags(self, branch):
2129
2059
        """See bzrlib.branch.BranchFormat.make_tags()."""
2147
2077
        """See BranchFormat.get_format_description()."""
2148
2078
        return "Branch format 8"
2149
2079
 
2150
 
    def initialize(self, a_bzrdir, name=None, repository=None):
 
2080
    def initialize(self, a_bzrdir, name=None):
2151
2081
        """Create a branch of this format in a_bzrdir."""
2152
2082
        utf8_files = [('last-revision', '0 null:\n'),
2153
2083
                      ('branch.conf', ''),
2154
2084
                      ('tags', ''),
2155
2085
                      ('references', '')
2156
2086
                      ]
2157
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
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()
2158
2093
 
2159
2094
    def make_tags(self, branch):
2160
2095
        """See bzrlib.branch.BranchFormat.make_tags()."""
2169
2104
    supports_reference_locations = True
2170
2105
 
2171
2106
 
2172
 
class BzrBranchFormat7(BranchFormatMetadir):
 
2107
class BzrBranchFormat7(BzrBranchFormat8):
2173
2108
    """Branch format with last-revision, tags, and a stacked location pointer.
2174
2109
 
2175
2110
    The stacked location pointer is passed down to the repository and requires
2178
2113
    This format was introduced in bzr 1.6.
2179
2114
    """
2180
2115
 
2181
 
    def initialize(self, a_bzrdir, name=None, repository=None):
 
2116
    def initialize(self, a_bzrdir, name=None):
2182
2117
        """Create a branch of this format in a_bzrdir."""
2183
2118
        utf8_files = [('last-revision', '0 null:\n'),
2184
2119
                      ('branch.conf', ''),
2185
2120
                      ('tags', ''),
2186
2121
                      ]
2187
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
2122
        return self._initialize_helper(a_bzrdir, utf8_files, name)
2188
2123
 
2189
2124
    def _branch_class(self):
2190
2125
        return BzrBranch7
2200
2135
    def supports_set_append_revisions_only(self):
2201
2136
        return True
2202
2137
 
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
 
 
2210
2138
    supports_reference_locations = False
2211
2139
 
2212
2140
 
2229
2157
        """See BranchFormat.get_format_description()."""
2230
2158
        return "Checkout reference format 1"
2231
2159
 
2232
 
    def get_reference(self, a_bzrdir, name=None):
 
2160
    def get_reference(self, a_bzrdir):
2233
2161
        """See BranchFormat.get_reference()."""
2234
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
2162
        transport = a_bzrdir.get_branch_transport(None)
2235
2163
        return transport.get_bytes('location')
2236
2164
 
2237
 
    def set_reference(self, a_bzrdir, name, to_branch):
 
2165
    def set_reference(self, a_bzrdir, to_branch):
2238
2166
        """See BranchFormat.set_reference()."""
2239
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
2167
        transport = a_bzrdir.get_branch_transport(None)
2240
2168
        location = transport.put_bytes('location', to_branch.base)
2241
2169
 
2242
 
    def initialize(self, a_bzrdir, name=None, target_branch=None,
2243
 
            repository=None):
 
2170
    def initialize(self, a_bzrdir, name=None, target_branch=None):
2244
2171
        """Create a branch of this format in a_bzrdir."""
2245
2172
        if target_branch is None:
2246
2173
            # this format does not implement branch itself, thus the implicit
2274
2201
        return clone
2275
2202
 
2276
2203
    def open(self, a_bzrdir, name=None, _found=False, location=None,
2277
 
             possible_transports=None, ignore_fallbacks=False,
2278
 
             found_repository=None):
 
2204
             possible_transports=None, ignore_fallbacks=False):
2279
2205
        """Return the branch that the branch reference in a_bzrdir points at.
2280
2206
 
2281
2207
        :param a_bzrdir: A BzrDir that contains a branch.
2295
2221
                raise AssertionError("wrong format %r found for %r" %
2296
2222
                    (format, self))
2297
2223
        if location is None:
2298
 
            location = self.get_reference(a_bzrdir, name)
 
2224
            location = self.get_reference(a_bzrdir)
2299
2225
        real_bzrdir = bzrdir.BzrDir.open(
2300
2226
            location, possible_transports=possible_transports)
2301
2227
        result = real_bzrdir.open_branch(name=name, 
2312
2238
        return result
2313
2239
 
2314
2240
 
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
 
 
2329
2241
network_format_registry = registry.FormatRegistry()
2330
2242
"""Registry of formats indexed by their network name.
2331
2243
 
2334
2246
BranchFormat.network_name() for more detail.
2335
2247
"""
2336
2248
 
2337
 
format_registry = BranchFormatRegistry(network_format_registry)
2338
 
 
2339
2249
 
2340
2250
# formats which have no format string are not discoverable
2341
2251
# and not independently creatable, so are not registered.
2343
2253
__format6 = BzrBranchFormat6()
2344
2254
__format7 = BzrBranchFormat7()
2345
2255
__format8 = BzrBranchFormat8()
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)
2352
 
 
2353
 
 
2354
 
class BranchWriteLockResult(LogicalLockResult):
2355
 
    """The result of write locking a branch.
2356
 
 
2357
 
    :ivar branch_token: The token obtained from the underlying branch lock, or
2358
 
        None.
2359
 
    :ivar unlock: A callable which will unlock the lock.
2360
 
    """
2361
 
 
2362
 
    def __init__(self, unlock, branch_token):
2363
 
        LogicalLockResult.__init__(self, unlock)
2364
 
        self.branch_token = branch_token
2365
 
 
2366
 
    def __repr__(self):
2367
 
        return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
2368
 
            self.unlock)
 
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__)
2369
2266
 
2370
2267
 
2371
2268
class BzrBranch(Branch, _RelockDebugMixin):
2427
2324
        return self.control_files.is_locked()
2428
2325
 
2429
2326
    def lock_write(self, token=None):
2430
 
        """Lock the branch for write operations.
2431
 
 
2432
 
        :param token: A token to permit reacquiring a previously held and
2433
 
            preserved lock.
2434
 
        :return: A BranchWriteLockResult.
2435
 
        """
2436
2327
        if not self.is_locked():
2437
2328
            self._note_lock('w')
2438
2329
        # All-in-one needs to always unlock/lock.
2444
2335
        else:
2445
2336
            took_lock = False
2446
2337
        try:
2447
 
            return BranchWriteLockResult(self.unlock,
2448
 
                self.control_files.lock_write(token=token))
 
2338
            return self.control_files.lock_write(token=token)
2449
2339
        except:
2450
2340
            if took_lock:
2451
2341
                self.repository.unlock()
2452
2342
            raise
2453
2343
 
2454
2344
    def lock_read(self):
2455
 
        """Lock the branch for read operations.
2456
 
 
2457
 
        :return: A bzrlib.lock.LogicalLockResult.
2458
 
        """
2459
2345
        if not self.is_locked():
2460
2346
            self._note_lock('r')
2461
2347
        # All-in-one needs to always unlock/lock.
2468
2354
            took_lock = False
2469
2355
        try:
2470
2356
            self.control_files.lock_read()
2471
 
            return LogicalLockResult(self.unlock)
2472
2357
        except:
2473
2358
            if took_lock:
2474
2359
                self.repository.unlock()
2577
2462
        configured to check constraints on history, in which case this may not
2578
2463
        be permitted.
2579
2464
        """
2580
 
        if not revision_id or not isinstance(revision_id, basestring):
2581
 
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
 
2465
        revision_id = _mod_revision.ensure_null(revision_id)
2582
2466
        # this old format stores the full history, but this api doesn't
2583
2467
        # provide it, so we must generate, and might as well check it's
2584
2468
        # correct
2631
2515
        result.target_branch = target
2632
2516
        result.old_revno, result.old_revid = target.last_revision_info()
2633
2517
        self.update_references(target)
2634
 
        if result.old_revid != stop_revision:
 
2518
        if result.old_revid != self.last_revision():
2635
2519
            # We assume that during 'push' this repository is closer than
2636
2520
            # the target.
2637
2521
            graph = self.repository.get_graph(target.repository)
2638
2522
            target.update_revisions(self, stop_revision,
2639
2523
                overwrite=overwrite, graph=graph)
2640
2524
        if self._push_should_merge_tags():
2641
 
            result.tag_conflicts = self.tags.merge_to(target.tags, overwrite)
 
2525
            result.tag_conflicts = self.tags.merge_to(target.tags,
 
2526
                overwrite)
2642
2527
        result.new_revno, result.new_revid = target.last_revision_info()
2643
2528
        return result
2644
2529
 
2676
2561
        """Return the branch we are bound to.
2677
2562
 
2678
2563
        :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.
2679
2569
        """
2680
 
        if self._master_branch_cache is None:
2681
 
            self._master_branch_cache = self._get_master_branch(
2682
 
                possible_transports)
2683
 
        return self._master_branch_cache
2684
 
 
2685
 
    def _get_master_branch(self, possible_transports):
2686
2570
        bound_loc = self.get_bound_location()
2687
2571
        if not bound_loc:
2688
2572
            return None
2699
2583
 
2700
2584
        :param location: URL to the target branch
2701
2585
        """
2702
 
        self._master_branch_cache = None
2703
2586
        if location:
2704
2587
            self._transport.put_bytes('bound', location+'\n',
2705
2588
                mode=self.bzrdir._get_file_mode())
2814
2697
 
2815
2698
    @needs_write_lock
2816
2699
    def set_last_revision_info(self, revno, revision_id):
2817
 
        if not revision_id or not isinstance(revision_id, basestring):
2818
 
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
 
2700
        revision_id = _mod_revision.ensure_null(revision_id)
2819
2701
        old_revno, old_revid = self.last_revision_info()
2820
2702
        if self._get_append_revisions_only():
2821
2703
            self._check_history_violation(revision_id)
2958
2840
 
2959
2841
    def set_bound_location(self, location):
2960
2842
        """See Branch.set_push_location."""
2961
 
        self._master_branch_cache = None
2962
2843
        result = None
2963
2844
        config = self.get_config()
2964
2845
        if location is None:
3041
2922
        try:
3042
2923
            index = self._partial_revision_history_cache.index(revision_id)
3043
2924
        except ValueError:
3044
 
            try:
3045
 
                self._extend_partial_history(stop_revision=revision_id)
3046
 
            except errors.RevisionNotPresent, e:
3047
 
                raise errors.GhostRevisionsHaveNoRevno(revision_id, e.revision_id)
 
2925
            self._extend_partial_history(stop_revision=revision_id)
3048
2926
            index = len(self._partial_revision_history_cache) - 1
3049
2927
            if self._partial_revision_history_cache[index] != revision_id:
3050
2928
                raise errors.NoSuchRevision(self, revision_id)
3105
2983
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
3106
2984
    """
3107
2985
 
3108
 
    @deprecated_method(deprecated_in((2, 3, 0)))
3109
2986
    def __int__(self):
3110
 
        """Return the relative change in revno.
3111
 
 
3112
 
        :deprecated: Use `new_revno` and `old_revno` instead.
3113
 
        """
 
2987
        # DEPRECATED: pull used to return the change in revno
3114
2988
        return self.new_revno - self.old_revno
3115
2989
 
3116
2990
    def report(self, to_file):
3141
3015
        target, otherwise it will be None.
3142
3016
    """
3143
3017
 
3144
 
    @deprecated_method(deprecated_in((2, 3, 0)))
3145
3018
    def __int__(self):
3146
 
        """Return the relative change in revno.
3147
 
 
3148
 
        :deprecated: Use `new_revno` and `old_revno` instead.
3149
 
        """
 
3019
        # DEPRECATED: push used to return the change in revno
3150
3020
        return self.new_revno - self.old_revno
3151
3021
 
3152
3022
    def report(self, to_file):
3275
3145
    _optimisers = []
3276
3146
    """The available optimised InterBranch types."""
3277
3147
 
3278
 
    @classmethod
3279
 
    def _get_branch_formats_to_test(klass):
3280
 
        """Return an iterable of format tuples for testing.
3281
 
        
3282
 
        :return: An iterable of (from_format, to_format) to use when testing
3283
 
            this InterBranch class. Each InterBranch class should define this
3284
 
            method itself.
3285
 
        """
3286
 
        raise NotImplementedError(klass._get_branch_formats_to_test)
 
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)
3287
3152
 
3288
 
    @needs_write_lock
3289
3153
    def pull(self, overwrite=False, stop_revision=None,
3290
3154
             possible_transports=None, local=False):
3291
3155
        """Mirror source into target branch.
3296
3160
        """
3297
3161
        raise NotImplementedError(self.pull)
3298
3162
 
3299
 
    @needs_write_lock
3300
3163
    def update_revisions(self, stop_revision=None, overwrite=False,
3301
 
                         graph=None, fetch_tags=True):
 
3164
                         graph=None):
3302
3165
        """Pull in new perfect-fit revisions.
3303
3166
 
3304
3167
        :param stop_revision: Updated until the given revision
3306
3169
            to see if it is a proper descendant.
3307
3170
        :param graph: A Graph object that can be used to query history
3308
3171
            information. This can be None.
3309
 
        :param fetch_tags: Flag that specifies if tags from source should be
3310
 
            fetched too.
3311
3172
        :return: None
3312
3173
        """
3313
3174
        raise NotImplementedError(self.update_revisions)
3314
3175
 
3315
 
    @needs_write_lock
3316
3176
    def push(self, overwrite=False, stop_revision=None,
3317
3177
             _override_hook_source_branch=None):
3318
3178
        """Mirror the source branch into the target branch.
3321
3181
        """
3322
3182
        raise NotImplementedError(self.push)
3323
3183
 
3324
 
    @needs_write_lock
3325
 
    def copy_content_into(self, revision_id=None):
3326
 
        """Copy the content of source into target
3327
 
 
3328
 
        revision_id: if not None, the revision history in the new branch will
3329
 
                     be truncated to end with revision_id.
3330
 
        """
3331
 
        raise NotImplementedError(self.copy_content_into)
3332
 
 
3333
 
    @needs_write_lock
3334
 
    def fetch(self, stop_revision=None, fetch_spec=None):
3335
 
        """Fetch revisions.
3336
 
 
3337
 
        :param stop_revision: Last revision to fetch
3338
 
        :param fetch_spec: Fetch spec.
3339
 
        """
3340
 
        raise NotImplementedError(self.fetch)
3341
 
 
3342
3184
 
3343
3185
class GenericInterBranch(InterBranch):
3344
 
    """InterBranch implementation that uses public Branch functions."""
3345
 
 
3346
 
    @classmethod
3347
 
    def is_compatible(klass, source, target):
3348
 
        # GenericBranch uses the public API, so always compatible
3349
 
        return True
3350
 
 
3351
 
    @classmethod
3352
 
    def _get_branch_formats_to_test(klass):
3353
 
        return [(format_registry.get_default(), format_registry.get_default())]
3354
 
 
3355
 
    @classmethod
3356
 
    def unwrap_format(klass, format):
3357
 
        if isinstance(format, remote.RemoteBranchFormat):
3358
 
            format._ensure_real()
3359
 
            return format._custom_format
3360
 
        return format
3361
 
 
3362
 
    @needs_write_lock
3363
 
    def copy_content_into(self, revision_id=None):
3364
 
        """Copy the content of source into target
3365
 
 
3366
 
        revision_id: if not None, the revision history in the new branch will
3367
 
                     be truncated to end with revision_id.
3368
 
        """
3369
 
        self.source.update_references(self.target)
3370
 
        self.source._synchronize_history(self.target, revision_id)
3371
 
        try:
3372
 
            parent = self.source.get_parent()
3373
 
        except errors.InaccessibleParent, e:
3374
 
            mutter('parent was not accessible to copy: %s', e)
3375
 
        else:
3376
 
            if parent:
3377
 
                self.target.set_parent(parent)
3378
 
        if self.source._push_should_merge_tags():
3379
 
            self.source.tags.merge_to(self.target.tags)
3380
 
 
3381
 
    @needs_write_lock
3382
 
    def fetch(self, stop_revision=None, fetch_spec=None):
3383
 
        if fetch_spec is not None and stop_revision is not None:
3384
 
            raise AssertionError(
3385
 
                "fetch_spec and last_revision are mutually exclusive.")
3386
 
        if self.target.base == self.source.base:
3387
 
            return (0, [])
3388
 
        self.source.lock_read()
3389
 
        try:
3390
 
            if stop_revision is None and fetch_spec is None:
3391
 
                stop_revision = self.source.last_revision()
3392
 
                stop_revision = _mod_revision.ensure_null(stop_revision)
3393
 
            return self.target.repository.fetch(self.source.repository,
3394
 
                revision_id=stop_revision, fetch_spec=fetch_spec)
3395
 
        finally:
3396
 
            self.source.unlock()
3397
 
 
3398
 
    @needs_write_lock
 
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
 
3399
3193
    def update_revisions(self, stop_revision=None, overwrite=False,
3400
 
        graph=None, fetch_tags=True):
 
3194
        graph=None):
3401
3195
        """See InterBranch.update_revisions()."""
3402
 
        other_revno, other_last_revision = self.source.last_revision_info()
3403
 
        stop_revno = None # unknown
3404
 
        if stop_revision is None:
3405
 
            stop_revision = other_last_revision
3406
 
            if _mod_revision.is_null(stop_revision):
3407
 
                # if there are no commits, we're done.
3408
 
                return
3409
 
            stop_revno = other_revno
3410
 
 
3411
 
        # what's the current last revision, before we fetch [and change it
3412
 
        # possibly]
3413
 
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
3414
 
        # we fetch here so that we don't process data twice in the common
3415
 
        # case of having something to pull, and so that the check for
3416
 
        # already merged can operate on the just fetched graph, which will
3417
 
        # be cached in memory.
3418
 
        if fetch_tags:
3419
 
            fetch_spec_factory = fetch.FetchSpecFactory()
3420
 
            fetch_spec_factory.source_branch = self.source
3421
 
            fetch_spec_factory.source_branch_stop_revision_id = stop_revision
3422
 
            fetch_spec_factory.source_repo = self.source.repository
3423
 
            fetch_spec_factory.target_repo = self.target.repository
3424
 
            fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
3425
 
            fetch_spec = fetch_spec_factory.make_fetch_spec()
3426
 
        else:
3427
 
            fetch_spec = _mod_graph.NotInOtherForRevs(self.target.repository,
3428
 
                self.source.repository, revision_ids=[stop_revision]).execute()
3429
 
        self.target.fetch(self.source, fetch_spec=fetch_spec)
3430
 
        # Check to see if one is an ancestor of the other
3431
 
        if not overwrite:
3432
 
            if graph is None:
3433
 
                graph = self.target.repository.get_graph()
3434
 
            if self.target._check_if_descendant_or_diverged(
3435
 
                    stop_revision, last_rev, graph, self.source):
3436
 
                # stop_revision is a descendant of last_rev, but we aren't
3437
 
                # overwriting, so we're done.
3438
 
                return
3439
 
        if stop_revno is None:
3440
 
            if graph is None:
3441
 
                graph = self.target.repository.get_graph()
3442
 
            this_revno, this_last_revision = \
3443
 
                    self.target.last_revision_info()
3444
 
            stop_revno = graph.find_distance_to_null(stop_revision,
3445
 
                            [(other_last_revision, other_revno),
3446
 
                             (this_last_revision, this_revno)])
3447
 
        self.target.set_last_revision_info(stop_revno, stop_revision)
3448
 
 
3449
 
    @needs_write_lock
 
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
 
3450
3236
    def pull(self, overwrite=False, stop_revision=None,
3451
 
             possible_transports=None, run_hooks=True,
 
3237
             possible_transports=None, _hook_master=None, run_hooks=True,
3452
3238
             _override_hook_target=None, local=False):
3453
 
        """Pull from source into self, updating my master if any.
 
3239
        """See Branch.pull.
3454
3240
 
 
3241
        :param _hook_master: Private parameter - set the branch to
 
3242
            be supplied as the master to pull hooks.
3455
3243
        :param run_hooks: Private parameter - if false, this branch
3456
3244
            is being called because it's the master of the primary branch,
3457
3245
            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.
3458
3249
        """
3459
 
        bound_location = self.target.get_bound_location()
3460
 
        if local and not bound_location:
 
3250
        # This type of branch can't be bound.
 
3251
        if local:
3461
3252
            raise errors.LocalRequiresBoundBranch()
3462
 
        master_branch = None
3463
 
        source_is_master = (self.source.user_url == bound_location)
3464
 
        if not local and bound_location and not source_is_master:
3465
 
            # not pulling from master, so we need to update master.
3466
 
            master_branch = self.target.get_master_branch(possible_transports)
3467
 
            master_branch.lock_write()
 
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()
3468
3260
        try:
3469
 
            if master_branch:
3470
 
                # pull from source into master.
3471
 
                master_branch.pull(self.source, overwrite, stop_revision,
3472
 
                    run_hooks=False)
3473
 
            return self._pull(overwrite,
3474
 
                stop_revision, _hook_master=master_branch,
3475
 
                run_hooks=run_hooks,
3476
 
                _override_hook_target=_override_hook_target,
3477
 
                merge_tags_to_master=not source_is_master)
 
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)
3478
3287
        finally:
3479
 
            if master_branch:
3480
 
                master_branch.unlock()
 
3288
            self.source.unlock()
 
3289
        return result
3481
3290
 
3482
3291
    def push(self, overwrite=False, stop_revision=None,
3483
3292
             _override_hook_source_branch=None):
3523
3332
                # push into the master from the source branch.
3524
3333
                self.source._basic_push(master_branch, overwrite, stop_revision)
3525
3334
                # and push into the target branch from the source. Note that we
3526
 
                # push from the source branch again, because it's considered the
 
3335
                # push from the source branch again, because its considered the
3527
3336
                # highest bandwidth repository.
3528
3337
                result = self.source._basic_push(self.target, overwrite,
3529
3338
                    stop_revision)
3545
3354
            _run_hooks()
3546
3355
            return result
3547
3356
 
3548
 
    def _pull(self, overwrite=False, stop_revision=None,
3549
 
             possible_transports=None, _hook_master=None, run_hooks=True,
3550
 
             _override_hook_target=None, local=False,
3551
 
             merge_tags_to_master=True):
3552
 
        """See Branch.pull.
3553
 
 
3554
 
        This function is the core worker, used by GenericInterBranch.pull to
3555
 
        avoid duplication when pulling source->master and source->local.
3556
 
 
3557
 
        :param _hook_master: Private parameter - set the branch to
3558
 
            be supplied as the master to pull hooks.
 
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
 
3559
3374
        :param run_hooks: Private parameter - if false, this branch
3560
3375
            is being called because it's the master of the primary branch,
3561
3376
            so it should not run its hooks.
3562
 
            is being called because it's the master of the primary branch,
3563
 
            so it should not run its hooks.
3564
 
        :param _override_hook_target: Private parameter - set the branch to be
3565
 
            supplied as the target_branch to pull hooks.
3566
 
        :param local: Only update the local branch, and not the bound branch.
3567
3377
        """
3568
 
        # This type of branch can't be bound.
3569
 
        if local:
 
3378
        bound_location = self.target.get_bound_location()
 
3379
        if local and not bound_location:
3570
3380
            raise errors.LocalRequiresBoundBranch()
3571
 
        result = PullResult()
3572
 
        result.source_branch = self.source
3573
 
        if _override_hook_target is None:
3574
 
            result.target_branch = self.target
3575
 
        else:
3576
 
            result.target_branch = _override_hook_target
3577
 
        self.source.lock_read()
 
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()
3578
3386
        try:
3579
 
            # We assume that during 'pull' the target repository is closer than
3580
 
            # the source one.
3581
 
            self.source.update_references(self.target)
3582
 
            graph = self.target.repository.get_graph(self.source.repository)
3583
 
            # TODO: Branch formats should have a flag that indicates 
3584
 
            # that revno's are expensive, and pull() should honor that flag.
3585
 
            # -- JRV20090506
3586
 
            result.old_revno, result.old_revid = \
3587
 
                self.target.last_revision_info()
3588
 
            self.target.update_revisions(self.source, stop_revision,
3589
 
                overwrite=overwrite, graph=graph)
3590
 
            # TODO: The old revid should be specified when merging tags, 
3591
 
            # so a tags implementation that versions tags can only 
3592
 
            # pull in the most recent changes. -- JRV20090506
3593
 
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3594
 
                overwrite, ignore_master=not merge_tags_to_master)
3595
 
            result.new_revno, result.new_revid = self.target.last_revision_info()
3596
 
            if _hook_master:
3597
 
                result.master_branch = _hook_master
3598
 
                result.local_branch = result.target_branch
3599
 
            else:
3600
 
                result.master_branch = result.target_branch
3601
 
                result.local_branch = None
3602
 
            if run_hooks:
3603
 
                for hook in Branch.hooks['post_pull']:
3604
 
                    hook(result)
 
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)
3605
3395
        finally:
3606
 
            self.source.unlock()
3607
 
        return result
 
3396
            if master_branch:
 
3397
                master_branch.unlock()
3608
3398
 
3609
3399
 
3610
3400
InterBranch.register_optimiser(GenericInterBranch)
 
3401
InterBranch.register_optimiser(InterToBranch5)