~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Martin
  • Date: 2011-03-20 18:58:43 UTC
  • mto: This revision was merged to the branch mainline in revision 5731.
  • Revision ID: gzlist@googlemail.com-20110320185843-qn8g96slbc33yw9h
Non-code fixes noticed looking at full diff

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
25
25
        bzrdir,
26
26
        cache_utf8,
27
27
        config as _mod_config,
 
28
        controldir,
28
29
        debug,
29
30
        errors,
 
31
        fetch,
 
32
        graph as _mod_graph,
30
33
        lockdir,
31
34
        lockable_files,
 
35
        remote,
32
36
        repository,
33
37
        revision as _mod_revision,
34
38
        rio,
49
53
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
50
54
from bzrlib.hooks import HookPoint, Hooks
51
55
from bzrlib.inter import InterObject
52
 
from bzrlib.lock import _RelockDebugMixin
 
56
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
53
57
from bzrlib import registry
54
58
from bzrlib.symbol_versioning import (
55
59
    deprecated_in,
63
67
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
64
68
 
65
69
 
66
 
class Branch(bzrdir.ControlComponent):
 
70
class Branch(controldir.ControlComponent):
67
71
    """Branch holding a history of revisions.
68
72
 
69
73
    :ivar base:
90
94
        self._revision_id_to_revno_cache = None
91
95
        self._partial_revision_id_to_revno_cache = {}
92
96
        self._partial_revision_history_cache = []
 
97
        self._tags_bytes = None
93
98
        self._last_revision_info_cache = None
94
99
        self._merge_sorted_revisions_cache = None
95
100
        self._open_hook()
102
107
 
103
108
    def _activate_fallback_location(self, url):
104
109
        """Activate the branch/repository from url as a fallback repository."""
 
110
        for existing_fallback_repo in self.repository._fallback_repositories:
 
111
            if existing_fallback_repo.user_url == url:
 
112
                # This fallback is already configured.  This probably only
 
113
                # happens because BzrDir.sprout is a horrible mess.  To avoid
 
114
                # confusing _unstack we don't add this a second time.
 
115
                mutter('duplicate activation of fallback %r on %r', url, self)
 
116
                return
105
117
        repo = self._get_fallback_repository(url)
106
118
        if repo.has_same_location(self.repository):
107
119
            raise errors.UnstackableLocationError(self.user_url, url)
197
209
        return self.supports_tags() and self.tags.get_tag_dict()
198
210
 
199
211
    def get_config(self):
 
212
        """Get a bzrlib.config.BranchConfig for this Branch.
 
213
 
 
214
        This can then be used to get and set configuration options for the
 
215
        branch.
 
216
 
 
217
        :return: A bzrlib.config.BranchConfig.
 
218
        """
200
219
        return BranchConfig(self)
201
220
 
202
221
    def _get_config(self):
218
237
            possible_transports=[self.bzrdir.root_transport])
219
238
        return a_branch.repository
220
239
 
 
240
    @needs_read_lock
221
241
    def _get_tags_bytes(self):
222
242
        """Get the bytes of a serialised tags dict.
223
243
 
230
250
        :return: The bytes of the tags file.
231
251
        :seealso: Branch._set_tags_bytes.
232
252
        """
233
 
        return self._transport.get_bytes('tags')
 
253
        if self._tags_bytes is None:
 
254
            self._tags_bytes = self._transport.get_bytes('tags')
 
255
        return self._tags_bytes
234
256
 
235
257
    def _get_nick(self, local=False, possible_transports=None):
236
258
        config = self.get_config()
238
260
        if not local and not config.has_explicit_nickname():
239
261
            try:
240
262
                master = self.get_master_branch(possible_transports)
 
263
                if master and self.user_url == master.user_url:
 
264
                    raise errors.RecursiveBind(self.user_url)
241
265
                if master is not None:
242
266
                    # return the master branch value
243
267
                    return master.nick
 
268
            except errors.RecursiveBind, e:
 
269
                raise e
244
270
            except errors.BzrError, e:
245
271
                # Silently fall back to local implicit nick if the master is
246
272
                # unavailable
283
309
        new_history.reverse()
284
310
        return new_history
285
311
 
286
 
    def lock_write(self):
 
312
    def lock_write(self, token=None):
 
313
        """Lock the branch for write operations.
 
314
 
 
315
        :param token: A token to permit reacquiring a previously held and
 
316
            preserved lock.
 
317
        :return: A BranchWriteLockResult.
 
318
        """
287
319
        raise NotImplementedError(self.lock_write)
288
320
 
289
321
    def lock_read(self):
 
322
        """Lock the branch for read operations.
 
323
 
 
324
        :return: A bzrlib.lock.LogicalLockResult.
 
325
        """
290
326
        raise NotImplementedError(self.lock_read)
291
327
 
292
328
    def unlock(self):
626
662
        raise errors.UnsupportedOperation(self.get_reference_info, self)
627
663
 
628
664
    @needs_write_lock
629
 
    def fetch(self, from_branch, last_revision=None, pb=None):
 
665
    def fetch(self, from_branch, last_revision=None, fetch_spec=None):
630
666
        """Copy revisions from from_branch into this branch.
631
667
 
632
668
        :param from_branch: Where to copy from.
633
669
        :param last_revision: What revision to stop at (None for at the end
634
670
                              of the branch.
635
 
        :param pb: An optional progress bar to use.
 
671
        :param fetch_spec: If specified, a SearchResult or
 
672
            PendingAncestryResult that describes which revisions to copy.  This
 
673
            allows copying multiple heads at once.  Mutually exclusive with
 
674
            last_revision.
636
675
        :return: None
637
676
        """
 
677
        if fetch_spec is not None and last_revision is not None:
 
678
            raise AssertionError(
 
679
                "fetch_spec and last_revision are mutually exclusive.")
638
680
        if self.base == from_branch.base:
639
681
            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
682
        from_branch.lock_read()
645
683
        try:
646
 
            if last_revision is None:
 
684
            if last_revision is None and fetch_spec is None:
647
685
                last_revision = from_branch.last_revision()
648
686
                last_revision = _mod_revision.ensure_null(last_revision)
649
687
            return self.repository.fetch(from_branch.repository,
650
688
                                         revision_id=last_revision,
651
 
                                         pb=pb)
 
689
                                         fetch_spec=fetch_spec)
652
690
        finally:
653
691
            from_branch.unlock()
654
692
 
782
820
            old_repository = self.repository
783
821
            if len(old_repository._fallback_repositories) != 1:
784
822
                raise AssertionError("can't cope with fallback repositories "
785
 
                    "of %r" % (self.repository,))
786
 
            # unlock it, including unlocking the fallback
 
823
                    "of %r (fallbacks: %r)" % (old_repository,
 
824
                        old_repository._fallback_repositories))
 
825
            # Open the new repository object.
 
826
            # Repositories don't offer an interface to remove fallback
 
827
            # repositories today; take the conceptually simpler option and just
 
828
            # reopen it.  We reopen it starting from the URL so that we
 
829
            # get a separate connection for RemoteRepositories and can
 
830
            # stream from one of them to the other.  This does mean doing
 
831
            # separate SSH connection setup, but unstacking is not a
 
832
            # common operation so it's tolerable.
 
833
            new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
 
834
            new_repository = new_bzrdir.find_repository()
 
835
            if new_repository._fallback_repositories:
 
836
                raise AssertionError("didn't expect %r to have "
 
837
                    "fallback_repositories"
 
838
                    % (self.repository,))
 
839
            # Replace self.repository with the new repository.
 
840
            # Do our best to transfer the lock state (i.e. lock-tokens and
 
841
            # lock count) of self.repository to the new repository.
 
842
            lock_token = old_repository.lock_write().repository_token
 
843
            self.repository = new_repository
 
844
            if isinstance(self, remote.RemoteBranch):
 
845
                # Remote branches can have a second reference to the old
 
846
                # repository that need to be replaced.
 
847
                if self._real_branch is not None:
 
848
                    self._real_branch.repository = new_repository
 
849
            self.repository.lock_write(token=lock_token)
 
850
            if lock_token is not None:
 
851
                old_repository.leave_lock_in_place()
787
852
            old_repository.unlock()
 
853
            if lock_token is not None:
 
854
                # XXX: self.repository.leave_lock_in_place() before this
 
855
                # function will not be preserved.  Fortunately that doesn't
 
856
                # affect the current default format (2a), and would be a
 
857
                # corner-case anyway.
 
858
                #  - Andrew Bennetts, 2010/06/30
 
859
                self.repository.dont_leave_lock_in_place()
 
860
            old_lock_count = 0
 
861
            while True:
 
862
                try:
 
863
                    old_repository.unlock()
 
864
                except errors.LockNotHeld:
 
865
                    break
 
866
                old_lock_count += 1
 
867
            if old_lock_count == 0:
 
868
                raise AssertionError(
 
869
                    'old_repository should have been locked at least once.')
 
870
            for i in range(old_lock_count-1):
 
871
                self.repository.lock_write()
 
872
            # Fetch from the old repository into the new.
788
873
            old_repository.lock_read()
789
874
            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
875
                # XXX: If you unstack a branch while it has a working tree
809
876
                # with a pending merge, the pending-merged revisions will no
810
877
                # 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)
 
878
                try:
 
879
                    tags_to_fetch = set(self.tags.get_reverse_tag_dict())
 
880
                except errors.TagsNotSupported:
 
881
                    tags_to_fetch = set()
 
882
                fetch_spec = _mod_graph.NotInOtherForRevs(self.repository,
 
883
                    old_repository, required_ids=[self.last_revision()],
 
884
                    if_present_ids=tags_to_fetch, find_ghosts=True).execute()
 
885
                self.repository.fetch(old_repository, fetch_spec=fetch_spec)
818
886
            finally:
819
887
                old_repository.unlock()
820
888
        finally:
825
893
 
826
894
        :seealso: Branch._get_tags_bytes.
827
895
        """
828
 
        return _run_with_write_locked_target(self, self._transport.put_bytes,
829
 
            'tags', bytes)
 
896
        return _run_with_write_locked_target(self, self._set_tags_bytes_locked,
 
897
                bytes)
 
898
 
 
899
    def _set_tags_bytes_locked(self, bytes):
 
900
        self._tags_bytes = bytes
 
901
        return self._transport.put_bytes('tags', bytes)
830
902
 
831
903
    def _cache_revision_history(self, rev_history):
832
904
        """Set the cached revision history to rev_history.
862
934
        self._merge_sorted_revisions_cache = None
863
935
        self._partial_revision_history_cache = []
864
936
        self._partial_revision_id_to_revno_cache = {}
 
937
        self._tags_bytes = None
865
938
 
866
939
    def _gen_revision_history(self):
867
940
        """Return sequence of revision hashes on to this branch.
928
1001
        else:
929
1002
            return (0, _mod_revision.NULL_REVISION)
930
1003
 
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
1004
    def update_revisions(self, other, stop_revision=None, overwrite=False,
956
 
                         graph=None):
 
1005
                         graph=None, fetch_tags=True):
957
1006
        """Pull in new perfect-fit revisions.
958
1007
 
959
1008
        :param other: Another Branch to pull from
962
1011
            to see if it is a proper descendant.
963
1012
        :param graph: A Graph object that can be used to query history
964
1013
            information. This can be None.
 
1014
        :param fetch_tags: Flag that specifies if tags from other should be
 
1015
            fetched too.
965
1016
        :return: None
966
1017
        """
967
1018
        return InterBranch.get(other, self).update_revisions(stop_revision,
968
 
            overwrite, graph)
 
1019
            overwrite, graph, fetch_tags=fetch_tags)
969
1020
 
 
1021
    @deprecated_method(deprecated_in((2, 4, 0)))
970
1022
    def import_last_revision_info(self, source_repo, revno, revid):
971
1023
        """Set the last revision info, importing from another repo if necessary.
972
1024
 
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
1025
        :param source_repo: Source repository to optionally fetch from
977
1026
        :param revno: Revision number of the new tip
978
1027
        :param revid: Revision id of the new tip
981
1030
            self.repository.fetch(source_repo, revision_id=revid)
982
1031
        self.set_last_revision_info(revno, revid)
983
1032
 
 
1033
    def import_last_revision_info_and_tags(self, source, revno, revid):
 
1034
        """Set the last revision info, importing from another repo if necessary.
 
1035
 
 
1036
        This is used by the bound branch code to upload a revision to
 
1037
        the master branch first before updating the tip of the local branch.
 
1038
        Revisions referenced by source's tags are also transferred.
 
1039
 
 
1040
        :param source: Source branch to optionally fetch from
 
1041
        :param revno: Revision number of the new tip
 
1042
        :param revid: Revision id of the new tip
 
1043
        """
 
1044
        if not self.repository.has_same_location(source.repository):
 
1045
            try:
 
1046
                tags_to_fetch = set(source.tags.get_reverse_tag_dict())
 
1047
            except errors.TagsNotSupported:
 
1048
                tags_to_fetch = set()
 
1049
            fetch_spec = _mod_graph.NotInOtherForRevs(self.repository,
 
1050
                source.repository, [revid],
 
1051
                if_present_ids=tags_to_fetch).execute()
 
1052
            self.repository.fetch(source.repository, fetch_spec=fetch_spec)
 
1053
        self.set_last_revision_info(revno, revid)
 
1054
 
984
1055
    def revision_id_to_revno(self, revision_id):
985
1056
        """Given a revision id, return its revno"""
986
1057
        if _mod_revision.is_null(revision_id):
1006
1077
            self._extend_partial_history(distance_from_last)
1007
1078
        return self._partial_revision_history_cache[distance_from_last]
1008
1079
 
1009
 
    @needs_write_lock
1010
1080
    def pull(self, source, overwrite=False, stop_revision=None,
1011
1081
             possible_transports=None, *args, **kwargs):
1012
1082
        """Mirror source into this branch.
1208
1278
        return result
1209
1279
 
1210
1280
    @needs_read_lock
1211
 
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None):
 
1281
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None,
 
1282
            repository=None):
1212
1283
        """Create a new line of development from the branch, into to_bzrdir.
1213
1284
 
1214
1285
        to_bzrdir controls the branch format.
1219
1290
        if (repository_policy is not None and
1220
1291
            repository_policy.requires_stacking()):
1221
1292
            to_bzrdir._format.require_stacking(_skip_repo=True)
1222
 
        result = to_bzrdir.create_branch()
 
1293
        result = to_bzrdir.create_branch(repository=repository)
1223
1294
        result.lock_write()
1224
1295
        try:
1225
1296
            if repository_policy is not None:
1255
1326
                revno = 1
1256
1327
        destination.set_last_revision_info(revno, revision_id)
1257
1328
 
1258
 
    @needs_read_lock
1259
1329
    def copy_content_into(self, destination, revision_id=None):
1260
1330
        """Copy the content of self into destination.
1261
1331
 
1262
1332
        revision_id: if not None, the revision history in the new branch will
1263
1333
                     be truncated to end with revision_id.
1264
1334
        """
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)
 
1335
        return InterBranch.get(self, destination).copy_content_into(
 
1336
            revision_id=revision_id)
1276
1337
 
1277
1338
    def update_references(self, target):
1278
1339
        if not getattr(self._format, 'supports_reference_locations', False):
1323
1384
        """Return the most suitable metadir for a checkout of this branch.
1324
1385
        Weaves are used if this branch's repository uses weaves.
1325
1386
        """
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)
 
1387
        format = self.repository.bzrdir.checkout_metadir()
 
1388
        format.set_branch_format(self._format)
1333
1389
        return format
1334
1390
 
1335
1391
    def create_clone_on_transport(self, to_transport, revision_id=None,
1336
 
        stacked_on=None, create_prefix=False, use_existing_dir=False):
 
1392
        stacked_on=None, create_prefix=False, use_existing_dir=False,
 
1393
        no_tree=None):
1337
1394
        """Create a clone of this branch and its bzrdir.
1338
1395
 
1339
1396
        :param to_transport: The transport to clone onto.
1346
1403
        """
1347
1404
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1348
1405
        # clone call. Or something. 20090224 RBC/spiv.
 
1406
        # XXX: Should this perhaps clone colocated branches as well, 
 
1407
        # rather than just the default branch? 20100319 JRV
1349
1408
        if revision_id is None:
1350
1409
            revision_id = self.last_revision()
1351
1410
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1352
1411
            revision_id=revision_id, stacked_on=stacked_on,
1353
 
            create_prefix=create_prefix, use_existing_dir=use_existing_dir)
 
1412
            create_prefix=create_prefix, use_existing_dir=use_existing_dir,
 
1413
            no_tree=no_tree)
1354
1414
        return dir_to.open_branch()
1355
1415
 
1356
1416
    def create_checkout(self, to_location, revision_id=None,
1471
1531
        else:
1472
1532
            raise AssertionError("invalid heads: %r" % (heads,))
1473
1533
 
1474
 
 
1475
 
class BranchFormat(object):
 
1534
    def heads_to_fetch(self):
 
1535
        """Return the heads that must and that should be fetched to copy this
 
1536
        branch into another repo.
 
1537
 
 
1538
        :returns: a 2-tuple of (must_fetch, if_present_fetch).  must_fetch is a
 
1539
            set of heads that must be fetched.  if_present_fetch is a set of
 
1540
            heads that must be fetched if present, but no error is necessary if
 
1541
            they are not present.
 
1542
        """
 
1543
        # For bzr native formats must_fetch is just the tip, and if_present_fetch
 
1544
        # are the tags.
 
1545
        must_fetch = set([self.last_revision()])
 
1546
        try:
 
1547
            if_present_fetch = set(self.tags.get_reverse_tag_dict())
 
1548
        except errors.TagsNotSupported:
 
1549
            if_present_fetch = set()
 
1550
        must_fetch.discard(_mod_revision.NULL_REVISION)
 
1551
        if_present_fetch.discard(_mod_revision.NULL_REVISION)
 
1552
        return must_fetch, if_present_fetch
 
1553
 
 
1554
 
 
1555
class BranchFormat(controldir.ControlComponentFormat):
1476
1556
    """An encapsulation of the initialization and open routines for a format.
1477
1557
 
1478
1558
    Formats provide three things:
1481
1561
     * an open routine.
1482
1562
 
1483
1563
    Formats are placed in an dict by their format string for reference
1484
 
    during branch opening. Its not required that these be instances, they
 
1564
    during branch opening. It's not required that these be instances, they
1485
1565
    can be classes themselves with class methods - it simply depends on
1486
1566
    whether state is needed for a given format or not.
1487
1567
 
1490
1570
    object will be created every time regardless.
1491
1571
    """
1492
1572
 
1493
 
    _default_format = None
1494
 
    """The default format used for new branches."""
1495
 
 
1496
 
    _formats = {}
1497
 
    """The known formats."""
1498
 
 
1499
1573
    can_set_append_revisions_only = True
1500
1574
 
1501
1575
    def __eq__(self, other):
1510
1584
        try:
1511
1585
            transport = a_bzrdir.get_branch_transport(None, name=name)
1512
1586
            format_string = transport.get_bytes("format")
1513
 
            return klass._formats[format_string]
 
1587
            return format_registry.get(format_string)
1514
1588
        except errors.NoSuchFile:
1515
1589
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1516
1590
        except KeyError:
1517
1591
            raise errors.UnknownFormatError(format=format_string, kind='branch')
1518
1592
 
1519
1593
    @classmethod
 
1594
    @deprecated_method(deprecated_in((2, 4, 0)))
1520
1595
    def get_default_format(klass):
1521
1596
        """Return the current default format."""
1522
 
        return klass._default_format
1523
 
 
1524
 
    def get_reference(self, a_bzrdir):
 
1597
        return format_registry.get_default()
 
1598
 
 
1599
    @classmethod
 
1600
    @deprecated_method(deprecated_in((2, 4, 0)))
 
1601
    def get_formats(klass):
 
1602
        """Get all the known formats.
 
1603
 
 
1604
        Warning: This triggers a load of all lazy registered formats: do not
 
1605
        use except when that is desireed.
 
1606
        """
 
1607
        return format_registry._get_all()
 
1608
 
 
1609
    def get_reference(self, a_bzrdir, name=None):
1525
1610
        """Get the target reference of the branch in a_bzrdir.
1526
1611
 
1527
1612
        format probing must have been completed before calling
1529
1614
        in a_bzrdir is correct.
1530
1615
 
1531
1616
        :param a_bzrdir: The bzrdir to get the branch data from.
 
1617
        :param name: Name of the colocated branch to fetch
1532
1618
        :return: None if the branch is not a reference branch.
1533
1619
        """
1534
1620
        return None
1535
1621
 
1536
1622
    @classmethod
1537
 
    def set_reference(self, a_bzrdir, to_branch):
 
1623
    def set_reference(self, a_bzrdir, name, to_branch):
1538
1624
        """Set the target reference of the branch in a_bzrdir.
1539
1625
 
1540
1626
        format probing must have been completed before calling
1542
1628
        in a_bzrdir is correct.
1543
1629
 
1544
1630
        :param a_bzrdir: The bzrdir to set the branch reference for.
 
1631
        :param name: Name of colocated branch to set, None for default
1545
1632
        :param to_branch: branch that the checkout is to reference
1546
1633
        """
1547
1634
        raise NotImplementedError(self.set_reference)
1563
1650
            hook(params)
1564
1651
 
1565
1652
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
1566
 
                           lock_type='metadir', set_format=True):
 
1653
                           repository=None, lock_type='metadir',
 
1654
                           set_format=True):
1567
1655
        """Initialize a branch in a bzrdir, with specified files
1568
1656
 
1569
1657
        :param a_bzrdir: The bzrdir to initialize the branch in
1603
1691
        finally:
1604
1692
            if lock_taken:
1605
1693
                control_files.unlock()
1606
 
        branch = self.open(a_bzrdir, name, _found=True)
 
1694
        branch = self.open(a_bzrdir, name, _found=True,
 
1695
                found_repository=repository)
1607
1696
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
1608
1697
        return branch
1609
1698
 
1610
 
    def initialize(self, a_bzrdir, name=None):
 
1699
    def initialize(self, a_bzrdir, name=None, repository=None):
1611
1700
        """Create a branch of this format in a_bzrdir.
1612
1701
        
1613
1702
        :param name: Name of the colocated branch to create.
1647
1736
        """
1648
1737
        raise NotImplementedError(self.network_name)
1649
1738
 
1650
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1739
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
 
1740
            found_repository=None):
1651
1741
        """Return the branch object for a_bzrdir
1652
1742
 
1653
1743
        :param a_bzrdir: A BzrDir that contains a branch.
1660
1750
        raise NotImplementedError(self.open)
1661
1751
 
1662
1752
    @classmethod
 
1753
    @deprecated_method(deprecated_in((2, 4, 0)))
1663
1754
    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__)
 
1755
        """Register a metadir format.
 
1756
 
 
1757
        See MetaDirBranchFormatFactory for the ability to register a format
 
1758
        without loading the code the format needs until it is actually used.
 
1759
        """
 
1760
        format_registry.register(format)
1669
1761
 
1670
1762
    @classmethod
 
1763
    @deprecated_method(deprecated_in((2, 4, 0)))
1671
1764
    def set_default_format(klass, format):
1672
 
        klass._default_format = format
 
1765
        format_registry.set_default(format)
1673
1766
 
1674
1767
    def supports_set_append_revisions_only(self):
1675
1768
        """True if this format supports set_append_revisions_only."""
1679
1772
        """True if this format records a stacked-on branch."""
1680
1773
        return False
1681
1774
 
 
1775
    def supports_leaving_lock(self):
 
1776
        """True if this format supports leaving locks in place."""
 
1777
        return False # by default
 
1778
 
1682
1779
    @classmethod
 
1780
    @deprecated_method(deprecated_in((2, 4, 0)))
1683
1781
    def unregister_format(klass, format):
1684
 
        del klass._formats[format.get_format_string()]
 
1782
        format_registry.remove(format)
1685
1783
 
1686
1784
    def __str__(self):
1687
1785
        return self.get_format_description().rstrip()
1691
1789
        return False  # by default
1692
1790
 
1693
1791
 
 
1792
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
 
1793
    """A factory for a BranchFormat object, permitting simple lazy registration.
 
1794
    
 
1795
    While none of the built in BranchFormats are lazy registered yet,
 
1796
    bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
 
1797
    use it, and the bzr-loom plugin uses it as well (see
 
1798
    bzrlib.plugins.loom.formats).
 
1799
    """
 
1800
 
 
1801
    def __init__(self, format_string, module_name, member_name):
 
1802
        """Create a MetaDirBranchFormatFactory.
 
1803
 
 
1804
        :param format_string: The format string the format has.
 
1805
        :param module_name: Module to load the format class from.
 
1806
        :param member_name: Attribute name within the module for the format class.
 
1807
        """
 
1808
        registry._LazyObjectGetter.__init__(self, module_name, member_name)
 
1809
        self._format_string = format_string
 
1810
        
 
1811
    def get_format_string(self):
 
1812
        """See BranchFormat.get_format_string."""
 
1813
        return self._format_string
 
1814
 
 
1815
    def __call__(self):
 
1816
        """Used for network_format_registry support."""
 
1817
        return self.get_obj()()
 
1818
 
 
1819
 
1694
1820
class BranchHooks(Hooks):
1695
1821
    """A dictionary mapping hook name to a list of callables for branch hooks.
1696
1822
 
1723
1849
            "with a bzrlib.branch.PullResult object and only runs in the "
1724
1850
            "bzr client.", (0, 15), None))
1725
1851
        self.create_hook(HookPoint('pre_commit',
1726
 
            "Called after a commit is calculated but before it is is "
 
1852
            "Called after a commit is calculated but before it is "
1727
1853
            "completed. pre_commit is called with (local, master, old_revno, "
1728
1854
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
1729
1855
            "). old_revid is NULL_REVISION for the first commit to a branch, "
1766
1892
            "all are called with the url returned from the previous hook."
1767
1893
            "The order is however undefined.", (1, 9), None))
1768
1894
        self.create_hook(HookPoint('automatic_tag_name',
1769
 
            "Called to determine an automatic tag name for a revision."
 
1895
            "Called to determine an automatic tag name for a revision. "
1770
1896
            "automatic_tag_name is called with (branch, revision_id) and "
1771
1897
            "should return a tag name or None if no tag name could be "
1772
1898
            "determined. The first non-None tag name returned will be used.",
1863
1989
        return self.__dict__ == other.__dict__
1864
1990
 
1865
1991
    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)
 
1992
        return "<%s of %s>" % (self.__class__.__name__, self.branch)
1872
1993
 
1873
1994
 
1874
1995
class SwitchHookParams(object):
1916
2037
        """See BranchFormat.get_format_description()."""
1917
2038
        return "Branch format 4"
1918
2039
 
1919
 
    def initialize(self, a_bzrdir, name=None):
 
2040
    def initialize(self, a_bzrdir, name=None, repository=None):
1920
2041
        """Create a branch of this format in a_bzrdir."""
 
2042
        if repository is not None:
 
2043
            raise NotImplementedError(
 
2044
                "initialize(repository=<not None>) on %r" % (self,))
1921
2045
        utf8_files = [('revision-history', ''),
1922
2046
                      ('branch-name', ''),
1923
2047
                      ]
1932
2056
        """The network name for this format is the control dirs disk label."""
1933
2057
        return self._matchingbzrdir.get_format_string()
1934
2058
 
1935
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
2059
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
 
2060
            found_repository=None):
1936
2061
        """See BranchFormat.open()."""
1937
2062
        if not _found:
1938
2063
            # we are being called directly and must probe.
1939
2064
            raise NotImplementedError
1940
 
        return BzrBranch(_format=self,
 
2065
        if found_repository is None:
 
2066
            found_repository = a_bzrdir.open_repository()
 
2067
        return BzrBranchPreSplitOut(_format=self,
1941
2068
                         _control_files=a_bzrdir._control_files,
1942
2069
                         a_bzrdir=a_bzrdir,
1943
2070
                         name=name,
1944
 
                         _repository=a_bzrdir.open_repository())
 
2071
                         _repository=found_repository)
1945
2072
 
1946
2073
    def __str__(self):
1947
2074
        return "Bazaar-NG branch format 4"
1948
2075
 
 
2076
    def supports_leaving_lock(self):
 
2077
        return False
 
2078
 
1949
2079
 
1950
2080
class BranchFormatMetadir(BranchFormat):
1951
2081
    """Common logic for meta-dir based branch formats."""
1961
2091
        """
1962
2092
        return self.get_format_string()
1963
2093
 
1964
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
2094
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
 
2095
            found_repository=None):
1965
2096
        """See BranchFormat.open()."""
1966
2097
        if not _found:
1967
2098
            format = BranchFormat.find_format(a_bzrdir, name=name)
1972
2103
        try:
1973
2104
            control_files = lockable_files.LockableFiles(transport, 'lock',
1974
2105
                                                         lockdir.LockDir)
 
2106
            if found_repository is None:
 
2107
                found_repository = a_bzrdir.find_repository()
1975
2108
            return self._branch_class()(_format=self,
1976
2109
                              _control_files=control_files,
1977
2110
                              name=name,
1978
2111
                              a_bzrdir=a_bzrdir,
1979
 
                              _repository=a_bzrdir.find_repository(),
 
2112
                              _repository=found_repository,
1980
2113
                              ignore_fallbacks=ignore_fallbacks)
1981
2114
        except errors.NoSuchFile:
1982
2115
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1989
2122
    def supports_tags(self):
1990
2123
        return True
1991
2124
 
 
2125
    def supports_leaving_lock(self):
 
2126
        return True
 
2127
 
1992
2128
 
1993
2129
class BzrBranchFormat5(BranchFormatMetadir):
1994
2130
    """Bzr branch format 5.
2014
2150
        """See BranchFormat.get_format_description()."""
2015
2151
        return "Branch format 5"
2016
2152
 
2017
 
    def initialize(self, a_bzrdir, name=None):
 
2153
    def initialize(self, a_bzrdir, name=None, repository=None):
2018
2154
        """Create a branch of this format in a_bzrdir."""
2019
2155
        utf8_files = [('revision-history', ''),
2020
2156
                      ('branch-name', ''),
2021
2157
                      ]
2022
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2158
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2023
2159
 
2024
2160
    def supports_tags(self):
2025
2161
        return False
2047
2183
        """See BranchFormat.get_format_description()."""
2048
2184
        return "Branch format 6"
2049
2185
 
2050
 
    def initialize(self, a_bzrdir, name=None):
 
2186
    def initialize(self, a_bzrdir, name=None, repository=None):
2051
2187
        """Create a branch of this format in a_bzrdir."""
2052
2188
        utf8_files = [('last-revision', '0 null:\n'),
2053
2189
                      ('branch.conf', ''),
2054
2190
                      ('tags', ''),
2055
2191
                      ]
2056
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2192
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2057
2193
 
2058
2194
    def make_tags(self, branch):
2059
2195
        """See bzrlib.branch.BranchFormat.make_tags()."""
2077
2213
        """See BranchFormat.get_format_description()."""
2078
2214
        return "Branch format 8"
2079
2215
 
2080
 
    def initialize(self, a_bzrdir, name=None):
 
2216
    def initialize(self, a_bzrdir, name=None, repository=None):
2081
2217
        """Create a branch of this format in a_bzrdir."""
2082
2218
        utf8_files = [('last-revision', '0 null:\n'),
2083
2219
                      ('branch.conf', ''),
2084
2220
                      ('tags', ''),
2085
2221
                      ('references', '')
2086
2222
                      ]
2087
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2223
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2088
2224
 
2089
2225
    def __init__(self):
2090
2226
        super(BzrBranchFormat8, self).__init__()
2113
2249
    This format was introduced in bzr 1.6.
2114
2250
    """
2115
2251
 
2116
 
    def initialize(self, a_bzrdir, name=None):
 
2252
    def initialize(self, a_bzrdir, name=None, repository=None):
2117
2253
        """Create a branch of this format in a_bzrdir."""
2118
2254
        utf8_files = [('last-revision', '0 null:\n'),
2119
2255
                      ('branch.conf', ''),
2120
2256
                      ('tags', ''),
2121
2257
                      ]
2122
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2258
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2123
2259
 
2124
2260
    def _branch_class(self):
2125
2261
        return BzrBranch7
2157
2293
        """See BranchFormat.get_format_description()."""
2158
2294
        return "Checkout reference format 1"
2159
2295
 
2160
 
    def get_reference(self, a_bzrdir):
 
2296
    def get_reference(self, a_bzrdir, name=None):
2161
2297
        """See BranchFormat.get_reference()."""
2162
 
        transport = a_bzrdir.get_branch_transport(None)
 
2298
        transport = a_bzrdir.get_branch_transport(None, name=name)
2163
2299
        return transport.get_bytes('location')
2164
2300
 
2165
 
    def set_reference(self, a_bzrdir, to_branch):
 
2301
    def set_reference(self, a_bzrdir, name, to_branch):
2166
2302
        """See BranchFormat.set_reference()."""
2167
 
        transport = a_bzrdir.get_branch_transport(None)
 
2303
        transport = a_bzrdir.get_branch_transport(None, name=name)
2168
2304
        location = transport.put_bytes('location', to_branch.base)
2169
2305
 
2170
 
    def initialize(self, a_bzrdir, name=None, target_branch=None):
 
2306
    def initialize(self, a_bzrdir, name=None, target_branch=None,
 
2307
            repository=None):
2171
2308
        """Create a branch of this format in a_bzrdir."""
2172
2309
        if target_branch is None:
2173
2310
            # this format does not implement branch itself, thus the implicit
2201
2338
        return clone
2202
2339
 
2203
2340
    def open(self, a_bzrdir, name=None, _found=False, location=None,
2204
 
             possible_transports=None, ignore_fallbacks=False):
 
2341
             possible_transports=None, ignore_fallbacks=False,
 
2342
             found_repository=None):
2205
2343
        """Return the branch that the branch reference in a_bzrdir points at.
2206
2344
 
2207
2345
        :param a_bzrdir: A BzrDir that contains a branch.
2221
2359
                raise AssertionError("wrong format %r found for %r" %
2222
2360
                    (format, self))
2223
2361
        if location is None:
2224
 
            location = self.get_reference(a_bzrdir)
 
2362
            location = self.get_reference(a_bzrdir, name)
2225
2363
        real_bzrdir = bzrdir.BzrDir.open(
2226
2364
            location, possible_transports=possible_transports)
2227
2365
        result = real_bzrdir.open_branch(name=name, 
2238
2376
        return result
2239
2377
 
2240
2378
 
 
2379
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
 
2380
    """Branch format registry."""
 
2381
 
 
2382
    def __init__(self, other_registry=None):
 
2383
        super(BranchFormatRegistry, self).__init__(other_registry)
 
2384
        self._default_format = None
 
2385
 
 
2386
    def set_default(self, format):
 
2387
        self._default_format = format
 
2388
 
 
2389
    def get_default(self):
 
2390
        return self._default_format
 
2391
 
 
2392
 
2241
2393
network_format_registry = registry.FormatRegistry()
2242
2394
"""Registry of formats indexed by their network name.
2243
2395
 
2246
2398
BranchFormat.network_name() for more detail.
2247
2399
"""
2248
2400
 
 
2401
format_registry = BranchFormatRegistry(network_format_registry)
 
2402
 
2249
2403
 
2250
2404
# formats which have no format string are not discoverable
2251
2405
# and not independently creatable, so are not registered.
 
2406
__format4 = BzrBranchFormat4()
2252
2407
__format5 = BzrBranchFormat5()
2253
2408
__format6 = BzrBranchFormat6()
2254
2409
__format7 = BzrBranchFormat7()
2255
2410
__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__)
 
2411
format_registry.register(__format5)
 
2412
format_registry.register(BranchReferenceFormat())
 
2413
format_registry.register(__format6)
 
2414
format_registry.register(__format7)
 
2415
format_registry.register(__format8)
 
2416
format_registry.set_default(__format7)
 
2417
format_registry.register_extra(__format4)
 
2418
network_format_registry.register(__format4.network_name(), __format4)
 
2419
 
 
2420
 
 
2421
class BranchWriteLockResult(LogicalLockResult):
 
2422
    """The result of write locking a branch.
 
2423
 
 
2424
    :ivar branch_token: The token obtained from the underlying branch lock, or
 
2425
        None.
 
2426
    :ivar unlock: A callable which will unlock the lock.
 
2427
    """
 
2428
 
 
2429
    def __init__(self, unlock, branch_token):
 
2430
        LogicalLockResult.__init__(self, unlock)
 
2431
        self.branch_token = branch_token
 
2432
 
 
2433
    def __repr__(self):
 
2434
        return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
 
2435
            self.unlock)
2266
2436
 
2267
2437
 
2268
2438
class BzrBranch(Branch, _RelockDebugMixin):
2324
2494
        return self.control_files.is_locked()
2325
2495
 
2326
2496
    def lock_write(self, token=None):
 
2497
        """Lock the branch for write operations.
 
2498
 
 
2499
        :param token: A token to permit reacquiring a previously held and
 
2500
            preserved lock.
 
2501
        :return: A BranchWriteLockResult.
 
2502
        """
2327
2503
        if not self.is_locked():
2328
2504
            self._note_lock('w')
2329
2505
        # All-in-one needs to always unlock/lock.
2335
2511
        else:
2336
2512
            took_lock = False
2337
2513
        try:
2338
 
            return self.control_files.lock_write(token=token)
 
2514
            return BranchWriteLockResult(self.unlock,
 
2515
                self.control_files.lock_write(token=token))
2339
2516
        except:
2340
2517
            if took_lock:
2341
2518
                self.repository.unlock()
2342
2519
            raise
2343
2520
 
2344
2521
    def lock_read(self):
 
2522
        """Lock the branch for read operations.
 
2523
 
 
2524
        :return: A bzrlib.lock.LogicalLockResult.
 
2525
        """
2345
2526
        if not self.is_locked():
2346
2527
            self._note_lock('r')
2347
2528
        # All-in-one needs to always unlock/lock.
2354
2535
            took_lock = False
2355
2536
        try:
2356
2537
            self.control_files.lock_read()
 
2538
            return LogicalLockResult(self.unlock)
2357
2539
        except:
2358
2540
            if took_lock:
2359
2541
                self.repository.unlock()
2515
2697
        result.target_branch = target
2516
2698
        result.old_revno, result.old_revid = target.last_revision_info()
2517
2699
        self.update_references(target)
2518
 
        if result.old_revid != self.last_revision():
 
2700
        if result.old_revid != stop_revision:
2519
2701
            # We assume that during 'push' this repository is closer than
2520
2702
            # the target.
2521
2703
            graph = self.repository.get_graph(target.repository)
2544
2726
                mode=self.bzrdir._get_file_mode())
2545
2727
 
2546
2728
 
 
2729
class BzrBranchPreSplitOut(BzrBranch):
 
2730
 
 
2731
    def _get_checkout_format(self):
 
2732
        """Return the most suitable metadir for a checkout of this branch.
 
2733
        Weaves are used if this branch's repository uses weaves.
 
2734
        """
 
2735
        from bzrlib.repofmt.weaverepo import RepositoryFormat7
 
2736
        from bzrlib.bzrdir import BzrDirMetaFormat1
 
2737
        format = BzrDirMetaFormat1()
 
2738
        format.repository_format = RepositoryFormat7()
 
2739
        return format
 
2740
 
 
2741
 
2547
2742
class BzrBranch5(BzrBranch):
2548
2743
    """A format 5 branch. This supports new features over plain branches.
2549
2744
 
2922
3117
        try:
2923
3118
            index = self._partial_revision_history_cache.index(revision_id)
2924
3119
        except ValueError:
2925
 
            self._extend_partial_history(stop_revision=revision_id)
 
3120
            try:
 
3121
                self._extend_partial_history(stop_revision=revision_id)
 
3122
            except errors.RevisionNotPresent, e:
 
3123
                raise errors.GhostRevisionsHaveNoRevno(revision_id, e.revision_id)
2926
3124
            index = len(self._partial_revision_history_cache) - 1
2927
3125
            if self._partial_revision_history_cache[index] != revision_id:
2928
3126
                raise errors.NoSuchRevision(self, revision_id)
2983
3181
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
2984
3182
    """
2985
3183
 
 
3184
    @deprecated_method(deprecated_in((2, 3, 0)))
2986
3185
    def __int__(self):
2987
 
        # DEPRECATED: pull used to return the change in revno
 
3186
        """Return the relative change in revno.
 
3187
 
 
3188
        :deprecated: Use `new_revno` and `old_revno` instead.
 
3189
        """
2988
3190
        return self.new_revno - self.old_revno
2989
3191
 
2990
3192
    def report(self, to_file):
3015
3217
        target, otherwise it will be None.
3016
3218
    """
3017
3219
 
 
3220
    @deprecated_method(deprecated_in((2, 3, 0)))
3018
3221
    def __int__(self):
3019
 
        # DEPRECATED: push used to return the change in revno
 
3222
        """Return the relative change in revno.
 
3223
 
 
3224
        :deprecated: Use `new_revno` and `old_revno` instead.
 
3225
        """
3020
3226
        return self.new_revno - self.old_revno
3021
3227
 
3022
3228
    def report(self, to_file):
3145
3351
    _optimisers = []
3146
3352
    """The available optimised InterBranch types."""
3147
3353
 
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)
 
3354
    @classmethod
 
3355
    def _get_branch_formats_to_test(klass):
 
3356
        """Return an iterable of format tuples for testing.
 
3357
        
 
3358
        :return: An iterable of (from_format, to_format) to use when testing
 
3359
            this InterBranch class. Each InterBranch class should define this
 
3360
            method itself.
 
3361
        """
 
3362
        raise NotImplementedError(klass._get_branch_formats_to_test)
3152
3363
 
 
3364
    @needs_write_lock
3153
3365
    def pull(self, overwrite=False, stop_revision=None,
3154
3366
             possible_transports=None, local=False):
3155
3367
        """Mirror source into target branch.
3160
3372
        """
3161
3373
        raise NotImplementedError(self.pull)
3162
3374
 
 
3375
    @needs_write_lock
3163
3376
    def update_revisions(self, stop_revision=None, overwrite=False,
3164
 
                         graph=None):
 
3377
                         graph=None, fetch_tags=True):
3165
3378
        """Pull in new perfect-fit revisions.
3166
3379
 
3167
3380
        :param stop_revision: Updated until the given revision
3169
3382
            to see if it is a proper descendant.
3170
3383
        :param graph: A Graph object that can be used to query history
3171
3384
            information. This can be None.
 
3385
        :param fetch_tags: Flag that specifies if tags from source should be
 
3386
            fetched too.
3172
3387
        :return: None
3173
3388
        """
3174
3389
        raise NotImplementedError(self.update_revisions)
3175
3390
 
 
3391
    @needs_write_lock
3176
3392
    def push(self, overwrite=False, stop_revision=None,
3177
3393
             _override_hook_source_branch=None):
3178
3394
        """Mirror the source branch into the target branch.
3181
3397
        """
3182
3398
        raise NotImplementedError(self.push)
3183
3399
 
 
3400
    @needs_write_lock
 
3401
    def copy_content_into(self, revision_id=None):
 
3402
        """Copy the content of source into target
 
3403
 
 
3404
        revision_id: if not None, the revision history in the new branch will
 
3405
                     be truncated to end with revision_id.
 
3406
        """
 
3407
        raise NotImplementedError(self.copy_content_into)
 
3408
 
3184
3409
 
3185
3410
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
 
 
 
3411
    """InterBranch implementation that uses public Branch functions."""
 
3412
 
 
3413
    @classmethod
 
3414
    def is_compatible(klass, source, target):
 
3415
        # GenericBranch uses the public API, so always compatible
 
3416
        return True
 
3417
 
 
3418
    @classmethod
 
3419
    def _get_branch_formats_to_test(klass):
 
3420
        return [(format_registry.get_default(), format_registry.get_default())]
 
3421
 
 
3422
    @classmethod
 
3423
    def unwrap_format(klass, format):
 
3424
        if isinstance(format, remote.RemoteBranchFormat):
 
3425
            format._ensure_real()
 
3426
            return format._custom_format
 
3427
        return format
 
3428
 
 
3429
    @needs_write_lock
 
3430
    def copy_content_into(self, revision_id=None):
 
3431
        """Copy the content of source into target
 
3432
 
 
3433
        revision_id: if not None, the revision history in the new branch will
 
3434
                     be truncated to end with revision_id.
 
3435
        """
 
3436
        self.source.update_references(self.target)
 
3437
        self.source._synchronize_history(self.target, revision_id)
 
3438
        try:
 
3439
            parent = self.source.get_parent()
 
3440
        except errors.InaccessibleParent, e:
 
3441
            mutter('parent was not accessible to copy: %s', e)
 
3442
        else:
 
3443
            if parent:
 
3444
                self.target.set_parent(parent)
 
3445
        if self.source._push_should_merge_tags():
 
3446
            self.source.tags.merge_to(self.target.tags)
 
3447
 
 
3448
    @needs_write_lock
3193
3449
    def update_revisions(self, stop_revision=None, overwrite=False,
3194
 
        graph=None):
 
3450
        graph=None, fetch_tags=True):
3195
3451
        """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
 
 
 
3452
        other_revno, other_last_revision = self.source.last_revision_info()
 
3453
        stop_revno = None # unknown
 
3454
        if stop_revision is None:
 
3455
            stop_revision = other_last_revision
 
3456
            if _mod_revision.is_null(stop_revision):
 
3457
                # if there are no commits, we're done.
 
3458
                return
 
3459
            stop_revno = other_revno
 
3460
 
 
3461
        # what's the current last revision, before we fetch [and change it
 
3462
        # possibly]
 
3463
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
3464
        # we fetch here so that we don't process data twice in the common
 
3465
        # case of having something to pull, and so that the check for
 
3466
        # already merged can operate on the just fetched graph, which will
 
3467
        # be cached in memory.
 
3468
        if fetch_tags:
 
3469
            fetch_spec_factory = fetch.FetchSpecFactory()
 
3470
            fetch_spec_factory.source_branch = self.source
 
3471
            fetch_spec_factory.source_branch_stop_revision_id = stop_revision
 
3472
            fetch_spec_factory.source_repo = self.source.repository
 
3473
            fetch_spec_factory.target_repo = self.target.repository
 
3474
            fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
 
3475
            fetch_spec = fetch_spec_factory.make_fetch_spec()
 
3476
        else:
 
3477
            fetch_spec = _mod_graph.NotInOtherForRevs(self.target.repository,
 
3478
                self.source.repository, revision_ids=[stop_revision]).execute()
 
3479
        self.target.fetch(self.source, fetch_spec=fetch_spec)
 
3480
        # Check to see if one is an ancestor of the other
 
3481
        if not overwrite:
 
3482
            if graph is None:
 
3483
                graph = self.target.repository.get_graph()
 
3484
            if self.target._check_if_descendant_or_diverged(
 
3485
                    stop_revision, last_rev, graph, self.source):
 
3486
                # stop_revision is a descendant of last_rev, but we aren't
 
3487
                # overwriting, so we're done.
 
3488
                return
 
3489
        if stop_revno is None:
 
3490
            if graph is None:
 
3491
                graph = self.target.repository.get_graph()
 
3492
            this_revno, this_last_revision = \
 
3493
                    self.target.last_revision_info()
 
3494
            stop_revno = graph.find_distance_to_null(stop_revision,
 
3495
                            [(other_last_revision, other_revno),
 
3496
                             (this_last_revision, this_revno)])
 
3497
        self.target.set_last_revision_info(stop_revno, stop_revision)
 
3498
 
 
3499
    @needs_write_lock
3236
3500
    def pull(self, overwrite=False, stop_revision=None,
3237
 
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3501
             possible_transports=None, run_hooks=True,
3238
3502
             _override_hook_target=None, local=False):
3239
 
        """See Branch.pull.
 
3503
        """Pull from source into self, updating my master if any.
3240
3504
 
3241
 
        :param _hook_master: Private parameter - set the branch to
3242
 
            be supplied as the master to pull hooks.
3243
3505
        :param run_hooks: Private parameter - if false, this branch
3244
3506
            is being called because it's the master of the primary branch,
3245
3507
            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
3508
        """
3250
 
        # This type of branch can't be bound.
3251
 
        if local:
 
3509
        bound_location = self.target.get_bound_location()
 
3510
        if local and not bound_location:
3252
3511
            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()
 
3512
        master_branch = None
 
3513
        source_is_master = (self.source.user_url == bound_location)
 
3514
        if not local and bound_location and not source_is_master:
 
3515
            # not pulling from master, so we need to update master.
 
3516
            master_branch = self.target.get_master_branch(possible_transports)
 
3517
            master_branch.lock_write()
3260
3518
        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)
 
3519
            if master_branch:
 
3520
                # pull from source into master.
 
3521
                master_branch.pull(self.source, overwrite, stop_revision,
 
3522
                    run_hooks=False)
 
3523
            return self._pull(overwrite,
 
3524
                stop_revision, _hook_master=master_branch,
 
3525
                run_hooks=run_hooks,
 
3526
                _override_hook_target=_override_hook_target,
 
3527
                merge_tags_to_master=not source_is_master)
3287
3528
        finally:
3288
 
            self.source.unlock()
3289
 
        return result
 
3529
            if master_branch:
 
3530
                master_branch.unlock()
3290
3531
 
3291
3532
    def push(self, overwrite=False, stop_revision=None,
3292
3533
             _override_hook_source_branch=None):
3332
3573
                # push into the master from the source branch.
3333
3574
                self.source._basic_push(master_branch, overwrite, stop_revision)
3334
3575
                # and push into the target branch from the source. Note that we
3335
 
                # push from the source branch again, because its considered the
 
3576
                # push from the source branch again, because it's considered the
3336
3577
                # highest bandwidth repository.
3337
3578
                result = self.source._basic_push(self.target, overwrite,
3338
3579
                    stop_revision)
3354
3595
            _run_hooks()
3355
3596
            return result
3356
3597
 
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
 
 
 
3598
    def _pull(self, overwrite=False, stop_revision=None,
 
3599
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3600
             _override_hook_target=None, local=False,
 
3601
             merge_tags_to_master=True):
 
3602
        """See Branch.pull.
 
3603
 
 
3604
        This function is the core worker, used by GenericInterBranch.pull to
 
3605
        avoid duplication when pulling source->master and source->local.
 
3606
 
 
3607
        :param _hook_master: Private parameter - set the branch to
 
3608
            be supplied as the master to pull hooks.
3374
3609
        :param run_hooks: Private parameter - if false, this branch
3375
3610
            is being called because it's the master of the primary branch,
3376
3611
            so it should not run its hooks.
 
3612
            is being called because it's the master of the primary branch,
 
3613
            so it should not run its hooks.
 
3614
        :param _override_hook_target: Private parameter - set the branch to be
 
3615
            supplied as the target_branch to pull hooks.
 
3616
        :param local: Only update the local branch, and not the bound branch.
3377
3617
        """
3378
 
        bound_location = self.target.get_bound_location()
3379
 
        if local and not bound_location:
 
3618
        # This type of branch can't be bound.
 
3619
        if local:
3380
3620
            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()
 
3621
        result = PullResult()
 
3622
        result.source_branch = self.source
 
3623
        if _override_hook_target is None:
 
3624
            result.target_branch = self.target
 
3625
        else:
 
3626
            result.target_branch = _override_hook_target
 
3627
        self.source.lock_read()
3386
3628
        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)
 
3629
            # We assume that during 'pull' the target repository is closer than
 
3630
            # the source one.
 
3631
            self.source.update_references(self.target)
 
3632
            graph = self.target.repository.get_graph(self.source.repository)
 
3633
            # TODO: Branch formats should have a flag that indicates 
 
3634
            # that revno's are expensive, and pull() should honor that flag.
 
3635
            # -- JRV20090506
 
3636
            result.old_revno, result.old_revid = \
 
3637
                self.target.last_revision_info()
 
3638
            self.target.update_revisions(self.source, stop_revision,
 
3639
                overwrite=overwrite, graph=graph)
 
3640
            # TODO: The old revid should be specified when merging tags, 
 
3641
            # so a tags implementation that versions tags can only 
 
3642
            # pull in the most recent changes. -- JRV20090506
 
3643
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
3644
                overwrite, ignore_master=not merge_tags_to_master)
 
3645
            result.new_revno, result.new_revid = self.target.last_revision_info()
 
3646
            if _hook_master:
 
3647
                result.master_branch = _hook_master
 
3648
                result.local_branch = result.target_branch
 
3649
            else:
 
3650
                result.master_branch = result.target_branch
 
3651
                result.local_branch = None
 
3652
            if run_hooks:
 
3653
                for hook in Branch.hooks['post_pull']:
 
3654
                    hook(result)
3395
3655
        finally:
3396
 
            if master_branch:
3397
 
                master_branch.unlock()
 
3656
            self.source.unlock()
 
3657
        return result
3398
3658
 
3399
3659
 
3400
3660
InterBranch.register_optimiser(GenericInterBranch)
3401
 
InterBranch.register_optimiser(InterToBranch5)