/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Jelmer Vernooij
  • Date: 2011-03-22 12:10:34 UTC
  • mto: This revision was merged to the branch mainline in revision 5737.
  • Revision ID: jelmer@samba.org-20110322121034-70a7037sqrs2l2no
Rename check_status -> check_support_status.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005-2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
27
27
        config as _mod_config,
28
28
        debug,
29
29
        errors,
 
30
        fetch,
 
31
        graph as _mod_graph,
30
32
        lockdir,
31
33
        lockable_files,
 
34
        remote,
32
35
        repository,
33
36
        revision as _mod_revision,
34
37
        rio,
46
49
    )
47
50
""")
48
51
 
49
 
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
 
52
from bzrlib import (
 
53
    controldir,
 
54
    )
 
55
from bzrlib.decorators import (
 
56
    needs_read_lock,
 
57
    needs_write_lock,
 
58
    only_raises,
 
59
    )
50
60
from bzrlib.hooks import HookPoint, Hooks
51
61
from bzrlib.inter import InterObject
52
 
from bzrlib.lock import _RelockDebugMixin
 
62
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
53
63
from bzrlib import registry
54
64
from bzrlib.symbol_versioning import (
55
65
    deprecated_in,
63
73
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
64
74
 
65
75
 
66
 
class Branch(bzrdir.ControlComponent):
 
76
class Branch(controldir.ControlComponent):
67
77
    """Branch holding a history of revisions.
68
78
 
69
79
    :ivar base:
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
94
105
        self._merge_sorted_revisions_cache = None
95
106
        self._open_hook()
102
113
 
103
114
    def _activate_fallback_location(self, url):
104
115
        """Activate the branch/repository from url as a fallback repository."""
 
116
        for existing_fallback_repo in self.repository._fallback_repositories:
 
117
            if existing_fallback_repo.user_url == url:
 
118
                # This fallback is already configured.  This probably only
 
119
                # happens because BzrDir.sprout is a horrible mess.  To avoid
 
120
                # confusing _unstack we don't add this a second time.
 
121
                mutter('duplicate activation of fallback %r on %r', url, self)
 
122
                return
105
123
        repo = self._get_fallback_repository(url)
106
124
        if repo.has_same_location(self.repository):
107
125
            raise errors.UnstackableLocationError(self.user_url, url)
197
215
        return self.supports_tags() and self.tags.get_tag_dict()
198
216
 
199
217
    def get_config(self):
 
218
        """Get a bzrlib.config.BranchConfig for this Branch.
 
219
 
 
220
        This can then be used to get and set configuration options for the
 
221
        branch.
 
222
 
 
223
        :return: A bzrlib.config.BranchConfig.
 
224
        """
200
225
        return BranchConfig(self)
201
226
 
202
227
    def _get_config(self):
218
243
            possible_transports=[self.bzrdir.root_transport])
219
244
        return a_branch.repository
220
245
 
 
246
    @needs_read_lock
221
247
    def _get_tags_bytes(self):
222
248
        """Get the bytes of a serialised tags dict.
223
249
 
230
256
        :return: The bytes of the tags file.
231
257
        :seealso: Branch._set_tags_bytes.
232
258
        """
233
 
        return self._transport.get_bytes('tags')
 
259
        if self._tags_bytes is None:
 
260
            self._tags_bytes = self._transport.get_bytes('tags')
 
261
        return self._tags_bytes
234
262
 
235
263
    def _get_nick(self, local=False, possible_transports=None):
236
264
        config = self.get_config()
238
266
        if not local and not config.has_explicit_nickname():
239
267
            try:
240
268
                master = self.get_master_branch(possible_transports)
 
269
                if master and self.user_url == master.user_url:
 
270
                    raise errors.RecursiveBind(self.user_url)
241
271
                if master is not None:
242
272
                    # return the master branch value
243
273
                    return master.nick
 
274
            except errors.RecursiveBind, e:
 
275
                raise e
244
276
            except errors.BzrError, e:
245
277
                # Silently fall back to local implicit nick if the master is
246
278
                # unavailable
283
315
        new_history.reverse()
284
316
        return new_history
285
317
 
286
 
    def lock_write(self):
 
318
    def lock_write(self, token=None):
 
319
        """Lock the branch for write operations.
 
320
 
 
321
        :param token: A token to permit reacquiring a previously held and
 
322
            preserved lock.
 
323
        :return: A BranchWriteLockResult.
 
324
        """
287
325
        raise NotImplementedError(self.lock_write)
288
326
 
289
327
    def lock_read(self):
 
328
        """Lock the branch for read operations.
 
329
 
 
330
        :return: A bzrlib.lock.LogicalLockResult.
 
331
        """
290
332
        raise NotImplementedError(self.lock_read)
291
333
 
292
334
    def unlock(self):
626
668
        raise errors.UnsupportedOperation(self.get_reference_info, self)
627
669
 
628
670
    @needs_write_lock
629
 
    def fetch(self, from_branch, last_revision=None, pb=None):
 
671
    def fetch(self, from_branch, last_revision=None, fetch_spec=None):
630
672
        """Copy revisions from from_branch into this branch.
631
673
 
632
674
        :param from_branch: Where to copy from.
633
675
        :param last_revision: What revision to stop at (None for at the end
634
676
                              of the branch.
635
 
        :param pb: An optional progress bar to use.
 
677
        :param fetch_spec: If specified, a SearchResult or
 
678
            PendingAncestryResult that describes which revisions to copy.  This
 
679
            allows copying multiple heads at once.  Mutually exclusive with
 
680
            last_revision.
636
681
        :return: None
637
682
        """
 
683
        if fetch_spec is not None and last_revision is not None:
 
684
            raise AssertionError(
 
685
                "fetch_spec and last_revision are mutually exclusive.")
638
686
        if self.base == from_branch.base:
639
687
            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
688
        from_branch.lock_read()
645
689
        try:
646
 
            if last_revision is None:
 
690
            if last_revision is None and fetch_spec is None:
647
691
                last_revision = from_branch.last_revision()
648
692
                last_revision = _mod_revision.ensure_null(last_revision)
649
693
            return self.repository.fetch(from_branch.repository,
650
694
                                         revision_id=last_revision,
651
 
                                         pb=pb)
 
695
                                         fetch_spec=fetch_spec)
652
696
        finally:
653
697
            from_branch.unlock()
654
698
 
767
811
 
768
812
    def _unstack(self):
769
813
        """Change a branch to be unstacked, copying data as needed.
770
 
        
 
814
 
771
815
        Don't call this directly, use set_stacked_on_url(None).
772
816
        """
773
817
        pb = ui.ui_factory.nested_progress_bar()
782
826
            old_repository = self.repository
783
827
            if len(old_repository._fallback_repositories) != 1:
784
828
                raise AssertionError("can't cope with fallback repositories "
785
 
                    "of %r" % (self.repository,))
786
 
            # unlock it, including unlocking the fallback
 
829
                    "of %r (fallbacks: %r)" % (old_repository,
 
830
                        old_repository._fallback_repositories))
 
831
            # Open the new repository object.
 
832
            # Repositories don't offer an interface to remove fallback
 
833
            # repositories today; take the conceptually simpler option and just
 
834
            # reopen it.  We reopen it starting from the URL so that we
 
835
            # get a separate connection for RemoteRepositories and can
 
836
            # stream from one of them to the other.  This does mean doing
 
837
            # separate SSH connection setup, but unstacking is not a
 
838
            # common operation so it's tolerable.
 
839
            new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
 
840
            new_repository = new_bzrdir.find_repository()
 
841
            if new_repository._fallback_repositories:
 
842
                raise AssertionError("didn't expect %r to have "
 
843
                    "fallback_repositories"
 
844
                    % (self.repository,))
 
845
            # Replace self.repository with the new repository.
 
846
            # Do our best to transfer the lock state (i.e. lock-tokens and
 
847
            # lock count) of self.repository to the new repository.
 
848
            lock_token = old_repository.lock_write().repository_token
 
849
            self.repository = new_repository
 
850
            if isinstance(self, remote.RemoteBranch):
 
851
                # Remote branches can have a second reference to the old
 
852
                # repository that need to be replaced.
 
853
                if self._real_branch is not None:
 
854
                    self._real_branch.repository = new_repository
 
855
            self.repository.lock_write(token=lock_token)
 
856
            if lock_token is not None:
 
857
                old_repository.leave_lock_in_place()
787
858
            old_repository.unlock()
 
859
            if lock_token is not None:
 
860
                # XXX: self.repository.leave_lock_in_place() before this
 
861
                # function will not be preserved.  Fortunately that doesn't
 
862
                # affect the current default format (2a), and would be a
 
863
                # corner-case anyway.
 
864
                #  - Andrew Bennetts, 2010/06/30
 
865
                self.repository.dont_leave_lock_in_place()
 
866
            old_lock_count = 0
 
867
            while True:
 
868
                try:
 
869
                    old_repository.unlock()
 
870
                except errors.LockNotHeld:
 
871
                    break
 
872
                old_lock_count += 1
 
873
            if old_lock_count == 0:
 
874
                raise AssertionError(
 
875
                    'old_repository should have been locked at least once.')
 
876
            for i in range(old_lock_count-1):
 
877
                self.repository.lock_write()
 
878
            # Fetch from the old repository into the new.
788
879
            old_repository.lock_read()
789
880
            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
881
                # XXX: If you unstack a branch while it has a working tree
809
882
                # with a pending merge, the pending-merged revisions will no
810
883
                # 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)
 
884
                try:
 
885
                    tags_to_fetch = set(self.tags.get_reverse_tag_dict())
 
886
                except errors.TagsNotSupported:
 
887
                    tags_to_fetch = set()
 
888
                fetch_spec = _mod_graph.NotInOtherForRevs(self.repository,
 
889
                    old_repository, required_ids=[self.last_revision()],
 
890
                    if_present_ids=tags_to_fetch, find_ghosts=True).execute()
 
891
                self.repository.fetch(old_repository, fetch_spec=fetch_spec)
818
892
            finally:
819
893
                old_repository.unlock()
820
894
        finally:
825
899
 
826
900
        :seealso: Branch._get_tags_bytes.
827
901
        """
828
 
        return _run_with_write_locked_target(self, self._transport.put_bytes,
829
 
            'tags', bytes)
 
902
        return _run_with_write_locked_target(self, self._set_tags_bytes_locked,
 
903
                bytes)
 
904
 
 
905
    def _set_tags_bytes_locked(self, bytes):
 
906
        self._tags_bytes = bytes
 
907
        return self._transport.put_bytes('tags', bytes)
830
908
 
831
909
    def _cache_revision_history(self, rev_history):
832
910
        """Set the cached revision history to rev_history.
862
940
        self._merge_sorted_revisions_cache = None
863
941
        self._partial_revision_history_cache = []
864
942
        self._partial_revision_id_to_revno_cache = {}
 
943
        self._tags_bytes = None
865
944
 
866
945
    def _gen_revision_history(self):
867
946
        """Return sequence of revision hashes on to this branch.
928
1007
        else:
929
1008
            return (0, _mod_revision.NULL_REVISION)
930
1009
 
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
1010
    def update_revisions(self, other, stop_revision=None, overwrite=False,
956
 
                         graph=None):
 
1011
                         graph=None, fetch_tags=True):
957
1012
        """Pull in new perfect-fit revisions.
958
1013
 
959
1014
        :param other: Another Branch to pull from
962
1017
            to see if it is a proper descendant.
963
1018
        :param graph: A Graph object that can be used to query history
964
1019
            information. This can be None.
 
1020
        :param fetch_tags: Flag that specifies if tags from other should be
 
1021
            fetched too.
965
1022
        :return: None
966
1023
        """
967
1024
        return InterBranch.get(other, self).update_revisions(stop_revision,
968
 
            overwrite, graph)
 
1025
            overwrite, graph, fetch_tags=fetch_tags)
969
1026
 
 
1027
    @deprecated_method(deprecated_in((2, 4, 0)))
970
1028
    def import_last_revision_info(self, source_repo, revno, revid):
971
1029
        """Set the last revision info, importing from another repo if necessary.
972
1030
 
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
1031
        :param source_repo: Source repository to optionally fetch from
977
1032
        :param revno: Revision number of the new tip
978
1033
        :param revid: Revision id of the new tip
981
1036
            self.repository.fetch(source_repo, revision_id=revid)
982
1037
        self.set_last_revision_info(revno, revid)
983
1038
 
 
1039
    def import_last_revision_info_and_tags(self, source, revno, revid):
 
1040
        """Set the last revision info, importing from another repo if necessary.
 
1041
 
 
1042
        This is used by the bound branch code to upload a revision to
 
1043
        the master branch first before updating the tip of the local branch.
 
1044
        Revisions referenced by source's tags are also transferred.
 
1045
 
 
1046
        :param source: Source branch to optionally fetch from
 
1047
        :param revno: Revision number of the new tip
 
1048
        :param revid: Revision id of the new tip
 
1049
        """
 
1050
        if not self.repository.has_same_location(source.repository):
 
1051
            try:
 
1052
                tags_to_fetch = set(source.tags.get_reverse_tag_dict())
 
1053
            except errors.TagsNotSupported:
 
1054
                tags_to_fetch = set()
 
1055
            fetch_spec = _mod_graph.NotInOtherForRevs(self.repository,
 
1056
                source.repository, [revid],
 
1057
                if_present_ids=tags_to_fetch).execute()
 
1058
            self.repository.fetch(source.repository, fetch_spec=fetch_spec)
 
1059
        self.set_last_revision_info(revno, revid)
 
1060
 
984
1061
    def revision_id_to_revno(self, revision_id):
985
1062
        """Given a revision id, return its revno"""
986
1063
        if _mod_revision.is_null(revision_id):
1006
1083
            self._extend_partial_history(distance_from_last)
1007
1084
        return self._partial_revision_history_cache[distance_from_last]
1008
1085
 
1009
 
    @needs_write_lock
1010
1086
    def pull(self, source, overwrite=False, stop_revision=None,
1011
1087
             possible_transports=None, *args, **kwargs):
1012
1088
        """Mirror source into this branch.
1208
1284
        return result
1209
1285
 
1210
1286
    @needs_read_lock
1211
 
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None):
 
1287
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None,
 
1288
            repository=None):
1212
1289
        """Create a new line of development from the branch, into to_bzrdir.
1213
1290
 
1214
1291
        to_bzrdir controls the branch format.
1219
1296
        if (repository_policy is not None and
1220
1297
            repository_policy.requires_stacking()):
1221
1298
            to_bzrdir._format.require_stacking(_skip_repo=True)
1222
 
        result = to_bzrdir.create_branch()
 
1299
        result = to_bzrdir.create_branch(repository=repository)
1223
1300
        result.lock_write()
1224
1301
        try:
1225
1302
            if repository_policy is not None:
1255
1332
                revno = 1
1256
1333
        destination.set_last_revision_info(revno, revision_id)
1257
1334
 
1258
 
    @needs_read_lock
1259
1335
    def copy_content_into(self, destination, revision_id=None):
1260
1336
        """Copy the content of self into destination.
1261
1337
 
1262
1338
        revision_id: if not None, the revision history in the new branch will
1263
1339
                     be truncated to end with revision_id.
1264
1340
        """
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
        return InterBranch.get(self, destination).copy_content_into(
 
1342
            revision_id=revision_id)
1276
1343
 
1277
1344
    def update_references(self, target):
1278
1345
        if not getattr(self._format, 'supports_reference_locations', False):
1323
1390
        """Return the most suitable metadir for a checkout of this branch.
1324
1391
        Weaves are used if this branch's repository uses weaves.
1325
1392
        """
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
        format = self.repository.bzrdir.checkout_metadir()
 
1394
        format.set_branch_format(self._format)
1333
1395
        return format
1334
1396
 
1335
1397
    def create_clone_on_transport(self, to_transport, revision_id=None,
1336
 
        stacked_on=None, create_prefix=False, use_existing_dir=False):
 
1398
        stacked_on=None, create_prefix=False, use_existing_dir=False,
 
1399
        no_tree=None):
1337
1400
        """Create a clone of this branch and its bzrdir.
1338
1401
 
1339
1402
        :param to_transport: The transport to clone onto.
1346
1409
        """
1347
1410
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1348
1411
        # clone call. Or something. 20090224 RBC/spiv.
 
1412
        # XXX: Should this perhaps clone colocated branches as well, 
 
1413
        # rather than just the default branch? 20100319 JRV
1349
1414
        if revision_id is None:
1350
1415
            revision_id = self.last_revision()
1351
1416
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1352
1417
            revision_id=revision_id, stacked_on=stacked_on,
1353
 
            create_prefix=create_prefix, use_existing_dir=use_existing_dir)
 
1418
            create_prefix=create_prefix, use_existing_dir=use_existing_dir,
 
1419
            no_tree=no_tree)
1354
1420
        return dir_to.open_branch()
1355
1421
 
1356
1422
    def create_checkout(self, to_location, revision_id=None,
1471
1537
        else:
1472
1538
            raise AssertionError("invalid heads: %r" % (heads,))
1473
1539
 
1474
 
 
1475
 
class BranchFormat(object):
 
1540
    def heads_to_fetch(self):
 
1541
        """Return the heads that must and that should be fetched to copy this
 
1542
        branch into another repo.
 
1543
 
 
1544
        :returns: a 2-tuple of (must_fetch, if_present_fetch).  must_fetch is a
 
1545
            set of heads that must be fetched.  if_present_fetch is a set of
 
1546
            heads that must be fetched if present, but no error is necessary if
 
1547
            they are not present.
 
1548
        """
 
1549
        # For bzr native formats must_fetch is just the tip, and if_present_fetch
 
1550
        # are the tags.
 
1551
        must_fetch = set([self.last_revision()])
 
1552
        try:
 
1553
            if_present_fetch = set(self.tags.get_reverse_tag_dict())
 
1554
        except errors.TagsNotSupported:
 
1555
            if_present_fetch = set()
 
1556
        must_fetch.discard(_mod_revision.NULL_REVISION)
 
1557
        if_present_fetch.discard(_mod_revision.NULL_REVISION)
 
1558
        return must_fetch, if_present_fetch
 
1559
 
 
1560
 
 
1561
class BranchFormat(controldir.ControlComponentFormat):
1476
1562
    """An encapsulation of the initialization and open routines for a format.
1477
1563
 
1478
1564
    Formats provide three things:
1481
1567
     * an open routine.
1482
1568
 
1483
1569
    Formats are placed in an dict by their format string for reference
1484
 
    during branch opening. Its not required that these be instances, they
 
1570
    during branch opening. It's not required that these be instances, they
1485
1571
    can be classes themselves with class methods - it simply depends on
1486
1572
    whether state is needed for a given format or not.
1487
1573
 
1490
1576
    object will be created every time regardless.
1491
1577
    """
1492
1578
 
1493
 
    _default_format = None
1494
 
    """The default format used for new branches."""
1495
 
 
1496
 
    _formats = {}
1497
 
    """The known formats."""
1498
 
 
1499
1579
    can_set_append_revisions_only = True
1500
1580
 
1501
1581
    def __eq__(self, other):
1510
1590
        try:
1511
1591
            transport = a_bzrdir.get_branch_transport(None, name=name)
1512
1592
            format_string = transport.get_bytes("format")
1513
 
            return klass._formats[format_string]
 
1593
            return format_registry.get(format_string)
1514
1594
        except errors.NoSuchFile:
1515
1595
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1516
1596
        except KeyError:
1517
1597
            raise errors.UnknownFormatError(format=format_string, kind='branch')
1518
1598
 
1519
1599
    @classmethod
 
1600
    @deprecated_method(deprecated_in((2, 4, 0)))
1520
1601
    def get_default_format(klass):
1521
1602
        """Return the current default format."""
1522
 
        return klass._default_format
1523
 
 
1524
 
    def get_reference(self, a_bzrdir):
 
1603
        return format_registry.get_default()
 
1604
 
 
1605
    @classmethod
 
1606
    @deprecated_method(deprecated_in((2, 4, 0)))
 
1607
    def get_formats(klass):
 
1608
        """Get all the known formats.
 
1609
 
 
1610
        Warning: This triggers a load of all lazy registered formats: do not
 
1611
        use except when that is desireed.
 
1612
        """
 
1613
        return format_registry._get_all()
 
1614
 
 
1615
    def get_reference(self, a_bzrdir, name=None):
1525
1616
        """Get the target reference of the branch in a_bzrdir.
1526
1617
 
1527
1618
        format probing must have been completed before calling
1529
1620
        in a_bzrdir is correct.
1530
1621
 
1531
1622
        :param a_bzrdir: The bzrdir to get the branch data from.
 
1623
        :param name: Name of the colocated branch to fetch
1532
1624
        :return: None if the branch is not a reference branch.
1533
1625
        """
1534
1626
        return None
1535
1627
 
1536
1628
    @classmethod
1537
 
    def set_reference(self, a_bzrdir, to_branch):
 
1629
    def set_reference(self, a_bzrdir, name, to_branch):
1538
1630
        """Set the target reference of the branch in a_bzrdir.
1539
1631
 
1540
1632
        format probing must have been completed before calling
1542
1634
        in a_bzrdir is correct.
1543
1635
 
1544
1636
        :param a_bzrdir: The bzrdir to set the branch reference for.
 
1637
        :param name: Name of colocated branch to set, None for default
1545
1638
        :param to_branch: branch that the checkout is to reference
1546
1639
        """
1547
1640
        raise NotImplementedError(self.set_reference)
1563
1656
            hook(params)
1564
1657
 
1565
1658
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
1566
 
                           lock_type='metadir', set_format=True):
 
1659
                           repository=None):
1567
1660
        """Initialize a branch in a bzrdir, with specified files
1568
1661
 
1569
1662
        :param a_bzrdir: The bzrdir to initialize the branch in
1570
1663
        :param utf8_files: The files to create as a list of
1571
1664
            (filename, content) tuples
1572
1665
        :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
1666
        :return: a branch in this format
1577
1667
        """
1578
1668
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
1579
1669
        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
1670
        control_files = lockable_files.LockableFiles(branch_transport,
1586
 
            lock_name, lock_class)
 
1671
            'lock', lockdir.LockDir)
1587
1672
        control_files.create_lock()
 
1673
        control_files.lock_write()
1588
1674
        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
1675
            utf8_files += [('format', self.get_format_string())]
1598
 
        try:
1599
1676
            for (filename, content) in utf8_files:
1600
1677
                branch_transport.put_bytes(
1601
1678
                    filename, content,
1602
1679
                    mode=a_bzrdir._get_file_mode())
1603
1680
        finally:
1604
 
            if lock_taken:
1605
 
                control_files.unlock()
1606
 
        branch = self.open(a_bzrdir, name, _found=True)
 
1681
            control_files.unlock()
 
1682
        branch = self.open(a_bzrdir, name, _found=True,
 
1683
                found_repository=repository)
1607
1684
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
1608
1685
        return branch
1609
1686
 
1610
 
    def initialize(self, a_bzrdir, name=None):
 
1687
    def initialize(self, a_bzrdir, name=None, repository=None):
1611
1688
        """Create a branch of this format in a_bzrdir.
1612
1689
        
1613
1690
        :param name: Name of the colocated branch to create.
1647
1724
        """
1648
1725
        raise NotImplementedError(self.network_name)
1649
1726
 
1650
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1727
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
 
1728
            found_repository=None):
1651
1729
        """Return the branch object for a_bzrdir
1652
1730
 
1653
1731
        :param a_bzrdir: A BzrDir that contains a branch.
1660
1738
        raise NotImplementedError(self.open)
1661
1739
 
1662
1740
    @classmethod
 
1741
    @deprecated_method(deprecated_in((2, 4, 0)))
1663
1742
    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__)
 
1743
        """Register a metadir format.
 
1744
 
 
1745
        See MetaDirBranchFormatFactory for the ability to register a format
 
1746
        without loading the code the format needs until it is actually used.
 
1747
        """
 
1748
        format_registry.register(format)
1669
1749
 
1670
1750
    @classmethod
 
1751
    @deprecated_method(deprecated_in((2, 4, 0)))
1671
1752
    def set_default_format(klass, format):
1672
 
        klass._default_format = format
 
1753
        format_registry.set_default(format)
1673
1754
 
1674
1755
    def supports_set_append_revisions_only(self):
1675
1756
        """True if this format supports set_append_revisions_only."""
1679
1760
        """True if this format records a stacked-on branch."""
1680
1761
        return False
1681
1762
 
 
1763
    def supports_leaving_lock(self):
 
1764
        """True if this format supports leaving locks in place."""
 
1765
        return False # by default
 
1766
 
1682
1767
    @classmethod
 
1768
    @deprecated_method(deprecated_in((2, 4, 0)))
1683
1769
    def unregister_format(klass, format):
1684
 
        del klass._formats[format.get_format_string()]
 
1770
        format_registry.remove(format)
1685
1771
 
1686
1772
    def __str__(self):
1687
1773
        return self.get_format_description().rstrip()
1691
1777
        return False  # by default
1692
1778
 
1693
1779
 
 
1780
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
 
1781
    """A factory for a BranchFormat object, permitting simple lazy registration.
 
1782
    
 
1783
    While none of the built in BranchFormats are lazy registered yet,
 
1784
    bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
 
1785
    use it, and the bzr-loom plugin uses it as well (see
 
1786
    bzrlib.plugins.loom.formats).
 
1787
    """
 
1788
 
 
1789
    def __init__(self, format_string, module_name, member_name):
 
1790
        """Create a MetaDirBranchFormatFactory.
 
1791
 
 
1792
        :param format_string: The format string the format has.
 
1793
        :param module_name: Module to load the format class from.
 
1794
        :param member_name: Attribute name within the module for the format class.
 
1795
        """
 
1796
        registry._LazyObjectGetter.__init__(self, module_name, member_name)
 
1797
        self._format_string = format_string
 
1798
        
 
1799
    def get_format_string(self):
 
1800
        """See BranchFormat.get_format_string."""
 
1801
        return self._format_string
 
1802
 
 
1803
    def __call__(self):
 
1804
        """Used for network_format_registry support."""
 
1805
        return self.get_obj()()
 
1806
 
 
1807
 
1694
1808
class BranchHooks(Hooks):
1695
1809
    """A dictionary mapping hook name to a list of callables for branch hooks.
1696
1810
 
1723
1837
            "with a bzrlib.branch.PullResult object and only runs in the "
1724
1838
            "bzr client.", (0, 15), None))
1725
1839
        self.create_hook(HookPoint('pre_commit',
1726
 
            "Called after a commit is calculated but before it is is "
 
1840
            "Called after a commit is calculated but before it is "
1727
1841
            "completed. pre_commit is called with (local, master, old_revno, "
1728
1842
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
1729
1843
            "). old_revid is NULL_REVISION for the first commit to a branch, "
1766
1880
            "all are called with the url returned from the previous hook."
1767
1881
            "The order is however undefined.", (1, 9), None))
1768
1882
        self.create_hook(HookPoint('automatic_tag_name',
1769
 
            "Called to determine an automatic tag name for a revision."
 
1883
            "Called to determine an automatic tag name for a revision. "
1770
1884
            "automatic_tag_name is called with (branch, revision_id) and "
1771
1885
            "should return a tag name or None if no tag name could be "
1772
1886
            "determined. The first non-None tag name returned will be used.",
1863
1977
        return self.__dict__ == other.__dict__
1864
1978
 
1865
1979
    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)
 
1980
        return "<%s of %s>" % (self.__class__.__name__, self.branch)
1872
1981
 
1873
1982
 
1874
1983
class SwitchHookParams(object):
1904
2013
            self.revision_id)
1905
2014
 
1906
2015
 
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
2016
class BranchFormatMetadir(BranchFormat):
1951
2017
    """Common logic for meta-dir based branch formats."""
1952
2018
 
1961
2027
        """
1962
2028
        return self.get_format_string()
1963
2029
 
1964
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
2030
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
 
2031
            found_repository=None):
1965
2032
        """See BranchFormat.open()."""
1966
2033
        if not _found:
1967
2034
            format = BranchFormat.find_format(a_bzrdir, name=name)
1972
2039
        try:
1973
2040
            control_files = lockable_files.LockableFiles(transport, 'lock',
1974
2041
                                                         lockdir.LockDir)
 
2042
            if found_repository is None:
 
2043
                found_repository = a_bzrdir.find_repository()
1975
2044
            return self._branch_class()(_format=self,
1976
2045
                              _control_files=control_files,
1977
2046
                              name=name,
1978
2047
                              a_bzrdir=a_bzrdir,
1979
 
                              _repository=a_bzrdir.find_repository(),
 
2048
                              _repository=found_repository,
1980
2049
                              ignore_fallbacks=ignore_fallbacks)
1981
2050
        except errors.NoSuchFile:
1982
2051
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1989
2058
    def supports_tags(self):
1990
2059
        return True
1991
2060
 
 
2061
    def supports_leaving_lock(self):
 
2062
        return True
 
2063
 
1992
2064
 
1993
2065
class BzrBranchFormat5(BranchFormatMetadir):
1994
2066
    """Bzr branch format 5.
2014
2086
        """See BranchFormat.get_format_description()."""
2015
2087
        return "Branch format 5"
2016
2088
 
2017
 
    def initialize(self, a_bzrdir, name=None):
 
2089
    def initialize(self, a_bzrdir, name=None, repository=None):
2018
2090
        """Create a branch of this format in a_bzrdir."""
2019
2091
        utf8_files = [('revision-history', ''),
2020
2092
                      ('branch-name', ''),
2021
2093
                      ]
2022
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2094
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2023
2095
 
2024
2096
    def supports_tags(self):
2025
2097
        return False
2047
2119
        """See BranchFormat.get_format_description()."""
2048
2120
        return "Branch format 6"
2049
2121
 
2050
 
    def initialize(self, a_bzrdir, name=None):
 
2122
    def initialize(self, a_bzrdir, name=None, repository=None):
2051
2123
        """Create a branch of this format in a_bzrdir."""
2052
2124
        utf8_files = [('last-revision', '0 null:\n'),
2053
2125
                      ('branch.conf', ''),
2054
2126
                      ('tags', ''),
2055
2127
                      ]
2056
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2128
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2057
2129
 
2058
2130
    def make_tags(self, branch):
2059
2131
        """See bzrlib.branch.BranchFormat.make_tags()."""
2077
2149
        """See BranchFormat.get_format_description()."""
2078
2150
        return "Branch format 8"
2079
2151
 
2080
 
    def initialize(self, a_bzrdir, name=None):
 
2152
    def initialize(self, a_bzrdir, name=None, repository=None):
2081
2153
        """Create a branch of this format in a_bzrdir."""
2082
2154
        utf8_files = [('last-revision', '0 null:\n'),
2083
2155
                      ('branch.conf', ''),
2084
2156
                      ('tags', ''),
2085
2157
                      ('references', '')
2086
2158
                      ]
2087
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2159
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2088
2160
 
2089
2161
    def __init__(self):
2090
2162
        super(BzrBranchFormat8, self).__init__()
2113
2185
    This format was introduced in bzr 1.6.
2114
2186
    """
2115
2187
 
2116
 
    def initialize(self, a_bzrdir, name=None):
 
2188
    def initialize(self, a_bzrdir, name=None, repository=None):
2117
2189
        """Create a branch of this format in a_bzrdir."""
2118
2190
        utf8_files = [('last-revision', '0 null:\n'),
2119
2191
                      ('branch.conf', ''),
2120
2192
                      ('tags', ''),
2121
2193
                      ]
2122
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2194
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2123
2195
 
2124
2196
    def _branch_class(self):
2125
2197
        return BzrBranch7
2157
2229
        """See BranchFormat.get_format_description()."""
2158
2230
        return "Checkout reference format 1"
2159
2231
 
2160
 
    def get_reference(self, a_bzrdir):
 
2232
    def get_reference(self, a_bzrdir, name=None):
2161
2233
        """See BranchFormat.get_reference()."""
2162
 
        transport = a_bzrdir.get_branch_transport(None)
 
2234
        transport = a_bzrdir.get_branch_transport(None, name=name)
2163
2235
        return transport.get_bytes('location')
2164
2236
 
2165
 
    def set_reference(self, a_bzrdir, to_branch):
 
2237
    def set_reference(self, a_bzrdir, name, to_branch):
2166
2238
        """See BranchFormat.set_reference()."""
2167
 
        transport = a_bzrdir.get_branch_transport(None)
 
2239
        transport = a_bzrdir.get_branch_transport(None, name=name)
2168
2240
        location = transport.put_bytes('location', to_branch.base)
2169
2241
 
2170
 
    def initialize(self, a_bzrdir, name=None, target_branch=None):
 
2242
    def initialize(self, a_bzrdir, name=None, target_branch=None,
 
2243
            repository=None):
2171
2244
        """Create a branch of this format in a_bzrdir."""
2172
2245
        if target_branch is None:
2173
2246
            # this format does not implement branch itself, thus the implicit
2201
2274
        return clone
2202
2275
 
2203
2276
    def open(self, a_bzrdir, name=None, _found=False, location=None,
2204
 
             possible_transports=None, ignore_fallbacks=False):
 
2277
             possible_transports=None, ignore_fallbacks=False,
 
2278
             found_repository=None):
2205
2279
        """Return the branch that the branch reference in a_bzrdir points at.
2206
2280
 
2207
2281
        :param a_bzrdir: A BzrDir that contains a branch.
2221
2295
                raise AssertionError("wrong format %r found for %r" %
2222
2296
                    (format, self))
2223
2297
        if location is None:
2224
 
            location = self.get_reference(a_bzrdir)
 
2298
            location = self.get_reference(a_bzrdir, name)
2225
2299
        real_bzrdir = bzrdir.BzrDir.open(
2226
2300
            location, possible_transports=possible_transports)
2227
2301
        result = real_bzrdir.open_branch(name=name, 
2238
2312
        return result
2239
2313
 
2240
2314
 
 
2315
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
 
2316
    """Branch format registry."""
 
2317
 
 
2318
    def __init__(self, other_registry=None):
 
2319
        super(BranchFormatRegistry, self).__init__(other_registry)
 
2320
        self._default_format = None
 
2321
 
 
2322
    def set_default(self, format):
 
2323
        self._default_format = format
 
2324
 
 
2325
    def get_default(self):
 
2326
        return self._default_format
 
2327
 
 
2328
 
2241
2329
network_format_registry = registry.FormatRegistry()
2242
2330
"""Registry of formats indexed by their network name.
2243
2331
 
2246
2334
BranchFormat.network_name() for more detail.
2247
2335
"""
2248
2336
 
 
2337
format_registry = BranchFormatRegistry(network_format_registry)
 
2338
 
2249
2339
 
2250
2340
# formats which have no format string are not discoverable
2251
2341
# and not independently creatable, so are not registered.
2253
2343
__format6 = BzrBranchFormat6()
2254
2344
__format7 = BzrBranchFormat7()
2255
2345
__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__)
 
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
format_registry.register_extra_lazy("bzrlib.branch_weave",
 
2353
    "BzrBranchFormat4")
 
2354
network_format_registry.register_lazy("Bazaar-NG branch, format 6\n",
 
2355
    "bzrlib.branch_weave", "BzrBranchFormat4")
 
2356
 
 
2357
 
 
2358
class BranchWriteLockResult(LogicalLockResult):
 
2359
    """The result of write locking a branch.
 
2360
 
 
2361
    :ivar branch_token: The token obtained from the underlying branch lock, or
 
2362
        None.
 
2363
    :ivar unlock: A callable which will unlock the lock.
 
2364
    """
 
2365
 
 
2366
    def __init__(self, unlock, branch_token):
 
2367
        LogicalLockResult.__init__(self, unlock)
 
2368
        self.branch_token = branch_token
 
2369
 
 
2370
    def __repr__(self):
 
2371
        return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
 
2372
            self.unlock)
2266
2373
 
2267
2374
 
2268
2375
class BzrBranch(Branch, _RelockDebugMixin):
2324
2431
        return self.control_files.is_locked()
2325
2432
 
2326
2433
    def lock_write(self, token=None):
 
2434
        """Lock the branch for write operations.
 
2435
 
 
2436
        :param token: A token to permit reacquiring a previously held and
 
2437
            preserved lock.
 
2438
        :return: A BranchWriteLockResult.
 
2439
        """
2327
2440
        if not self.is_locked():
2328
2441
            self._note_lock('w')
2329
2442
        # All-in-one needs to always unlock/lock.
2335
2448
        else:
2336
2449
            took_lock = False
2337
2450
        try:
2338
 
            return self.control_files.lock_write(token=token)
 
2451
            return BranchWriteLockResult(self.unlock,
 
2452
                self.control_files.lock_write(token=token))
2339
2453
        except:
2340
2454
            if took_lock:
2341
2455
                self.repository.unlock()
2342
2456
            raise
2343
2457
 
2344
2458
    def lock_read(self):
 
2459
        """Lock the branch for read operations.
 
2460
 
 
2461
        :return: A bzrlib.lock.LogicalLockResult.
 
2462
        """
2345
2463
        if not self.is_locked():
2346
2464
            self._note_lock('r')
2347
2465
        # All-in-one needs to always unlock/lock.
2354
2472
            took_lock = False
2355
2473
        try:
2356
2474
            self.control_files.lock_read()
 
2475
            return LogicalLockResult(self.unlock)
2357
2476
        except:
2358
2477
            if took_lock:
2359
2478
                self.repository.unlock()
2515
2634
        result.target_branch = target
2516
2635
        result.old_revno, result.old_revid = target.last_revision_info()
2517
2636
        self.update_references(target)
2518
 
        if result.old_revid != self.last_revision():
 
2637
        if result.old_revid != stop_revision:
2519
2638
            # We assume that during 'push' this repository is closer than
2520
2639
            # the target.
2521
2640
            graph = self.repository.get_graph(target.repository)
2922
3041
        try:
2923
3042
            index = self._partial_revision_history_cache.index(revision_id)
2924
3043
        except ValueError:
2925
 
            self._extend_partial_history(stop_revision=revision_id)
 
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)
2926
3048
            index = len(self._partial_revision_history_cache) - 1
2927
3049
            if self._partial_revision_history_cache[index] != revision_id:
2928
3050
                raise errors.NoSuchRevision(self, revision_id)
2983
3105
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
2984
3106
    """
2985
3107
 
 
3108
    @deprecated_method(deprecated_in((2, 3, 0)))
2986
3109
    def __int__(self):
2987
 
        # DEPRECATED: pull used to return the change in revno
 
3110
        """Return the relative change in revno.
 
3111
 
 
3112
        :deprecated: Use `new_revno` and `old_revno` instead.
 
3113
        """
2988
3114
        return self.new_revno - self.old_revno
2989
3115
 
2990
3116
    def report(self, to_file):
3015
3141
        target, otherwise it will be None.
3016
3142
    """
3017
3143
 
 
3144
    @deprecated_method(deprecated_in((2, 3, 0)))
3018
3145
    def __int__(self):
3019
 
        # DEPRECATED: push used to return the change in revno
 
3146
        """Return the relative change in revno.
 
3147
 
 
3148
        :deprecated: Use `new_revno` and `old_revno` instead.
 
3149
        """
3020
3150
        return self.new_revno - self.old_revno
3021
3151
 
3022
3152
    def report(self, to_file):
3145
3275
    _optimisers = []
3146
3276
    """The available optimised InterBranch types."""
3147
3277
 
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)
 
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)
3152
3287
 
 
3288
    @needs_write_lock
3153
3289
    def pull(self, overwrite=False, stop_revision=None,
3154
3290
             possible_transports=None, local=False):
3155
3291
        """Mirror source into target branch.
3160
3296
        """
3161
3297
        raise NotImplementedError(self.pull)
3162
3298
 
 
3299
    @needs_write_lock
3163
3300
    def update_revisions(self, stop_revision=None, overwrite=False,
3164
 
                         graph=None):
 
3301
                         graph=None, fetch_tags=True):
3165
3302
        """Pull in new perfect-fit revisions.
3166
3303
 
3167
3304
        :param stop_revision: Updated until the given revision
3169
3306
            to see if it is a proper descendant.
3170
3307
        :param graph: A Graph object that can be used to query history
3171
3308
            information. This can be None.
 
3309
        :param fetch_tags: Flag that specifies if tags from source should be
 
3310
            fetched too.
3172
3311
        :return: None
3173
3312
        """
3174
3313
        raise NotImplementedError(self.update_revisions)
3175
3314
 
 
3315
    @needs_write_lock
3176
3316
    def push(self, overwrite=False, stop_revision=None,
3177
3317
             _override_hook_source_branch=None):
3178
3318
        """Mirror the source branch into the target branch.
3181
3321
        """
3182
3322
        raise NotImplementedError(self.push)
3183
3323
 
 
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
 
3184
3333
 
3185
3334
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
 
 
 
3335
    """InterBranch implementation that uses public Branch functions."""
 
3336
 
 
3337
    @classmethod
 
3338
    def is_compatible(klass, source, target):
 
3339
        # GenericBranch uses the public API, so always compatible
 
3340
        return True
 
3341
 
 
3342
    @classmethod
 
3343
    def _get_branch_formats_to_test(klass):
 
3344
        return [(format_registry.get_default(), format_registry.get_default())]
 
3345
 
 
3346
    @classmethod
 
3347
    def unwrap_format(klass, format):
 
3348
        if isinstance(format, remote.RemoteBranchFormat):
 
3349
            format._ensure_real()
 
3350
            return format._custom_format
 
3351
        return format
 
3352
 
 
3353
    @needs_write_lock
 
3354
    def copy_content_into(self, revision_id=None):
 
3355
        """Copy the content of source into target
 
3356
 
 
3357
        revision_id: if not None, the revision history in the new branch will
 
3358
                     be truncated to end with revision_id.
 
3359
        """
 
3360
        self.source.update_references(self.target)
 
3361
        self.source._synchronize_history(self.target, revision_id)
 
3362
        try:
 
3363
            parent = self.source.get_parent()
 
3364
        except errors.InaccessibleParent, e:
 
3365
            mutter('parent was not accessible to copy: %s', e)
 
3366
        else:
 
3367
            if parent:
 
3368
                self.target.set_parent(parent)
 
3369
        if self.source._push_should_merge_tags():
 
3370
            self.source.tags.merge_to(self.target.tags)
 
3371
 
 
3372
    @needs_write_lock
3193
3373
    def update_revisions(self, stop_revision=None, overwrite=False,
3194
 
        graph=None):
 
3374
        graph=None, fetch_tags=True):
3195
3375
        """See InterBranch.update_revisions()."""
3196
 
        self.source.lock_read()
3197
 
        try:
3198
 
            other_revno, other_last_revision = self.source.last_revision_info()
3199
 
            stop_revno = None # unknown
3200
 
            if stop_revision is None:
3201
 
                stop_revision = other_last_revision
3202
 
                if _mod_revision.is_null(stop_revision):
3203
 
                    # if there are no commits, we're done.
3204
 
                    return
3205
 
                stop_revno = other_revno
3206
 
 
3207
 
            # what's the current last revision, before we fetch [and change it
3208
 
            # possibly]
3209
 
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
3210
 
            # we fetch here so that we don't process data twice in the common
3211
 
            # case of having something to pull, and so that the check for
3212
 
            # already merged can operate on the just fetched graph, which will
3213
 
            # be cached in memory.
3214
 
            self.target.fetch(self.source, stop_revision)
3215
 
            # Check to see if one is an ancestor of the other
3216
 
            if not overwrite:
3217
 
                if graph is None:
3218
 
                    graph = self.target.repository.get_graph()
3219
 
                if self.target._check_if_descendant_or_diverged(
3220
 
                        stop_revision, last_rev, graph, self.source):
3221
 
                    # stop_revision is a descendant of last_rev, but we aren't
3222
 
                    # overwriting, so we're done.
3223
 
                    return
3224
 
            if stop_revno is None:
3225
 
                if graph is None:
3226
 
                    graph = self.target.repository.get_graph()
3227
 
                this_revno, this_last_revision = \
3228
 
                        self.target.last_revision_info()
3229
 
                stop_revno = graph.find_distance_to_null(stop_revision,
3230
 
                                [(other_last_revision, other_revno),
3231
 
                                 (this_last_revision, this_revno)])
3232
 
            self.target.set_last_revision_info(stop_revno, stop_revision)
3233
 
        finally:
3234
 
            self.source.unlock()
3235
 
 
 
3376
        other_revno, other_last_revision = self.source.last_revision_info()
 
3377
        stop_revno = None # unknown
 
3378
        if stop_revision is None:
 
3379
            stop_revision = other_last_revision
 
3380
            if _mod_revision.is_null(stop_revision):
 
3381
                # if there are no commits, we're done.
 
3382
                return
 
3383
            stop_revno = other_revno
 
3384
 
 
3385
        # what's the current last revision, before we fetch [and change it
 
3386
        # possibly]
 
3387
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
3388
        # we fetch here so that we don't process data twice in the common
 
3389
        # case of having something to pull, and so that the check for
 
3390
        # already merged can operate on the just fetched graph, which will
 
3391
        # be cached in memory.
 
3392
        if fetch_tags:
 
3393
            fetch_spec_factory = fetch.FetchSpecFactory()
 
3394
            fetch_spec_factory.source_branch = self.source
 
3395
            fetch_spec_factory.source_branch_stop_revision_id = stop_revision
 
3396
            fetch_spec_factory.source_repo = self.source.repository
 
3397
            fetch_spec_factory.target_repo = self.target.repository
 
3398
            fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
 
3399
            fetch_spec = fetch_spec_factory.make_fetch_spec()
 
3400
        else:
 
3401
            fetch_spec = _mod_graph.NotInOtherForRevs(self.target.repository,
 
3402
                self.source.repository, revision_ids=[stop_revision]).execute()
 
3403
        self.target.fetch(self.source, fetch_spec=fetch_spec)
 
3404
        # Check to see if one is an ancestor of the other
 
3405
        if not overwrite:
 
3406
            if graph is None:
 
3407
                graph = self.target.repository.get_graph()
 
3408
            if self.target._check_if_descendant_or_diverged(
 
3409
                    stop_revision, last_rev, graph, self.source):
 
3410
                # stop_revision is a descendant of last_rev, but we aren't
 
3411
                # overwriting, so we're done.
 
3412
                return
 
3413
        if stop_revno is None:
 
3414
            if graph is None:
 
3415
                graph = self.target.repository.get_graph()
 
3416
            this_revno, this_last_revision = \
 
3417
                    self.target.last_revision_info()
 
3418
            stop_revno = graph.find_distance_to_null(stop_revision,
 
3419
                            [(other_last_revision, other_revno),
 
3420
                             (this_last_revision, this_revno)])
 
3421
        self.target.set_last_revision_info(stop_revno, stop_revision)
 
3422
 
 
3423
    @needs_write_lock
3236
3424
    def pull(self, overwrite=False, stop_revision=None,
3237
 
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3425
             possible_transports=None, run_hooks=True,
3238
3426
             _override_hook_target=None, local=False):
3239
 
        """See Branch.pull.
 
3427
        """Pull from source into self, updating my master if any.
3240
3428
 
3241
 
        :param _hook_master: Private parameter - set the branch to
3242
 
            be supplied as the master to pull hooks.
3243
3429
        :param run_hooks: Private parameter - if false, this branch
3244
3430
            is being called because it's the master of the primary branch,
3245
3431
            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
3432
        """
3250
 
        # This type of branch can't be bound.
3251
 
        if local:
 
3433
        bound_location = self.target.get_bound_location()
 
3434
        if local and not bound_location:
3252
3435
            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()
 
3436
        master_branch = None
 
3437
        source_is_master = (self.source.user_url == bound_location)
 
3438
        if not local and bound_location and not source_is_master:
 
3439
            # not pulling from master, so we need to update master.
 
3440
            master_branch = self.target.get_master_branch(possible_transports)
 
3441
            master_branch.lock_write()
3260
3442
        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)
 
3443
            if master_branch:
 
3444
                # pull from source into master.
 
3445
                master_branch.pull(self.source, overwrite, stop_revision,
 
3446
                    run_hooks=False)
 
3447
            return self._pull(overwrite,
 
3448
                stop_revision, _hook_master=master_branch,
 
3449
                run_hooks=run_hooks,
 
3450
                _override_hook_target=_override_hook_target,
 
3451
                merge_tags_to_master=not source_is_master)
3287
3452
        finally:
3288
 
            self.source.unlock()
3289
 
        return result
 
3453
            if master_branch:
 
3454
                master_branch.unlock()
3290
3455
 
3291
3456
    def push(self, overwrite=False, stop_revision=None,
3292
3457
             _override_hook_source_branch=None):
3332
3497
                # push into the master from the source branch.
3333
3498
                self.source._basic_push(master_branch, overwrite, stop_revision)
3334
3499
                # and push into the target branch from the source. Note that we
3335
 
                # push from the source branch again, because its considered the
 
3500
                # push from the source branch again, because it's considered the
3336
3501
                # highest bandwidth repository.
3337
3502
                result = self.source._basic_push(self.target, overwrite,
3338
3503
                    stop_revision)
3354
3519
            _run_hooks()
3355
3520
            return result
3356
3521
 
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
 
 
 
3522
    def _pull(self, overwrite=False, stop_revision=None,
 
3523
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3524
             _override_hook_target=None, local=False,
 
3525
             merge_tags_to_master=True):
 
3526
        """See Branch.pull.
 
3527
 
 
3528
        This function is the core worker, used by GenericInterBranch.pull to
 
3529
        avoid duplication when pulling source->master and source->local.
 
3530
 
 
3531
        :param _hook_master: Private parameter - set the branch to
 
3532
            be supplied as the master to pull hooks.
3374
3533
        :param run_hooks: Private parameter - if false, this branch
3375
3534
            is being called because it's the master of the primary branch,
3376
3535
            so it should not run its hooks.
 
3536
            is being called because it's the master of the primary branch,
 
3537
            so it should not run its hooks.
 
3538
        :param _override_hook_target: Private parameter - set the branch to be
 
3539
            supplied as the target_branch to pull hooks.
 
3540
        :param local: Only update the local branch, and not the bound branch.
3377
3541
        """
3378
 
        bound_location = self.target.get_bound_location()
3379
 
        if local and not bound_location:
 
3542
        # This type of branch can't be bound.
 
3543
        if local:
3380
3544
            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()
 
3545
        result = PullResult()
 
3546
        result.source_branch = self.source
 
3547
        if _override_hook_target is None:
 
3548
            result.target_branch = self.target
 
3549
        else:
 
3550
            result.target_branch = _override_hook_target
 
3551
        self.source.lock_read()
3386
3552
        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)
 
3553
            # We assume that during 'pull' the target repository is closer than
 
3554
            # the source one.
 
3555
            self.source.update_references(self.target)
 
3556
            graph = self.target.repository.get_graph(self.source.repository)
 
3557
            # TODO: Branch formats should have a flag that indicates 
 
3558
            # that revno's are expensive, and pull() should honor that flag.
 
3559
            # -- JRV20090506
 
3560
            result.old_revno, result.old_revid = \
 
3561
                self.target.last_revision_info()
 
3562
            self.target.update_revisions(self.source, stop_revision,
 
3563
                overwrite=overwrite, graph=graph)
 
3564
            # TODO: The old revid should be specified when merging tags, 
 
3565
            # so a tags implementation that versions tags can only 
 
3566
            # pull in the most recent changes. -- JRV20090506
 
3567
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
3568
                overwrite, ignore_master=not merge_tags_to_master)
 
3569
            result.new_revno, result.new_revid = self.target.last_revision_info()
 
3570
            if _hook_master:
 
3571
                result.master_branch = _hook_master
 
3572
                result.local_branch = result.target_branch
 
3573
            else:
 
3574
                result.master_branch = result.target_branch
 
3575
                result.local_branch = None
 
3576
            if run_hooks:
 
3577
                for hook in Branch.hooks['post_pull']:
 
3578
                    hook(result)
3395
3579
        finally:
3396
 
            if master_branch:
3397
 
                master_branch.unlock()
 
3580
            self.source.unlock()
 
3581
        return result
3398
3582
 
3399
3583
 
3400
3584
InterBranch.register_optimiser(GenericInterBranch)
3401
 
InterBranch.register_optimiser(InterToBranch5)