/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: Canonical.com Patch Queue Manager
  • Date: 2011-05-09 08:12:01 UTC
  • mfrom: (5837.1.3 inter-no-default)
  • Revision ID: pqm@pqm.ubuntu.com-20110509081201-1nreh088nt7xh3l1
(jelmer) Require the default for Inter.get to be explicitly registered.
 (Jelmer Vernooij)

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):
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.
636
678
        :return: None
637
679
        """
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()
 
680
        return InterBranch.get(from_branch, self).fetch(last_revision)
654
681
 
655
682
    def get_bound_location(self):
656
683
        """Return the URL of the branch we are bound to.
667
694
 
668
695
    def get_commit_builder(self, parents, config=None, timestamp=None,
669
696
                           timezone=None, committer=None, revprops=None,
670
 
                           revision_id=None):
 
697
                           revision_id=None, lossy=False):
671
698
        """Obtain a CommitBuilder for this branch.
672
699
 
673
700
        :param parents: Revision ids of the parents of the new revision.
677
704
        :param committer: Optional committer to set for commit.
678
705
        :param revprops: Optional dictionary of revision properties.
679
706
        :param revision_id: Optional revision id.
 
707
        :param lossy: Whether to discard data that can not be natively
 
708
            represented, when pushing to a foreign VCS 
680
709
        """
681
710
 
682
711
        if config is None:
683
712
            config = self.get_config()
684
713
 
685
714
        return self.repository.get_commit_builder(self, parents, config,
686
 
            timestamp, timezone, committer, revprops, revision_id)
 
715
            timestamp, timezone, committer, revprops, revision_id,
 
716
            lossy)
687
717
 
688
718
    def get_master_branch(self, possible_transports=None):
689
719
        """Return the branch we are bound to.
767
797
 
768
798
    def _unstack(self):
769
799
        """Change a branch to be unstacked, copying data as needed.
770
 
        
 
800
 
771
801
        Don't call this directly, use set_stacked_on_url(None).
772
802
        """
773
803
        pb = ui.ui_factory.nested_progress_bar()
782
812
            old_repository = self.repository
783
813
            if len(old_repository._fallback_repositories) != 1:
784
814
                raise AssertionError("can't cope with fallback repositories "
785
 
                    "of %r" % (self.repository,))
786
 
            # unlock it, including unlocking the fallback
 
815
                    "of %r (fallbacks: %r)" % (old_repository,
 
816
                        old_repository._fallback_repositories))
 
817
            # Open the new repository object.
 
818
            # Repositories don't offer an interface to remove fallback
 
819
            # repositories today; take the conceptually simpler option and just
 
820
            # reopen it.  We reopen it starting from the URL so that we
 
821
            # get a separate connection for RemoteRepositories and can
 
822
            # stream from one of them to the other.  This does mean doing
 
823
            # separate SSH connection setup, but unstacking is not a
 
824
            # common operation so it's tolerable.
 
825
            new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
 
826
            new_repository = new_bzrdir.find_repository()
 
827
            if new_repository._fallback_repositories:
 
828
                raise AssertionError("didn't expect %r to have "
 
829
                    "fallback_repositories"
 
830
                    % (self.repository,))
 
831
            # Replace self.repository with the new repository.
 
832
            # Do our best to transfer the lock state (i.e. lock-tokens and
 
833
            # lock count) of self.repository to the new repository.
 
834
            lock_token = old_repository.lock_write().repository_token
 
835
            self.repository = new_repository
 
836
            if isinstance(self, remote.RemoteBranch):
 
837
                # Remote branches can have a second reference to the old
 
838
                # repository that need to be replaced.
 
839
                if self._real_branch is not None:
 
840
                    self._real_branch.repository = new_repository
 
841
            self.repository.lock_write(token=lock_token)
 
842
            if lock_token is not None:
 
843
                old_repository.leave_lock_in_place()
787
844
            old_repository.unlock()
 
845
            if lock_token is not None:
 
846
                # XXX: self.repository.leave_lock_in_place() before this
 
847
                # function will not be preserved.  Fortunately that doesn't
 
848
                # affect the current default format (2a), and would be a
 
849
                # corner-case anyway.
 
850
                #  - Andrew Bennetts, 2010/06/30
 
851
                self.repository.dont_leave_lock_in_place()
 
852
            old_lock_count = 0
 
853
            while True:
 
854
                try:
 
855
                    old_repository.unlock()
 
856
                except errors.LockNotHeld:
 
857
                    break
 
858
                old_lock_count += 1
 
859
            if old_lock_count == 0:
 
860
                raise AssertionError(
 
861
                    'old_repository should have been locked at least once.')
 
862
            for i in range(old_lock_count-1):
 
863
                self.repository.lock_write()
 
864
            # Fetch from the old repository into the new.
788
865
            old_repository.lock_read()
789
866
            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
867
                # XXX: If you unstack a branch while it has a working tree
809
868
                # with a pending merge, the pending-merged revisions will no
810
869
                # 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)
 
870
                try:
 
871
                    tags_to_fetch = set(self.tags.get_reverse_tag_dict())
 
872
                except errors.TagsNotSupported:
 
873
                    tags_to_fetch = set()
 
874
                fetch_spec = _mod_graph.NotInOtherForRevs(self.repository,
 
875
                    old_repository, required_ids=[self.last_revision()],
 
876
                    if_present_ids=tags_to_fetch, find_ghosts=True).execute()
 
877
                self.repository.fetch(old_repository, fetch_spec=fetch_spec)
818
878
            finally:
819
879
                old_repository.unlock()
820
880
        finally:
825
885
 
826
886
        :seealso: Branch._get_tags_bytes.
827
887
        """
828
 
        return _run_with_write_locked_target(self, self._transport.put_bytes,
829
 
            'tags', bytes)
 
888
        return _run_with_write_locked_target(self, self._set_tags_bytes_locked,
 
889
                bytes)
 
890
 
 
891
    def _set_tags_bytes_locked(self, bytes):
 
892
        self._tags_bytes = bytes
 
893
        return self._transport.put_bytes('tags', bytes)
830
894
 
831
895
    def _cache_revision_history(self, rev_history):
832
896
        """Set the cached revision history to rev_history.
859
923
        self._revision_history_cache = None
860
924
        self._revision_id_to_revno_cache = None
861
925
        self._last_revision_info_cache = None
 
926
        self._master_branch_cache = None
862
927
        self._merge_sorted_revisions_cache = None
863
928
        self._partial_revision_history_cache = []
864
929
        self._partial_revision_id_to_revno_cache = {}
 
930
        self._tags_bytes = None
865
931
 
866
932
    def _gen_revision_history(self):
867
933
        """Return sequence of revision hashes on to this branch.
928
994
        else:
929
995
            return (0, _mod_revision.NULL_REVISION)
930
996
 
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
 
    def update_revisions(self, other, stop_revision=None, overwrite=False,
956
 
                         graph=None):
957
 
        """Pull in new perfect-fit revisions.
958
 
 
959
 
        :param other: Another Branch to pull from
960
 
        :param stop_revision: Updated until the given revision
961
 
        :param overwrite: Always set the branch pointer, rather than checking
962
 
            to see if it is a proper descendant.
963
 
        :param graph: A Graph object that can be used to query history
964
 
            information. This can be None.
965
 
        :return: None
966
 
        """
967
 
        return InterBranch.get(other, self).update_revisions(stop_revision,
968
 
            overwrite, graph)
969
 
 
 
997
    @deprecated_method(deprecated_in((2, 4, 0)))
970
998
    def import_last_revision_info(self, source_repo, revno, revid):
971
999
        """Set the last revision info, importing from another repo if necessary.
972
1000
 
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
1001
        :param source_repo: Source repository to optionally fetch from
977
1002
        :param revno: Revision number of the new tip
978
1003
        :param revid: Revision id of the new tip
981
1006
            self.repository.fetch(source_repo, revision_id=revid)
982
1007
        self.set_last_revision_info(revno, revid)
983
1008
 
 
1009
    def import_last_revision_info_and_tags(self, source, revno, revid,
 
1010
                                           lossy=False):
 
1011
        """Set the last revision info, importing from another repo if necessary.
 
1012
 
 
1013
        This is used by the bound branch code to upload a revision to
 
1014
        the master branch first before updating the tip of the local branch.
 
1015
        Revisions referenced by source's tags are also transferred.
 
1016
 
 
1017
        :param source: Source branch to optionally fetch from
 
1018
        :param revno: Revision number of the new tip
 
1019
        :param revid: Revision id of the new tip
 
1020
        :param lossy: Whether to discard metadata that can not be
 
1021
            natively represented
 
1022
        :return: Tuple with the new revision number and revision id
 
1023
            (should only be different from the arguments when lossy=True)
 
1024
        """
 
1025
        if not self.repository.has_same_location(source.repository):
 
1026
            self.fetch(source, revid)
 
1027
        self.set_last_revision_info(revno, revid)
 
1028
        return (revno, revid)
 
1029
 
984
1030
    def revision_id_to_revno(self, revision_id):
985
1031
        """Given a revision id, return its revno"""
986
1032
        if _mod_revision.is_null(revision_id):
1006
1052
            self._extend_partial_history(distance_from_last)
1007
1053
        return self._partial_revision_history_cache[distance_from_last]
1008
1054
 
1009
 
    @needs_write_lock
1010
1055
    def pull(self, source, overwrite=False, stop_revision=None,
1011
1056
             possible_transports=None, *args, **kwargs):
1012
1057
        """Mirror source into this branch.
1208
1253
        return result
1209
1254
 
1210
1255
    @needs_read_lock
1211
 
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None):
 
1256
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None,
 
1257
            repository=None):
1212
1258
        """Create a new line of development from the branch, into to_bzrdir.
1213
1259
 
1214
1260
        to_bzrdir controls the branch format.
1219
1265
        if (repository_policy is not None and
1220
1266
            repository_policy.requires_stacking()):
1221
1267
            to_bzrdir._format.require_stacking(_skip_repo=True)
1222
 
        result = to_bzrdir.create_branch()
 
1268
        result = to_bzrdir.create_branch(repository=repository)
1223
1269
        result.lock_write()
1224
1270
        try:
1225
1271
            if repository_policy is not None:
1226
1272
                repository_policy.configure_branch(result)
1227
1273
            self.copy_content_into(result, revision_id=revision_id)
1228
 
            result.set_parent(self.bzrdir.root_transport.base)
 
1274
            master_branch = self.get_master_branch()
 
1275
            if master_branch is None:
 
1276
                result.set_parent(self.bzrdir.root_transport.base)
 
1277
            else:
 
1278
                result.set_parent(master_branch.bzrdir.root_transport.base)
1229
1279
        finally:
1230
1280
            result.unlock()
1231
1281
        return result
1255
1305
                revno = 1
1256
1306
        destination.set_last_revision_info(revno, revision_id)
1257
1307
 
1258
 
    @needs_read_lock
1259
1308
    def copy_content_into(self, destination, revision_id=None):
1260
1309
        """Copy the content of self into destination.
1261
1310
 
1262
1311
        revision_id: if not None, the revision history in the new branch will
1263
1312
                     be truncated to end with revision_id.
1264
1313
        """
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)
 
1314
        return InterBranch.get(self, destination).copy_content_into(
 
1315
            revision_id=revision_id)
1276
1316
 
1277
1317
    def update_references(self, target):
1278
1318
        if not getattr(self._format, 'supports_reference_locations', False):
1323
1363
        """Return the most suitable metadir for a checkout of this branch.
1324
1364
        Weaves are used if this branch's repository uses weaves.
1325
1365
        """
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)
 
1366
        format = self.repository.bzrdir.checkout_metadir()
 
1367
        format.set_branch_format(self._format)
1333
1368
        return format
1334
1369
 
1335
1370
    def create_clone_on_transport(self, to_transport, revision_id=None,
1336
 
        stacked_on=None, create_prefix=False, use_existing_dir=False):
 
1371
        stacked_on=None, create_prefix=False, use_existing_dir=False,
 
1372
        no_tree=None):
1337
1373
        """Create a clone of this branch and its bzrdir.
1338
1374
 
1339
1375
        :param to_transport: The transport to clone onto.
1346
1382
        """
1347
1383
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1348
1384
        # clone call. Or something. 20090224 RBC/spiv.
 
1385
        # XXX: Should this perhaps clone colocated branches as well, 
 
1386
        # rather than just the default branch? 20100319 JRV
1349
1387
        if revision_id is None:
1350
1388
            revision_id = self.last_revision()
1351
1389
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1352
1390
            revision_id=revision_id, stacked_on=stacked_on,
1353
 
            create_prefix=create_prefix, use_existing_dir=use_existing_dir)
 
1391
            create_prefix=create_prefix, use_existing_dir=use_existing_dir,
 
1392
            no_tree=no_tree)
1354
1393
        return dir_to.open_branch()
1355
1394
 
1356
1395
    def create_checkout(self, to_location, revision_id=None,
1471
1510
        else:
1472
1511
            raise AssertionError("invalid heads: %r" % (heads,))
1473
1512
 
1474
 
 
1475
 
class BranchFormat(object):
 
1513
    def heads_to_fetch(self):
 
1514
        """Return the heads that must and that should be fetched to copy this
 
1515
        branch into another repo.
 
1516
 
 
1517
        :returns: a 2-tuple of (must_fetch, if_present_fetch).  must_fetch is a
 
1518
            set of heads that must be fetched.  if_present_fetch is a set of
 
1519
            heads that must be fetched if present, but no error is necessary if
 
1520
            they are not present.
 
1521
        """
 
1522
        # For bzr native formats must_fetch is just the tip, and if_present_fetch
 
1523
        # are the tags.
 
1524
        must_fetch = set([self.last_revision()])
 
1525
        try:
 
1526
            if_present_fetch = set(self.tags.get_reverse_tag_dict())
 
1527
        except errors.TagsNotSupported:
 
1528
            if_present_fetch = set()
 
1529
        must_fetch.discard(_mod_revision.NULL_REVISION)
 
1530
        if_present_fetch.discard(_mod_revision.NULL_REVISION)
 
1531
        return must_fetch, if_present_fetch
 
1532
 
 
1533
 
 
1534
class BranchFormat(controldir.ControlComponentFormat):
1476
1535
    """An encapsulation of the initialization and open routines for a format.
1477
1536
 
1478
1537
    Formats provide three things:
1481
1540
     * an open routine.
1482
1541
 
1483
1542
    Formats are placed in an dict by their format string for reference
1484
 
    during branch opening. Its not required that these be instances, they
 
1543
    during branch opening. It's not required that these be instances, they
1485
1544
    can be classes themselves with class methods - it simply depends on
1486
1545
    whether state is needed for a given format or not.
1487
1546
 
1490
1549
    object will be created every time regardless.
1491
1550
    """
1492
1551
 
1493
 
    _default_format = None
1494
 
    """The default format used for new branches."""
1495
 
 
1496
 
    _formats = {}
1497
 
    """The known formats."""
1498
 
 
1499
1552
    can_set_append_revisions_only = True
1500
1553
 
1501
1554
    def __eq__(self, other):
1510
1563
        try:
1511
1564
            transport = a_bzrdir.get_branch_transport(None, name=name)
1512
1565
            format_string = transport.get_bytes("format")
1513
 
            return klass._formats[format_string]
 
1566
            return format_registry.get(format_string)
1514
1567
        except errors.NoSuchFile:
1515
1568
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1516
1569
        except KeyError:
1517
1570
            raise errors.UnknownFormatError(format=format_string, kind='branch')
1518
1571
 
1519
1572
    @classmethod
 
1573
    @deprecated_method(deprecated_in((2, 4, 0)))
1520
1574
    def get_default_format(klass):
1521
1575
        """Return the current default format."""
1522
 
        return klass._default_format
1523
 
 
1524
 
    def get_reference(self, a_bzrdir):
 
1576
        return format_registry.get_default()
 
1577
 
 
1578
    @classmethod
 
1579
    @deprecated_method(deprecated_in((2, 4, 0)))
 
1580
    def get_formats(klass):
 
1581
        """Get all the known formats.
 
1582
 
 
1583
        Warning: This triggers a load of all lazy registered formats: do not
 
1584
        use except when that is desireed.
 
1585
        """
 
1586
        return format_registry._get_all()
 
1587
 
 
1588
    def get_reference(self, a_bzrdir, name=None):
1525
1589
        """Get the target reference of the branch in a_bzrdir.
1526
1590
 
1527
1591
        format probing must have been completed before calling
1529
1593
        in a_bzrdir is correct.
1530
1594
 
1531
1595
        :param a_bzrdir: The bzrdir to get the branch data from.
 
1596
        :param name: Name of the colocated branch to fetch
1532
1597
        :return: None if the branch is not a reference branch.
1533
1598
        """
1534
1599
        return None
1535
1600
 
1536
1601
    @classmethod
1537
 
    def set_reference(self, a_bzrdir, to_branch):
 
1602
    def set_reference(self, a_bzrdir, name, to_branch):
1538
1603
        """Set the target reference of the branch in a_bzrdir.
1539
1604
 
1540
1605
        format probing must have been completed before calling
1542
1607
        in a_bzrdir is correct.
1543
1608
 
1544
1609
        :param a_bzrdir: The bzrdir to set the branch reference for.
 
1610
        :param name: Name of colocated branch to set, None for default
1545
1611
        :param to_branch: branch that the checkout is to reference
1546
1612
        """
1547
1613
        raise NotImplementedError(self.set_reference)
1562
1628
        for hook in hooks:
1563
1629
            hook(params)
1564
1630
 
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):
 
1631
    def initialize(self, a_bzrdir, name=None, repository=None):
1611
1632
        """Create a branch of this format in a_bzrdir.
1612
1633
        
1613
1634
        :param name: Name of the colocated branch to create.
1647
1668
        """
1648
1669
        raise NotImplementedError(self.network_name)
1649
1670
 
1650
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1671
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
 
1672
            found_repository=None):
1651
1673
        """Return the branch object for a_bzrdir
1652
1674
 
1653
1675
        :param a_bzrdir: A BzrDir that contains a branch.
1660
1682
        raise NotImplementedError(self.open)
1661
1683
 
1662
1684
    @classmethod
 
1685
    @deprecated_method(deprecated_in((2, 4, 0)))
1663
1686
    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__)
 
1687
        """Register a metadir format.
 
1688
 
 
1689
        See MetaDirBranchFormatFactory for the ability to register a format
 
1690
        without loading the code the format needs until it is actually used.
 
1691
        """
 
1692
        format_registry.register(format)
1669
1693
 
1670
1694
    @classmethod
 
1695
    @deprecated_method(deprecated_in((2, 4, 0)))
1671
1696
    def set_default_format(klass, format):
1672
 
        klass._default_format = format
 
1697
        format_registry.set_default(format)
1673
1698
 
1674
1699
    def supports_set_append_revisions_only(self):
1675
1700
        """True if this format supports set_append_revisions_only."""
1679
1704
        """True if this format records a stacked-on branch."""
1680
1705
        return False
1681
1706
 
 
1707
    def supports_leaving_lock(self):
 
1708
        """True if this format supports leaving locks in place."""
 
1709
        return False # by default
 
1710
 
1682
1711
    @classmethod
 
1712
    @deprecated_method(deprecated_in((2, 4, 0)))
1683
1713
    def unregister_format(klass, format):
1684
 
        del klass._formats[format.get_format_string()]
 
1714
        format_registry.remove(format)
1685
1715
 
1686
1716
    def __str__(self):
1687
1717
        return self.get_format_description().rstrip()
1691
1721
        return False  # by default
1692
1722
 
1693
1723
 
 
1724
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
 
1725
    """A factory for a BranchFormat object, permitting simple lazy registration.
 
1726
    
 
1727
    While none of the built in BranchFormats are lazy registered yet,
 
1728
    bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
 
1729
    use it, and the bzr-loom plugin uses it as well (see
 
1730
    bzrlib.plugins.loom.formats).
 
1731
    """
 
1732
 
 
1733
    def __init__(self, format_string, module_name, member_name):
 
1734
        """Create a MetaDirBranchFormatFactory.
 
1735
 
 
1736
        :param format_string: The format string the format has.
 
1737
        :param module_name: Module to load the format class from.
 
1738
        :param member_name: Attribute name within the module for the format class.
 
1739
        """
 
1740
        registry._LazyObjectGetter.__init__(self, module_name, member_name)
 
1741
        self._format_string = format_string
 
1742
        
 
1743
    def get_format_string(self):
 
1744
        """See BranchFormat.get_format_string."""
 
1745
        return self._format_string
 
1746
 
 
1747
    def __call__(self):
 
1748
        """Used for network_format_registry support."""
 
1749
        return self.get_obj()()
 
1750
 
 
1751
 
1694
1752
class BranchHooks(Hooks):
1695
1753
    """A dictionary mapping hook name to a list of callables for branch hooks.
1696
1754
 
1704
1762
        These are all empty initially, because by default nothing should get
1705
1763
        notified.
1706
1764
        """
1707
 
        Hooks.__init__(self)
1708
 
        self.create_hook(HookPoint('set_rh',
 
1765
        Hooks.__init__(self, "bzrlib.branch", "Branch.hooks")
 
1766
        self.add_hook('set_rh',
1709
1767
            "Invoked whenever the revision history has been set via "
1710
1768
            "set_revision_history. The api signature is (branch, "
1711
1769
            "revision_history), and the branch will be write-locked. "
1712
1770
            "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',
 
1771
            "hook to use is Branch.post_change_branch_tip.", (0, 15))
 
1772
        self.add_hook('open',
1715
1773
            "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',
 
1774
            "branch is opened.", (1, 8))
 
1775
        self.add_hook('post_push',
1718
1776
            "Called after a push operation completes. post_push is called "
1719
1777
            "with a bzrlib.branch.BranchPushResult object and only runs in the "
1720
 
            "bzr client.", (0, 15), None))
1721
 
        self.create_hook(HookPoint('post_pull',
 
1778
            "bzr client.", (0, 15))
 
1779
        self.add_hook('post_pull',
1722
1780
            "Called after a pull operation completes. post_pull is called "
1723
1781
            "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 "
 
1782
            "bzr client.", (0, 15))
 
1783
        self.add_hook('pre_commit',
 
1784
            "Called after a commit is calculated but before it is "
1727
1785
            "completed. pre_commit is called with (local, master, old_revno, "
1728
1786
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
1729
1787
            "). old_revid is NULL_REVISION for the first commit to a branch, "
1731
1789
            "basis revision. hooks MUST NOT modify this delta. "
1732
1790
            " future_tree is an in-memory tree obtained from "
1733
1791
            "CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1734
 
            "tree.", (0,91), None))
1735
 
        self.create_hook(HookPoint('post_commit',
 
1792
            "tree.", (0,91))
 
1793
        self.add_hook('post_commit',
1736
1794
            "Called in the bzr client after a commit has completed. "
1737
1795
            "post_commit is called with (local, master, old_revno, old_revid, "
1738
1796
            "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',
 
1797
            "commit to a branch.", (0, 15))
 
1798
        self.add_hook('post_uncommit',
1741
1799
            "Called in the bzr client after an uncommit completes. "
1742
1800
            "post_uncommit is called with (local, master, old_revno, "
1743
1801
            "old_revid, new_revno, new_revid) where local is the local branch "
1744
1802
            "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',
 
1803
            "receives new_revno of 0, new_revid of None.", (0, 15))
 
1804
        self.add_hook('pre_change_branch_tip',
1747
1805
            "Called in bzr client and server before a change to the tip of a "
1748
1806
            "branch is made. pre_change_branch_tip is called with a "
1749
1807
            "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',
 
1808
            "commit, uncommit will all trigger this hook.", (1, 6))
 
1809
        self.add_hook('post_change_branch_tip',
1752
1810
            "Called in bzr client and server after a change to the tip of a "
1753
1811
            "branch is made. post_change_branch_tip is called with a "
1754
1812
            "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',
 
1813
            "commit, uncommit will all trigger this hook.", (1, 4))
 
1814
        self.add_hook('transform_fallback_location',
1757
1815
            "Called when a stacked branch is activating its fallback "
1758
1816
            "locations. transform_fallback_location is called with (branch, "
1759
1817
            "url), and should return a new url. Returning the same url "
1764
1822
            "fallback locations have not been activated. When there are "
1765
1823
            "multiple hooks installed for transform_fallback_location, "
1766
1824
            "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."
 
1825
            "The order is however undefined.", (1, 9))
 
1826
        self.add_hook('automatic_tag_name',
 
1827
            "Called to determine an automatic tag name for a revision. "
1770
1828
            "automatic_tag_name is called with (branch, revision_id) and "
1771
1829
            "should return a tag name or None if no tag name could be "
1772
1830
            "determined. The first non-None tag name returned will be used.",
1773
 
            (2, 2), None))
1774
 
        self.create_hook(HookPoint('post_branch_init',
 
1831
            (2, 2))
 
1832
        self.add_hook('post_branch_init',
1775
1833
            "Called after new branch initialization completes. "
1776
1834
            "post_branch_init is called with a "
1777
1835
            "bzrlib.branch.BranchInitHookParams. "
1778
1836
            "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',
 
1837
            "lightweight) will all trigger this hook.", (2, 2))
 
1838
        self.add_hook('post_switch',
1781
1839
            "Called after a checkout switches branch. "
1782
1840
            "post_switch is called with a "
1783
 
            "bzrlib.branch.SwitchHookParams.", (2, 2), None))
 
1841
            "bzrlib.branch.SwitchHookParams.", (2, 2))
1784
1842
 
1785
1843
 
1786
1844
 
1863
1921
        return self.__dict__ == other.__dict__
1864
1922
 
1865
1923
    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)
 
1924
        return "<%s of %s>" % (self.__class__.__name__, self.branch)
1872
1925
 
1873
1926
 
1874
1927
class SwitchHookParams(object):
1904
1957
            self.revision_id)
1905
1958
 
1906
1959
 
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
1960
class BranchFormatMetadir(BranchFormat):
1951
1961
    """Common logic for meta-dir based branch formats."""
1952
1962
 
1954
1964
        """What class to instantiate on open calls."""
1955
1965
        raise NotImplementedError(self._branch_class)
1956
1966
 
 
1967
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
 
1968
                           repository=None):
 
1969
        """Initialize a branch in a bzrdir, with specified files
 
1970
 
 
1971
        :param a_bzrdir: The bzrdir to initialize the branch in
 
1972
        :param utf8_files: The files to create as a list of
 
1973
            (filename, content) tuples
 
1974
        :param name: Name of colocated branch to create, if any
 
1975
        :return: a branch in this format
 
1976
        """
 
1977
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
 
1978
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
1979
        control_files = lockable_files.LockableFiles(branch_transport,
 
1980
            'lock', lockdir.LockDir)
 
1981
        control_files.create_lock()
 
1982
        control_files.lock_write()
 
1983
        try:
 
1984
            utf8_files += [('format', self.get_format_string())]
 
1985
            for (filename, content) in utf8_files:
 
1986
                branch_transport.put_bytes(
 
1987
                    filename, content,
 
1988
                    mode=a_bzrdir._get_file_mode())
 
1989
        finally:
 
1990
            control_files.unlock()
 
1991
        branch = self.open(a_bzrdir, name, _found=True,
 
1992
                found_repository=repository)
 
1993
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
 
1994
        return branch
 
1995
 
1957
1996
    def network_name(self):
1958
1997
        """A simple byte string uniquely identifying this format for RPC calls.
1959
1998
 
1961
2000
        """
1962
2001
        return self.get_format_string()
1963
2002
 
1964
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
2003
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
 
2004
            found_repository=None):
1965
2005
        """See BranchFormat.open()."""
1966
2006
        if not _found:
1967
2007
            format = BranchFormat.find_format(a_bzrdir, name=name)
1972
2012
        try:
1973
2013
            control_files = lockable_files.LockableFiles(transport, 'lock',
1974
2014
                                                         lockdir.LockDir)
 
2015
            if found_repository is None:
 
2016
                found_repository = a_bzrdir.find_repository()
1975
2017
            return self._branch_class()(_format=self,
1976
2018
                              _control_files=control_files,
1977
2019
                              name=name,
1978
2020
                              a_bzrdir=a_bzrdir,
1979
 
                              _repository=a_bzrdir.find_repository(),
 
2021
                              _repository=found_repository,
1980
2022
                              ignore_fallbacks=ignore_fallbacks)
1981
2023
        except errors.NoSuchFile:
1982
2024
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1989
2031
    def supports_tags(self):
1990
2032
        return True
1991
2033
 
 
2034
    def supports_leaving_lock(self):
 
2035
        return True
 
2036
 
1992
2037
 
1993
2038
class BzrBranchFormat5(BranchFormatMetadir):
1994
2039
    """Bzr branch format 5.
2014
2059
        """See BranchFormat.get_format_description()."""
2015
2060
        return "Branch format 5"
2016
2061
 
2017
 
    def initialize(self, a_bzrdir, name=None):
 
2062
    def initialize(self, a_bzrdir, name=None, repository=None):
2018
2063
        """Create a branch of this format in a_bzrdir."""
2019
2064
        utf8_files = [('revision-history', ''),
2020
2065
                      ('branch-name', ''),
2021
2066
                      ]
2022
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2067
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2023
2068
 
2024
2069
    def supports_tags(self):
2025
2070
        return False
2047
2092
        """See BranchFormat.get_format_description()."""
2048
2093
        return "Branch format 6"
2049
2094
 
2050
 
    def initialize(self, a_bzrdir, name=None):
 
2095
    def initialize(self, a_bzrdir, name=None, repository=None):
2051
2096
        """Create a branch of this format in a_bzrdir."""
2052
2097
        utf8_files = [('last-revision', '0 null:\n'),
2053
2098
                      ('branch.conf', ''),
2054
2099
                      ('tags', ''),
2055
2100
                      ]
2056
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2101
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2057
2102
 
2058
2103
    def make_tags(self, branch):
2059
2104
        """See bzrlib.branch.BranchFormat.make_tags()."""
2077
2122
        """See BranchFormat.get_format_description()."""
2078
2123
        return "Branch format 8"
2079
2124
 
2080
 
    def initialize(self, a_bzrdir, name=None):
 
2125
    def initialize(self, a_bzrdir, name=None, repository=None):
2081
2126
        """Create a branch of this format in a_bzrdir."""
2082
2127
        utf8_files = [('last-revision', '0 null:\n'),
2083
2128
                      ('branch.conf', ''),
2084
2129
                      ('tags', ''),
2085
2130
                      ('references', '')
2086
2131
                      ]
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()
 
2132
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2093
2133
 
2094
2134
    def make_tags(self, branch):
2095
2135
        """See bzrlib.branch.BranchFormat.make_tags()."""
2104
2144
    supports_reference_locations = True
2105
2145
 
2106
2146
 
2107
 
class BzrBranchFormat7(BzrBranchFormat8):
 
2147
class BzrBranchFormat7(BranchFormatMetadir):
2108
2148
    """Branch format with last-revision, tags, and a stacked location pointer.
2109
2149
 
2110
2150
    The stacked location pointer is passed down to the repository and requires
2113
2153
    This format was introduced in bzr 1.6.
2114
2154
    """
2115
2155
 
2116
 
    def initialize(self, a_bzrdir, name=None):
 
2156
    def initialize(self, a_bzrdir, name=None, repository=None):
2117
2157
        """Create a branch of this format in a_bzrdir."""
2118
2158
        utf8_files = [('last-revision', '0 null:\n'),
2119
2159
                      ('branch.conf', ''),
2120
2160
                      ('tags', ''),
2121
2161
                      ]
2122
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2162
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2123
2163
 
2124
2164
    def _branch_class(self):
2125
2165
        return BzrBranch7
2135
2175
    def supports_set_append_revisions_only(self):
2136
2176
        return True
2137
2177
 
 
2178
    def supports_stacking(self):
 
2179
        return True
 
2180
 
 
2181
    def make_tags(self, branch):
 
2182
        """See bzrlib.branch.BranchFormat.make_tags()."""
 
2183
        return BasicTags(branch)
 
2184
 
2138
2185
    supports_reference_locations = False
2139
2186
 
2140
2187
 
2157
2204
        """See BranchFormat.get_format_description()."""
2158
2205
        return "Checkout reference format 1"
2159
2206
 
2160
 
    def get_reference(self, a_bzrdir):
 
2207
    def get_reference(self, a_bzrdir, name=None):
2161
2208
        """See BranchFormat.get_reference()."""
2162
 
        transport = a_bzrdir.get_branch_transport(None)
 
2209
        transport = a_bzrdir.get_branch_transport(None, name=name)
2163
2210
        return transport.get_bytes('location')
2164
2211
 
2165
 
    def set_reference(self, a_bzrdir, to_branch):
 
2212
    def set_reference(self, a_bzrdir, name, to_branch):
2166
2213
        """See BranchFormat.set_reference()."""
2167
 
        transport = a_bzrdir.get_branch_transport(None)
 
2214
        transport = a_bzrdir.get_branch_transport(None, name=name)
2168
2215
        location = transport.put_bytes('location', to_branch.base)
2169
2216
 
2170
 
    def initialize(self, a_bzrdir, name=None, target_branch=None):
 
2217
    def initialize(self, a_bzrdir, name=None, target_branch=None,
 
2218
            repository=None):
2171
2219
        """Create a branch of this format in a_bzrdir."""
2172
2220
        if target_branch is None:
2173
2221
            # this format does not implement branch itself, thus the implicit
2201
2249
        return clone
2202
2250
 
2203
2251
    def open(self, a_bzrdir, name=None, _found=False, location=None,
2204
 
             possible_transports=None, ignore_fallbacks=False):
 
2252
             possible_transports=None, ignore_fallbacks=False,
 
2253
             found_repository=None):
2205
2254
        """Return the branch that the branch reference in a_bzrdir points at.
2206
2255
 
2207
2256
        :param a_bzrdir: A BzrDir that contains a branch.
2221
2270
                raise AssertionError("wrong format %r found for %r" %
2222
2271
                    (format, self))
2223
2272
        if location is None:
2224
 
            location = self.get_reference(a_bzrdir)
 
2273
            location = self.get_reference(a_bzrdir, name)
2225
2274
        real_bzrdir = bzrdir.BzrDir.open(
2226
2275
            location, possible_transports=possible_transports)
2227
2276
        result = real_bzrdir.open_branch(name=name, 
2238
2287
        return result
2239
2288
 
2240
2289
 
 
2290
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
 
2291
    """Branch format registry."""
 
2292
 
 
2293
    def __init__(self, other_registry=None):
 
2294
        super(BranchFormatRegistry, self).__init__(other_registry)
 
2295
        self._default_format = None
 
2296
 
 
2297
    def set_default(self, format):
 
2298
        self._default_format = format
 
2299
 
 
2300
    def get_default(self):
 
2301
        return self._default_format
 
2302
 
 
2303
 
2241
2304
network_format_registry = registry.FormatRegistry()
2242
2305
"""Registry of formats indexed by their network name.
2243
2306
 
2246
2309
BranchFormat.network_name() for more detail.
2247
2310
"""
2248
2311
 
 
2312
format_registry = BranchFormatRegistry(network_format_registry)
 
2313
 
2249
2314
 
2250
2315
# formats which have no format string are not discoverable
2251
2316
# and not independently creatable, so are not registered.
2253
2318
__format6 = BzrBranchFormat6()
2254
2319
__format7 = BzrBranchFormat7()
2255
2320
__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__)
 
2321
format_registry.register(__format5)
 
2322
format_registry.register(BranchReferenceFormat())
 
2323
format_registry.register(__format6)
 
2324
format_registry.register(__format7)
 
2325
format_registry.register(__format8)
 
2326
format_registry.set_default(__format7)
 
2327
 
 
2328
 
 
2329
class BranchWriteLockResult(LogicalLockResult):
 
2330
    """The result of write locking a branch.
 
2331
 
 
2332
    :ivar branch_token: The token obtained from the underlying branch lock, or
 
2333
        None.
 
2334
    :ivar unlock: A callable which will unlock the lock.
 
2335
    """
 
2336
 
 
2337
    def __init__(self, unlock, branch_token):
 
2338
        LogicalLockResult.__init__(self, unlock)
 
2339
        self.branch_token = branch_token
 
2340
 
 
2341
    def __repr__(self):
 
2342
        return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
 
2343
            self.unlock)
2266
2344
 
2267
2345
 
2268
2346
class BzrBranch(Branch, _RelockDebugMixin):
2324
2402
        return self.control_files.is_locked()
2325
2403
 
2326
2404
    def lock_write(self, token=None):
 
2405
        """Lock the branch for write operations.
 
2406
 
 
2407
        :param token: A token to permit reacquiring a previously held and
 
2408
            preserved lock.
 
2409
        :return: A BranchWriteLockResult.
 
2410
        """
2327
2411
        if not self.is_locked():
2328
2412
            self._note_lock('w')
2329
2413
        # All-in-one needs to always unlock/lock.
2335
2419
        else:
2336
2420
            took_lock = False
2337
2421
        try:
2338
 
            return self.control_files.lock_write(token=token)
 
2422
            return BranchWriteLockResult(self.unlock,
 
2423
                self.control_files.lock_write(token=token))
2339
2424
        except:
2340
2425
            if took_lock:
2341
2426
                self.repository.unlock()
2342
2427
            raise
2343
2428
 
2344
2429
    def lock_read(self):
 
2430
        """Lock the branch for read operations.
 
2431
 
 
2432
        :return: A bzrlib.lock.LogicalLockResult.
 
2433
        """
2345
2434
        if not self.is_locked():
2346
2435
            self._note_lock('r')
2347
2436
        # All-in-one needs to always unlock/lock.
2354
2443
            took_lock = False
2355
2444
        try:
2356
2445
            self.control_files.lock_read()
 
2446
            return LogicalLockResult(self.unlock)
2357
2447
        except:
2358
2448
            if took_lock:
2359
2449
                self.repository.unlock()
2396
2486
            'revision-history', '\n'.join(history),
2397
2487
            mode=self.bzrdir._get_file_mode())
2398
2488
 
2399
 
    @needs_write_lock
 
2489
    @deprecated_method(deprecated_in((2, 4, 0)))
2400
2490
    def set_revision_history(self, rev_history):
2401
2491
        """See Branch.set_revision_history."""
 
2492
        self._set_revision_history(rev_history)
 
2493
 
 
2494
    @needs_write_lock
 
2495
    def _set_revision_history(self, rev_history):
2402
2496
        if 'evil' in debug.debug_flags:
2403
2497
            mutter_callsite(3, "set_revision_history scales with history.")
2404
2498
        check_not_reserved_id = _mod_revision.check_not_reserved_id
2448
2542
            except ValueError:
2449
2543
                rev = self.repository.get_revision(revision_id)
2450
2544
                new_history = rev.get_history(self.repository)[1:]
2451
 
        destination.set_revision_history(new_history)
 
2545
        destination._set_revision_history(new_history)
2452
2546
 
2453
2547
    @needs_write_lock
2454
2548
    def set_last_revision_info(self, revno, revision_id):
2462
2556
        configured to check constraints on history, in which case this may not
2463
2557
        be permitted.
2464
2558
        """
2465
 
        revision_id = _mod_revision.ensure_null(revision_id)
 
2559
        if not revision_id or not isinstance(revision_id, basestring):
 
2560
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2466
2561
        # this old format stores the full history, but this api doesn't
2467
2562
        # provide it, so we must generate, and might as well check it's
2468
2563
        # correct
2469
2564
        history = self._lefthand_history(revision_id)
2470
2565
        if len(history) != revno:
2471
2566
            raise AssertionError('%d != %d' % (len(history), revno))
2472
 
        self.set_revision_history(history)
 
2567
        self._set_revision_history(history)
2473
2568
 
2474
2569
    def _gen_revision_history(self):
2475
2570
        history = self._transport.get_bytes('revision-history').split('\n')
2489
2584
        :param other_branch: The other branch that DivergedBranches should
2490
2585
            raise with respect to.
2491
2586
        """
2492
 
        self.set_revision_history(self._lefthand_history(revision_id,
 
2587
        self._set_revision_history(self._lefthand_history(revision_id,
2493
2588
            last_rev, other_branch))
2494
2589
 
2495
2590
    def basis_tree(self):
2505
2600
                pass
2506
2601
        return None
2507
2602
 
2508
 
    def _basic_push(self, target, overwrite, stop_revision):
2509
 
        """Basic implementation of push without bound branches or hooks.
2510
 
 
2511
 
        Must be called with source read locked and target write locked.
2512
 
        """
2513
 
        result = BranchPushResult()
2514
 
        result.source_branch = self
2515
 
        result.target_branch = target
2516
 
        result.old_revno, result.old_revid = target.last_revision_info()
2517
 
        self.update_references(target)
2518
 
        if result.old_revid != self.last_revision():
2519
 
            # We assume that during 'push' this repository is closer than
2520
 
            # the target.
2521
 
            graph = self.repository.get_graph(target.repository)
2522
 
            target.update_revisions(self, stop_revision,
2523
 
                overwrite=overwrite, graph=graph)
2524
 
        if self._push_should_merge_tags():
2525
 
            result.tag_conflicts = self.tags.merge_to(target.tags,
2526
 
                overwrite)
2527
 
        result.new_revno, result.new_revid = target.last_revision_info()
2528
 
        return result
2529
 
 
2530
2603
    def get_stacked_on_url(self):
2531
2604
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
2532
2605
 
2561
2634
        """Return the branch we are bound to.
2562
2635
 
2563
2636
        :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
2637
        """
 
2638
        if self._master_branch_cache is None:
 
2639
            self._master_branch_cache = self._get_master_branch(
 
2640
                possible_transports)
 
2641
        return self._master_branch_cache
 
2642
 
 
2643
    def _get_master_branch(self, possible_transports):
2570
2644
        bound_loc = self.get_bound_location()
2571
2645
        if not bound_loc:
2572
2646
            return None
2583
2657
 
2584
2658
        :param location: URL to the target branch
2585
2659
        """
 
2660
        self._master_branch_cache = None
2586
2661
        if location:
2587
2662
            self._transport.put_bytes('bound', location+'\n',
2588
2663
                mode=self.bzrdir._get_file_mode())
2697
2772
 
2698
2773
    @needs_write_lock
2699
2774
    def set_last_revision_info(self, revno, revision_id):
2700
 
        revision_id = _mod_revision.ensure_null(revision_id)
 
2775
        if not revision_id or not isinstance(revision_id, basestring):
 
2776
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2701
2777
        old_revno, old_revid = self.last_revision_info()
2702
2778
        if self._get_append_revisions_only():
2703
2779
            self._check_history_violation(revision_id)
2840
2916
 
2841
2917
    def set_bound_location(self, location):
2842
2918
        """See Branch.set_push_location."""
 
2919
        self._master_branch_cache = None
2843
2920
        result = None
2844
2921
        config = self.get_config()
2845
2922
        if location is None:
2922
2999
        try:
2923
3000
            index = self._partial_revision_history_cache.index(revision_id)
2924
3001
        except ValueError:
2925
 
            self._extend_partial_history(stop_revision=revision_id)
 
3002
            try:
 
3003
                self._extend_partial_history(stop_revision=revision_id)
 
3004
            except errors.RevisionNotPresent, e:
 
3005
                raise errors.GhostRevisionsHaveNoRevno(revision_id, e.revision_id)
2926
3006
            index = len(self._partial_revision_history_cache) - 1
2927
3007
            if self._partial_revision_history_cache[index] != revision_id:
2928
3008
                raise errors.NoSuchRevision(self, revision_id)
2983
3063
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
2984
3064
    """
2985
3065
 
 
3066
    @deprecated_method(deprecated_in((2, 3, 0)))
2986
3067
    def __int__(self):
2987
 
        # DEPRECATED: pull used to return the change in revno
 
3068
        """Return the relative change in revno.
 
3069
 
 
3070
        :deprecated: Use `new_revno` and `old_revno` instead.
 
3071
        """
2988
3072
        return self.new_revno - self.old_revno
2989
3073
 
2990
3074
    def report(self, to_file):
3015
3099
        target, otherwise it will be None.
3016
3100
    """
3017
3101
 
 
3102
    @deprecated_method(deprecated_in((2, 3, 0)))
3018
3103
    def __int__(self):
3019
 
        # DEPRECATED: push used to return the change in revno
 
3104
        """Return the relative change in revno.
 
3105
 
 
3106
        :deprecated: Use `new_revno` and `old_revno` instead.
 
3107
        """
3020
3108
        return self.new_revno - self.old_revno
3021
3109
 
3022
3110
    def report(self, to_file):
3145
3233
    _optimisers = []
3146
3234
    """The available optimised InterBranch types."""
3147
3235
 
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)
 
3236
    @classmethod
 
3237
    def _get_branch_formats_to_test(klass):
 
3238
        """Return an iterable of format tuples for testing.
 
3239
        
 
3240
        :return: An iterable of (from_format, to_format) to use when testing
 
3241
            this InterBranch class. Each InterBranch class should define this
 
3242
            method itself.
 
3243
        """
 
3244
        raise NotImplementedError(klass._get_branch_formats_to_test)
3152
3245
 
 
3246
    @needs_write_lock
3153
3247
    def pull(self, overwrite=False, stop_revision=None,
3154
3248
             possible_transports=None, local=False):
3155
3249
        """Mirror source into target branch.
3160
3254
        """
3161
3255
        raise NotImplementedError(self.pull)
3162
3256
 
3163
 
    def update_revisions(self, stop_revision=None, overwrite=False,
3164
 
                         graph=None):
3165
 
        """Pull in new perfect-fit revisions.
3166
 
 
3167
 
        :param stop_revision: Updated until the given revision
3168
 
        :param overwrite: Always set the branch pointer, rather than checking
3169
 
            to see if it is a proper descendant.
3170
 
        :param graph: A Graph object that can be used to query history
3171
 
            information. This can be None.
3172
 
        :return: None
3173
 
        """
3174
 
        raise NotImplementedError(self.update_revisions)
3175
 
 
 
3257
    @needs_write_lock
3176
3258
    def push(self, overwrite=False, stop_revision=None,
3177
3259
             _override_hook_source_branch=None):
3178
3260
        """Mirror the source branch into the target branch.
3181
3263
        """
3182
3264
        raise NotImplementedError(self.push)
3183
3265
 
 
3266
    @needs_write_lock
 
3267
    def copy_content_into(self, revision_id=None):
 
3268
        """Copy the content of source into target
 
3269
 
 
3270
        revision_id: if not None, the revision history in the new branch will
 
3271
                     be truncated to end with revision_id.
 
3272
        """
 
3273
        raise NotImplementedError(self.copy_content_into)
 
3274
 
 
3275
    @needs_write_lock
 
3276
    def fetch(self, stop_revision=None):
 
3277
        """Fetch revisions.
 
3278
 
 
3279
        :param stop_revision: Last revision to fetch
 
3280
        """
 
3281
        raise NotImplementedError(self.fetch)
 
3282
 
3184
3283
 
3185
3284
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
 
 
3193
 
    def update_revisions(self, stop_revision=None, overwrite=False,
3194
 
        graph=None):
3195
 
        """See InterBranch.update_revisions()."""
 
3285
    """InterBranch implementation that uses public Branch functions."""
 
3286
 
 
3287
    @classmethod
 
3288
    def is_compatible(klass, source, target):
 
3289
        # GenericBranch uses the public API, so always compatible
 
3290
        return True
 
3291
 
 
3292
    @classmethod
 
3293
    def _get_branch_formats_to_test(klass):
 
3294
        return [(format_registry.get_default(), format_registry.get_default())]
 
3295
 
 
3296
    @classmethod
 
3297
    def unwrap_format(klass, format):
 
3298
        if isinstance(format, remote.RemoteBranchFormat):
 
3299
            format._ensure_real()
 
3300
            return format._custom_format
 
3301
        return format
 
3302
 
 
3303
    @needs_write_lock
 
3304
    def copy_content_into(self, revision_id=None):
 
3305
        """Copy the content of source into target
 
3306
 
 
3307
        revision_id: if not None, the revision history in the new branch will
 
3308
                     be truncated to end with revision_id.
 
3309
        """
 
3310
        self.source.update_references(self.target)
 
3311
        self.source._synchronize_history(self.target, revision_id)
 
3312
        try:
 
3313
            parent = self.source.get_parent()
 
3314
        except errors.InaccessibleParent, e:
 
3315
            mutter('parent was not accessible to copy: %s', e)
 
3316
        else:
 
3317
            if parent:
 
3318
                self.target.set_parent(parent)
 
3319
        if self.source._push_should_merge_tags():
 
3320
            self.source.tags.merge_to(self.target.tags)
 
3321
 
 
3322
    @needs_write_lock
 
3323
    def fetch(self, stop_revision=None):
 
3324
        if self.target.base == self.source.base:
 
3325
            return (0, [])
3196
3326
        self.source.lock_read()
3197
3327
        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)
 
3328
            fetch_spec_factory = fetch.FetchSpecFactory()
 
3329
            fetch_spec_factory.source_branch = self.source
 
3330
            fetch_spec_factory.source_branch_stop_revision_id = stop_revision
 
3331
            fetch_spec_factory.source_repo = self.source.repository
 
3332
            fetch_spec_factory.target_repo = self.target.repository
 
3333
            fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
 
3334
            fetch_spec = fetch_spec_factory.make_fetch_spec()
 
3335
            return self.target.repository.fetch(self.source.repository,
 
3336
                fetch_spec=fetch_spec)
3233
3337
        finally:
3234
3338
            self.source.unlock()
3235
3339
 
 
3340
    @needs_write_lock
 
3341
    def _update_revisions(self, stop_revision=None, overwrite=False,
 
3342
            graph=None):
 
3343
        other_revno, other_last_revision = self.source.last_revision_info()
 
3344
        stop_revno = None # unknown
 
3345
        if stop_revision is None:
 
3346
            stop_revision = other_last_revision
 
3347
            if _mod_revision.is_null(stop_revision):
 
3348
                # if there are no commits, we're done.
 
3349
                return
 
3350
            stop_revno = other_revno
 
3351
 
 
3352
        # what's the current last revision, before we fetch [and change it
 
3353
        # possibly]
 
3354
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
3355
        # we fetch here so that we don't process data twice in the common
 
3356
        # case of having something to pull, and so that the check for
 
3357
        # already merged can operate on the just fetched graph, which will
 
3358
        # be cached in memory.
 
3359
        self.fetch(stop_revision=stop_revision)
 
3360
        # Check to see if one is an ancestor of the other
 
3361
        if not overwrite:
 
3362
            if graph is None:
 
3363
                graph = self.target.repository.get_graph()
 
3364
            if self.target._check_if_descendant_or_diverged(
 
3365
                    stop_revision, last_rev, graph, self.source):
 
3366
                # stop_revision is a descendant of last_rev, but we aren't
 
3367
                # overwriting, so we're done.
 
3368
                return
 
3369
        if stop_revno is None:
 
3370
            if graph is None:
 
3371
                graph = self.target.repository.get_graph()
 
3372
            this_revno, this_last_revision = \
 
3373
                    self.target.last_revision_info()
 
3374
            stop_revno = graph.find_distance_to_null(stop_revision,
 
3375
                            [(other_last_revision, other_revno),
 
3376
                             (this_last_revision, this_revno)])
 
3377
        self.target.set_last_revision_info(stop_revno, stop_revision)
 
3378
 
 
3379
    @needs_write_lock
3236
3380
    def pull(self, overwrite=False, stop_revision=None,
3237
 
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3381
             possible_transports=None, run_hooks=True,
3238
3382
             _override_hook_target=None, local=False):
3239
 
        """See Branch.pull.
 
3383
        """Pull from source into self, updating my master if any.
3240
3384
 
3241
 
        :param _hook_master: Private parameter - set the branch to
3242
 
            be supplied as the master to pull hooks.
3243
3385
        :param run_hooks: Private parameter - if false, this branch
3244
3386
            is being called because it's the master of the primary branch,
3245
3387
            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
3388
        """
3250
 
        # This type of branch can't be bound.
3251
 
        if local:
 
3389
        bound_location = self.target.get_bound_location()
 
3390
        if local and not bound_location:
3252
3391
            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()
 
3392
        master_branch = None
 
3393
        source_is_master = (self.source.user_url == bound_location)
 
3394
        if not local and bound_location and not source_is_master:
 
3395
            # not pulling from master, so we need to update master.
 
3396
            master_branch = self.target.get_master_branch(possible_transports)
 
3397
            master_branch.lock_write()
3260
3398
        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)
 
3399
            if master_branch:
 
3400
                # pull from source into master.
 
3401
                master_branch.pull(self.source, overwrite, stop_revision,
 
3402
                    run_hooks=False)
 
3403
            return self._pull(overwrite,
 
3404
                stop_revision, _hook_master=master_branch,
 
3405
                run_hooks=run_hooks,
 
3406
                _override_hook_target=_override_hook_target,
 
3407
                merge_tags_to_master=not source_is_master)
3287
3408
        finally:
3288
 
            self.source.unlock()
3289
 
        return result
 
3409
            if master_branch:
 
3410
                master_branch.unlock()
3290
3411
 
3291
3412
    def push(self, overwrite=False, stop_revision=None,
3292
3413
             _override_hook_source_branch=None):
3310
3431
        finally:
3311
3432
            self.source.unlock()
3312
3433
 
 
3434
    def _basic_push(self, overwrite, stop_revision):
 
3435
        """Basic implementation of push without bound branches or hooks.
 
3436
 
 
3437
        Must be called with source read locked and target write locked.
 
3438
        """
 
3439
        result = BranchPushResult()
 
3440
        result.source_branch = self.source
 
3441
        result.target_branch = self.target
 
3442
        result.old_revno, result.old_revid = self.target.last_revision_info()
 
3443
        self.source.update_references(self.target)
 
3444
        if result.old_revid != stop_revision:
 
3445
            # We assume that during 'push' this repository is closer than
 
3446
            # the target.
 
3447
            graph = self.source.repository.get_graph(self.target.repository)
 
3448
            self._update_revisions(stop_revision, overwrite=overwrite,
 
3449
                    graph=graph)
 
3450
        if self.source._push_should_merge_tags():
 
3451
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
3452
                overwrite)
 
3453
        result.new_revno, result.new_revid = self.target.last_revision_info()
 
3454
        return result
 
3455
 
3313
3456
    def _push_with_bound_branches(self, overwrite, stop_revision,
3314
3457
            _override_hook_source_branch=None):
3315
3458
        """Push from source into target, and into target's master if any.
3330
3473
            master_branch.lock_write()
3331
3474
            try:
3332
3475
                # push into the master from the source branch.
3333
 
                self.source._basic_push(master_branch, overwrite, stop_revision)
3334
 
                # and push into the target branch from the source. Note that we
3335
 
                # push from the source branch again, because its considered the
3336
 
                # highest bandwidth repository.
3337
 
                result = self.source._basic_push(self.target, overwrite,
3338
 
                    stop_revision)
 
3476
                master_inter = InterBranch.get(self.source, master_branch)
 
3477
                master_inter._basic_push(overwrite, stop_revision)
 
3478
                # and push into the target branch from the source. Note that
 
3479
                # we push from the source branch again, because it's considered
 
3480
                # the highest bandwidth repository.
 
3481
                result = self._basic_push(overwrite, stop_revision)
3339
3482
                result.master_branch = master_branch
3340
3483
                result.local_branch = self.target
3341
3484
                _run_hooks()
3344
3487
                master_branch.unlock()
3345
3488
        else:
3346
3489
            # no master branch
3347
 
            result = self.source._basic_push(self.target, overwrite,
3348
 
                stop_revision)
 
3490
            result = self._basic_push(overwrite, stop_revision)
3349
3491
            # TODO: Why set master_branch and local_branch if there's no
3350
3492
            # binding?  Maybe cleaner to just leave them unset? -- mbp
3351
3493
            # 20070504
3354
3496
            _run_hooks()
3355
3497
            return result
3356
3498
 
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
 
 
 
3499
    def _pull(self, overwrite=False, stop_revision=None,
 
3500
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3501
             _override_hook_target=None, local=False,
 
3502
             merge_tags_to_master=True):
 
3503
        """See Branch.pull.
 
3504
 
 
3505
        This function is the core worker, used by GenericInterBranch.pull to
 
3506
        avoid duplication when pulling source->master and source->local.
 
3507
 
 
3508
        :param _hook_master: Private parameter - set the branch to
 
3509
            be supplied as the master to pull hooks.
3374
3510
        :param run_hooks: Private parameter - if false, this branch
3375
3511
            is being called because it's the master of the primary branch,
3376
3512
            so it should not run its hooks.
 
3513
            is being called because it's the master of the primary branch,
 
3514
            so it should not run its hooks.
 
3515
        :param _override_hook_target: Private parameter - set the branch to be
 
3516
            supplied as the target_branch to pull hooks.
 
3517
        :param local: Only update the local branch, and not the bound branch.
3377
3518
        """
3378
 
        bound_location = self.target.get_bound_location()
3379
 
        if local and not bound_location:
 
3519
        # This type of branch can't be bound.
 
3520
        if local:
3380
3521
            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()
 
3522
        result = PullResult()
 
3523
        result.source_branch = self.source
 
3524
        if _override_hook_target is None:
 
3525
            result.target_branch = self.target
 
3526
        else:
 
3527
            result.target_branch = _override_hook_target
 
3528
        self.source.lock_read()
3386
3529
        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)
 
3530
            # We assume that during 'pull' the target repository is closer than
 
3531
            # the source one.
 
3532
            self.source.update_references(self.target)
 
3533
            graph = self.target.repository.get_graph(self.source.repository)
 
3534
            # TODO: Branch formats should have a flag that indicates 
 
3535
            # that revno's are expensive, and pull() should honor that flag.
 
3536
            # -- JRV20090506
 
3537
            result.old_revno, result.old_revid = \
 
3538
                self.target.last_revision_info()
 
3539
            self._update_revisions(stop_revision, overwrite=overwrite,
 
3540
                graph=graph)
 
3541
            # TODO: The old revid should be specified when merging tags, 
 
3542
            # so a tags implementation that versions tags can only 
 
3543
            # pull in the most recent changes. -- JRV20090506
 
3544
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
3545
                overwrite, ignore_master=not merge_tags_to_master)
 
3546
            result.new_revno, result.new_revid = self.target.last_revision_info()
 
3547
            if _hook_master:
 
3548
                result.master_branch = _hook_master
 
3549
                result.local_branch = result.target_branch
 
3550
            else:
 
3551
                result.master_branch = result.target_branch
 
3552
                result.local_branch = None
 
3553
            if run_hooks:
 
3554
                for hook in Branch.hooks['post_pull']:
 
3555
                    hook(result)
3395
3556
        finally:
3396
 
            if master_branch:
3397
 
                master_branch.unlock()
 
3557
            self.source.unlock()
 
3558
        return result
3398
3559
 
3399
3560
 
3400
3561
InterBranch.register_optimiser(GenericInterBranch)
3401
 
InterBranch.register_optimiser(InterToBranch5)