~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Jelmer Vernooij
  • Date: 2011-03-13 21:30:33 UTC
  • mto: This revision was merged to the branch mainline in revision 5724.
  • Revision ID: jelmer@samba.org-20110313213033-ud9t11mm8e3idtti
Add test for per-file-timestamp zipfiles.

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
295
327
    def lock_read(self):
296
328
        """Lock the branch for read operations.
297
329
 
298
 
        :return: An object with an unlock method which will release the lock
299
 
            obtained.
 
330
        :return: A bzrlib.lock.LogicalLockResult.
300
331
        """
301
332
        raise NotImplementedError(self.lock_read)
302
333
 
637
668
        raise errors.UnsupportedOperation(self.get_reference_info, self)
638
669
 
639
670
    @needs_write_lock
640
 
    def fetch(self, from_branch, last_revision=None, pb=None):
 
671
    def fetch(self, from_branch, last_revision=None, fetch_spec=None):
641
672
        """Copy revisions from from_branch into this branch.
642
673
 
643
674
        :param from_branch: Where to copy from.
644
675
        :param last_revision: What revision to stop at (None for at the end
645
676
                              of the branch.
646
 
        :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.
647
681
        :return: None
648
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.")
649
686
        if self.base == from_branch.base:
650
687
            return (0, [])
651
 
        if pb is not None:
652
 
            symbol_versioning.warn(
653
 
                symbol_versioning.deprecated_in((1, 14, 0))
654
 
                % "pb parameter to fetch()")
655
688
        from_branch.lock_read()
656
689
        try:
657
 
            if last_revision is None:
 
690
            if last_revision is None and fetch_spec is None:
658
691
                last_revision = from_branch.last_revision()
659
692
                last_revision = _mod_revision.ensure_null(last_revision)
660
693
            return self.repository.fetch(from_branch.repository,
661
694
                                         revision_id=last_revision,
662
 
                                         pb=pb)
 
695
                                         fetch_spec=fetch_spec)
663
696
        finally:
664
697
            from_branch.unlock()
665
698
 
778
811
 
779
812
    def _unstack(self):
780
813
        """Change a branch to be unstacked, copying data as needed.
781
 
        
 
814
 
782
815
        Don't call this directly, use set_stacked_on_url(None).
783
816
        """
784
817
        pb = ui.ui_factory.nested_progress_bar()
793
826
            old_repository = self.repository
794
827
            if len(old_repository._fallback_repositories) != 1:
795
828
                raise AssertionError("can't cope with fallback repositories "
796
 
                    "of %r" % (self.repository,))
797
 
            # 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()
798
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.
799
879
            old_repository.lock_read()
800
880
            try:
801
 
                # Repositories don't offer an interface to remove fallback
802
 
                # repositories today; take the conceptually simpler option and just
803
 
                # reopen it.  We reopen it starting from the URL so that we
804
 
                # get a separate connection for RemoteRepositories and can
805
 
                # stream from one of them to the other.  This does mean doing
806
 
                # separate SSH connection setup, but unstacking is not a
807
 
                # common operation so it's tolerable.
808
 
                new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
809
 
                new_repository = new_bzrdir.find_repository()
810
 
                self.repository = new_repository
811
 
                if self.repository._fallback_repositories:
812
 
                    raise AssertionError("didn't expect %r to have "
813
 
                        "fallback_repositories"
814
 
                        % (self.repository,))
815
 
                # this is not paired with an unlock because it's just restoring
816
 
                # the previous state; the lock's released when set_stacked_on_url
817
 
                # returns
818
 
                self.repository.lock_write()
819
881
                # XXX: If you unstack a branch while it has a working tree
820
882
                # with a pending merge, the pending-merged revisions will no
821
883
                # longer be present.  You can (probably) revert and remerge.
822
 
                #
823
 
                # XXX: This only fetches up to the tip of the repository; it
824
 
                # doesn't bring across any tags.  That's fairly consistent
825
 
                # with how branch works, but perhaps not ideal.
826
 
                self.repository.fetch(old_repository,
827
 
                    revision_id=self.last_revision(),
828
 
                    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)
829
892
            finally:
830
893
                old_repository.unlock()
831
894
        finally:
836
899
 
837
900
        :seealso: Branch._get_tags_bytes.
838
901
        """
839
 
        return _run_with_write_locked_target(self, self._transport.put_bytes,
840
 
            '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)
841
908
 
842
909
    def _cache_revision_history(self, rev_history):
843
910
        """Set the cached revision history to rev_history.
873
940
        self._merge_sorted_revisions_cache = None
874
941
        self._partial_revision_history_cache = []
875
942
        self._partial_revision_id_to_revno_cache = {}
 
943
        self._tags_bytes = None
876
944
 
877
945
    def _gen_revision_history(self):
878
946
        """Return sequence of revision hashes on to this branch.
939
1007
        else:
940
1008
            return (0, _mod_revision.NULL_REVISION)
941
1009
 
942
 
    @deprecated_method(deprecated_in((1, 6, 0)))
943
 
    def missing_revisions(self, other, stop_revision=None):
944
 
        """Return a list of new revisions that would perfectly fit.
945
 
 
946
 
        If self and other have not diverged, return a list of the revisions
947
 
        present in other, but missing from self.
948
 
        """
949
 
        self_history = self.revision_history()
950
 
        self_len = len(self_history)
951
 
        other_history = other.revision_history()
952
 
        other_len = len(other_history)
953
 
        common_index = min(self_len, other_len) -1
954
 
        if common_index >= 0 and \
955
 
            self_history[common_index] != other_history[common_index]:
956
 
            raise errors.DivergedBranches(self, other)
957
 
 
958
 
        if stop_revision is None:
959
 
            stop_revision = other_len
960
 
        else:
961
 
            if stop_revision > other_len:
962
 
                raise errors.NoSuchRevision(self, stop_revision)
963
 
        return other_history[self_len:stop_revision]
964
 
 
965
 
    @needs_write_lock
966
1010
    def update_revisions(self, other, stop_revision=None, overwrite=False,
967
 
                         graph=None):
 
1011
                         graph=None, fetch_tags=True):
968
1012
        """Pull in new perfect-fit revisions.
969
1013
 
970
1014
        :param other: Another Branch to pull from
973
1017
            to see if it is a proper descendant.
974
1018
        :param graph: A Graph object that can be used to query history
975
1019
            information. This can be None.
 
1020
        :param fetch_tags: Flag that specifies if tags from other should be
 
1021
            fetched too.
976
1022
        :return: None
977
1023
        """
978
1024
        return InterBranch.get(other, self).update_revisions(stop_revision,
979
 
            overwrite, graph)
 
1025
            overwrite, graph, fetch_tags=fetch_tags)
980
1026
 
 
1027
    @deprecated_method(deprecated_in((2, 4, 0)))
981
1028
    def import_last_revision_info(self, source_repo, revno, revid):
982
1029
        """Set the last revision info, importing from another repo if necessary.
983
1030
 
984
 
        This is used by the bound branch code to upload a revision to
985
 
        the master branch first before updating the tip of the local branch.
986
 
 
987
1031
        :param source_repo: Source repository to optionally fetch from
988
1032
        :param revno: Revision number of the new tip
989
1033
        :param revid: Revision id of the new tip
992
1036
            self.repository.fetch(source_repo, revision_id=revid)
993
1037
        self.set_last_revision_info(revno, revid)
994
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
 
995
1061
    def revision_id_to_revno(self, revision_id):
996
1062
        """Given a revision id, return its revno"""
997
1063
        if _mod_revision.is_null(revision_id):
1017
1083
            self._extend_partial_history(distance_from_last)
1018
1084
        return self._partial_revision_history_cache[distance_from_last]
1019
1085
 
1020
 
    @needs_write_lock
1021
1086
    def pull(self, source, overwrite=False, stop_revision=None,
1022
1087
             possible_transports=None, *args, **kwargs):
1023
1088
        """Mirror source into this branch.
1219
1284
        return result
1220
1285
 
1221
1286
    @needs_read_lock
1222
 
    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):
1223
1289
        """Create a new line of development from the branch, into to_bzrdir.
1224
1290
 
1225
1291
        to_bzrdir controls the branch format.
1230
1296
        if (repository_policy is not None and
1231
1297
            repository_policy.requires_stacking()):
1232
1298
            to_bzrdir._format.require_stacking(_skip_repo=True)
1233
 
        result = to_bzrdir.create_branch()
 
1299
        result = to_bzrdir.create_branch(repository=repository)
1234
1300
        result.lock_write()
1235
1301
        try:
1236
1302
            if repository_policy is not None:
1266
1332
                revno = 1
1267
1333
        destination.set_last_revision_info(revno, revision_id)
1268
1334
 
1269
 
    @needs_read_lock
1270
1335
    def copy_content_into(self, destination, revision_id=None):
1271
1336
        """Copy the content of self into destination.
1272
1337
 
1273
1338
        revision_id: if not None, the revision history in the new branch will
1274
1339
                     be truncated to end with revision_id.
1275
1340
        """
1276
 
        self.update_references(destination)
1277
 
        self._synchronize_history(destination, revision_id)
1278
 
        try:
1279
 
            parent = self.get_parent()
1280
 
        except errors.InaccessibleParent, e:
1281
 
            mutter('parent was not accessible to copy: %s', e)
1282
 
        else:
1283
 
            if parent:
1284
 
                destination.set_parent(parent)
1285
 
        if self._push_should_merge_tags():
1286
 
            self.tags.merge_to(destination.tags)
 
1341
        return InterBranch.get(self, destination).copy_content_into(
 
1342
            revision_id=revision_id)
1287
1343
 
1288
1344
    def update_references(self, target):
1289
1345
        if not getattr(self._format, 'supports_reference_locations', False):
1334
1390
        """Return the most suitable metadir for a checkout of this branch.
1335
1391
        Weaves are used if this branch's repository uses weaves.
1336
1392
        """
1337
 
        if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
1338
 
            from bzrlib.repofmt import weaverepo
1339
 
            format = bzrdir.BzrDirMetaFormat1()
1340
 
            format.repository_format = weaverepo.RepositoryFormat7()
1341
 
        else:
1342
 
            format = self.repository.bzrdir.checkout_metadir()
1343
 
            format.set_branch_format(self._format)
 
1393
        format = self.repository.bzrdir.checkout_metadir()
 
1394
        format.set_branch_format(self._format)
1344
1395
        return format
1345
1396
 
1346
1397
    def create_clone_on_transport(self, to_transport, revision_id=None,
1347
 
        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):
1348
1400
        """Create a clone of this branch and its bzrdir.
1349
1401
 
1350
1402
        :param to_transport: The transport to clone onto.
1357
1409
        """
1358
1410
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1359
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
1360
1414
        if revision_id is None:
1361
1415
            revision_id = self.last_revision()
1362
1416
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1363
1417
            revision_id=revision_id, stacked_on=stacked_on,
1364
 
            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)
1365
1420
        return dir_to.open_branch()
1366
1421
 
1367
1422
    def create_checkout(self, to_location, revision_id=None,
1482
1537
        else:
1483
1538
            raise AssertionError("invalid heads: %r" % (heads,))
1484
1539
 
1485
 
 
1486
 
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):
1487
1562
    """An encapsulation of the initialization and open routines for a format.
1488
1563
 
1489
1564
    Formats provide three things:
1492
1567
     * an open routine.
1493
1568
 
1494
1569
    Formats are placed in an dict by their format string for reference
1495
 
    during branch opening. Its not required that these be instances, they
 
1570
    during branch opening. It's not required that these be instances, they
1496
1571
    can be classes themselves with class methods - it simply depends on
1497
1572
    whether state is needed for a given format or not.
1498
1573
 
1501
1576
    object will be created every time regardless.
1502
1577
    """
1503
1578
 
1504
 
    _default_format = None
1505
 
    """The default format used for new branches."""
1506
 
 
1507
 
    _formats = {}
1508
 
    """The known formats."""
1509
 
 
1510
1579
    can_set_append_revisions_only = True
1511
1580
 
1512
1581
    def __eq__(self, other):
1521
1590
        try:
1522
1591
            transport = a_bzrdir.get_branch_transport(None, name=name)
1523
1592
            format_string = transport.get_bytes("format")
1524
 
            return klass._formats[format_string]
 
1593
            return format_registry.get(format_string)
1525
1594
        except errors.NoSuchFile:
1526
1595
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1527
1596
        except KeyError:
1528
1597
            raise errors.UnknownFormatError(format=format_string, kind='branch')
1529
1598
 
1530
1599
    @classmethod
 
1600
    @deprecated_method(deprecated_in((2, 4, 0)))
1531
1601
    def get_default_format(klass):
1532
1602
        """Return the current default format."""
1533
 
        return klass._default_format
1534
 
 
1535
 
    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):
1536
1616
        """Get the target reference of the branch in a_bzrdir.
1537
1617
 
1538
1618
        format probing must have been completed before calling
1540
1620
        in a_bzrdir is correct.
1541
1621
 
1542
1622
        :param a_bzrdir: The bzrdir to get the branch data from.
 
1623
        :param name: Name of the colocated branch to fetch
1543
1624
        :return: None if the branch is not a reference branch.
1544
1625
        """
1545
1626
        return None
1546
1627
 
1547
1628
    @classmethod
1548
 
    def set_reference(self, a_bzrdir, to_branch):
 
1629
    def set_reference(self, a_bzrdir, name, to_branch):
1549
1630
        """Set the target reference of the branch in a_bzrdir.
1550
1631
 
1551
1632
        format probing must have been completed before calling
1553
1634
        in a_bzrdir is correct.
1554
1635
 
1555
1636
        :param a_bzrdir: The bzrdir to set the branch reference for.
 
1637
        :param name: Name of colocated branch to set, None for default
1556
1638
        :param to_branch: branch that the checkout is to reference
1557
1639
        """
1558
1640
        raise NotImplementedError(self.set_reference)
1574
1656
            hook(params)
1575
1657
 
1576
1658
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
1577
 
                           lock_type='metadir', set_format=True):
 
1659
                           repository=None):
1578
1660
        """Initialize a branch in a bzrdir, with specified files
1579
1661
 
1580
1662
        :param a_bzrdir: The bzrdir to initialize the branch in
1581
1663
        :param utf8_files: The files to create as a list of
1582
1664
            (filename, content) tuples
1583
1665
        :param name: Name of colocated branch to create, if any
1584
 
        :param set_format: If True, set the format with
1585
 
            self.get_format_string.  (BzrBranch4 has its format set
1586
 
            elsewhere)
1587
1666
        :return: a branch in this format
1588
1667
        """
1589
1668
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
1590
1669
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
1591
 
        lock_map = {
1592
 
            'metadir': ('lock', lockdir.LockDir),
1593
 
            'branch4': ('branch-lock', lockable_files.TransportLock),
1594
 
        }
1595
 
        lock_name, lock_class = lock_map[lock_type]
1596
1670
        control_files = lockable_files.LockableFiles(branch_transport,
1597
 
            lock_name, lock_class)
 
1671
            'lock', lockdir.LockDir)
1598
1672
        control_files.create_lock()
 
1673
        control_files.lock_write()
1599
1674
        try:
1600
 
            control_files.lock_write()
1601
 
        except errors.LockContention:
1602
 
            if lock_type != 'branch4':
1603
 
                raise
1604
 
            lock_taken = False
1605
 
        else:
1606
 
            lock_taken = True
1607
 
        if set_format:
1608
1675
            utf8_files += [('format', self.get_format_string())]
1609
 
        try:
1610
1676
            for (filename, content) in utf8_files:
1611
1677
                branch_transport.put_bytes(
1612
1678
                    filename, content,
1613
1679
                    mode=a_bzrdir._get_file_mode())
1614
1680
        finally:
1615
 
            if lock_taken:
1616
 
                control_files.unlock()
1617
 
        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)
1618
1684
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
1619
1685
        return branch
1620
1686
 
1621
 
    def initialize(self, a_bzrdir, name=None):
 
1687
    def initialize(self, a_bzrdir, name=None, repository=None):
1622
1688
        """Create a branch of this format in a_bzrdir.
1623
1689
        
1624
1690
        :param name: Name of the colocated branch to create.
1658
1724
        """
1659
1725
        raise NotImplementedError(self.network_name)
1660
1726
 
1661
 
    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):
1662
1729
        """Return the branch object for a_bzrdir
1663
1730
 
1664
1731
        :param a_bzrdir: A BzrDir that contains a branch.
1671
1738
        raise NotImplementedError(self.open)
1672
1739
 
1673
1740
    @classmethod
 
1741
    @deprecated_method(deprecated_in((2, 4, 0)))
1674
1742
    def register_format(klass, format):
1675
 
        """Register a metadir format."""
1676
 
        klass._formats[format.get_format_string()] = format
1677
 
        # Metadir formats have a network name of their format string, and get
1678
 
        # registered as class factories.
1679
 
        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)
1680
1749
 
1681
1750
    @classmethod
 
1751
    @deprecated_method(deprecated_in((2, 4, 0)))
1682
1752
    def set_default_format(klass, format):
1683
 
        klass._default_format = format
 
1753
        format_registry.set_default(format)
1684
1754
 
1685
1755
    def supports_set_append_revisions_only(self):
1686
1756
        """True if this format supports set_append_revisions_only."""
1690
1760
        """True if this format records a stacked-on branch."""
1691
1761
        return False
1692
1762
 
 
1763
    def supports_leaving_lock(self):
 
1764
        """True if this format supports leaving locks in place."""
 
1765
        return False # by default
 
1766
 
1693
1767
    @classmethod
 
1768
    @deprecated_method(deprecated_in((2, 4, 0)))
1694
1769
    def unregister_format(klass, format):
1695
 
        del klass._formats[format.get_format_string()]
 
1770
        format_registry.remove(format)
1696
1771
 
1697
1772
    def __str__(self):
1698
1773
        return self.get_format_description().rstrip()
1702
1777
        return False  # by default
1703
1778
 
1704
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
 
1705
1808
class BranchHooks(Hooks):
1706
1809
    """A dictionary mapping hook name to a list of callables for branch hooks.
1707
1810
 
1734
1837
            "with a bzrlib.branch.PullResult object and only runs in the "
1735
1838
            "bzr client.", (0, 15), None))
1736
1839
        self.create_hook(HookPoint('pre_commit',
1737
 
            "Called after a commit is calculated but before it is is "
 
1840
            "Called after a commit is calculated but before it is "
1738
1841
            "completed. pre_commit is called with (local, master, old_revno, "
1739
1842
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
1740
1843
            "). old_revid is NULL_REVISION for the first commit to a branch, "
1777
1880
            "all are called with the url returned from the previous hook."
1778
1881
            "The order is however undefined.", (1, 9), None))
1779
1882
        self.create_hook(HookPoint('automatic_tag_name',
1780
 
            "Called to determine an automatic tag name for a revision."
 
1883
            "Called to determine an automatic tag name for a revision. "
1781
1884
            "automatic_tag_name is called with (branch, revision_id) and "
1782
1885
            "should return a tag name or None if no tag name could be "
1783
1886
            "determined. The first non-None tag name returned will be used.",
1874
1977
        return self.__dict__ == other.__dict__
1875
1978
 
1876
1979
    def __repr__(self):
1877
 
        if self.branch:
1878
 
            return "<%s of %s>" % (self.__class__.__name__, self.branch)
1879
 
        else:
1880
 
            return "<%s of format:%s bzrdir:%s>" % (
1881
 
                self.__class__.__name__, self.branch,
1882
 
                self.format, self.bzrdir)
 
1980
        return "<%s of %s>" % (self.__class__.__name__, self.branch)
1883
1981
 
1884
1982
 
1885
1983
class SwitchHookParams(object):
1915
2013
            self.revision_id)
1916
2014
 
1917
2015
 
1918
 
class BzrBranchFormat4(BranchFormat):
1919
 
    """Bzr branch format 4.
1920
 
 
1921
 
    This format has:
1922
 
     - a revision-history file.
1923
 
     - a branch-lock lock file [ to be shared with the bzrdir ]
1924
 
    """
1925
 
 
1926
 
    def get_format_description(self):
1927
 
        """See BranchFormat.get_format_description()."""
1928
 
        return "Branch format 4"
1929
 
 
1930
 
    def initialize(self, a_bzrdir, name=None):
1931
 
        """Create a branch of this format in a_bzrdir."""
1932
 
        utf8_files = [('revision-history', ''),
1933
 
                      ('branch-name', ''),
1934
 
                      ]
1935
 
        return self._initialize_helper(a_bzrdir, utf8_files, name=name,
1936
 
                                       lock_type='branch4', set_format=False)
1937
 
 
1938
 
    def __init__(self):
1939
 
        super(BzrBranchFormat4, self).__init__()
1940
 
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
1941
 
 
1942
 
    def network_name(self):
1943
 
        """The network name for this format is the control dirs disk label."""
1944
 
        return self._matchingbzrdir.get_format_string()
1945
 
 
1946
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
1947
 
        """See BranchFormat.open()."""
1948
 
        if not _found:
1949
 
            # we are being called directly and must probe.
1950
 
            raise NotImplementedError
1951
 
        return BzrBranch(_format=self,
1952
 
                         _control_files=a_bzrdir._control_files,
1953
 
                         a_bzrdir=a_bzrdir,
1954
 
                         name=name,
1955
 
                         _repository=a_bzrdir.open_repository())
1956
 
 
1957
 
    def __str__(self):
1958
 
        return "Bazaar-NG branch format 4"
1959
 
 
1960
 
 
1961
2016
class BranchFormatMetadir(BranchFormat):
1962
2017
    """Common logic for meta-dir based branch formats."""
1963
2018
 
1972
2027
        """
1973
2028
        return self.get_format_string()
1974
2029
 
1975
 
    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):
1976
2032
        """See BranchFormat.open()."""
1977
2033
        if not _found:
1978
2034
            format = BranchFormat.find_format(a_bzrdir, name=name)
1983
2039
        try:
1984
2040
            control_files = lockable_files.LockableFiles(transport, 'lock',
1985
2041
                                                         lockdir.LockDir)
 
2042
            if found_repository is None:
 
2043
                found_repository = a_bzrdir.find_repository()
1986
2044
            return self._branch_class()(_format=self,
1987
2045
                              _control_files=control_files,
1988
2046
                              name=name,
1989
2047
                              a_bzrdir=a_bzrdir,
1990
 
                              _repository=a_bzrdir.find_repository(),
 
2048
                              _repository=found_repository,
1991
2049
                              ignore_fallbacks=ignore_fallbacks)
1992
2050
        except errors.NoSuchFile:
1993
2051
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
2000
2058
    def supports_tags(self):
2001
2059
        return True
2002
2060
 
 
2061
    def supports_leaving_lock(self):
 
2062
        return True
 
2063
 
2003
2064
 
2004
2065
class BzrBranchFormat5(BranchFormatMetadir):
2005
2066
    """Bzr branch format 5.
2025
2086
        """See BranchFormat.get_format_description()."""
2026
2087
        return "Branch format 5"
2027
2088
 
2028
 
    def initialize(self, a_bzrdir, name=None):
 
2089
    def initialize(self, a_bzrdir, name=None, repository=None):
2029
2090
        """Create a branch of this format in a_bzrdir."""
2030
2091
        utf8_files = [('revision-history', ''),
2031
2092
                      ('branch-name', ''),
2032
2093
                      ]
2033
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2094
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2034
2095
 
2035
2096
    def supports_tags(self):
2036
2097
        return False
2058
2119
        """See BranchFormat.get_format_description()."""
2059
2120
        return "Branch format 6"
2060
2121
 
2061
 
    def initialize(self, a_bzrdir, name=None):
 
2122
    def initialize(self, a_bzrdir, name=None, repository=None):
2062
2123
        """Create a branch of this format in a_bzrdir."""
2063
2124
        utf8_files = [('last-revision', '0 null:\n'),
2064
2125
                      ('branch.conf', ''),
2065
2126
                      ('tags', ''),
2066
2127
                      ]
2067
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2128
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2068
2129
 
2069
2130
    def make_tags(self, branch):
2070
2131
        """See bzrlib.branch.BranchFormat.make_tags()."""
2088
2149
        """See BranchFormat.get_format_description()."""
2089
2150
        return "Branch format 8"
2090
2151
 
2091
 
    def initialize(self, a_bzrdir, name=None):
 
2152
    def initialize(self, a_bzrdir, name=None, repository=None):
2092
2153
        """Create a branch of this format in a_bzrdir."""
2093
2154
        utf8_files = [('last-revision', '0 null:\n'),
2094
2155
                      ('branch.conf', ''),
2095
2156
                      ('tags', ''),
2096
2157
                      ('references', '')
2097
2158
                      ]
2098
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2159
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2099
2160
 
2100
2161
    def __init__(self):
2101
2162
        super(BzrBranchFormat8, self).__init__()
2124
2185
    This format was introduced in bzr 1.6.
2125
2186
    """
2126
2187
 
2127
 
    def initialize(self, a_bzrdir, name=None):
 
2188
    def initialize(self, a_bzrdir, name=None, repository=None):
2128
2189
        """Create a branch of this format in a_bzrdir."""
2129
2190
        utf8_files = [('last-revision', '0 null:\n'),
2130
2191
                      ('branch.conf', ''),
2131
2192
                      ('tags', ''),
2132
2193
                      ]
2133
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2194
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2134
2195
 
2135
2196
    def _branch_class(self):
2136
2197
        return BzrBranch7
2168
2229
        """See BranchFormat.get_format_description()."""
2169
2230
        return "Checkout reference format 1"
2170
2231
 
2171
 
    def get_reference(self, a_bzrdir):
 
2232
    def get_reference(self, a_bzrdir, name=None):
2172
2233
        """See BranchFormat.get_reference()."""
2173
 
        transport = a_bzrdir.get_branch_transport(None)
 
2234
        transport = a_bzrdir.get_branch_transport(None, name=name)
2174
2235
        return transport.get_bytes('location')
2175
2236
 
2176
 
    def set_reference(self, a_bzrdir, to_branch):
 
2237
    def set_reference(self, a_bzrdir, name, to_branch):
2177
2238
        """See BranchFormat.set_reference()."""
2178
 
        transport = a_bzrdir.get_branch_transport(None)
 
2239
        transport = a_bzrdir.get_branch_transport(None, name=name)
2179
2240
        location = transport.put_bytes('location', to_branch.base)
2180
2241
 
2181
 
    def initialize(self, a_bzrdir, name=None, target_branch=None):
 
2242
    def initialize(self, a_bzrdir, name=None, target_branch=None,
 
2243
            repository=None):
2182
2244
        """Create a branch of this format in a_bzrdir."""
2183
2245
        if target_branch is None:
2184
2246
            # this format does not implement branch itself, thus the implicit
2212
2274
        return clone
2213
2275
 
2214
2276
    def open(self, a_bzrdir, name=None, _found=False, location=None,
2215
 
             possible_transports=None, ignore_fallbacks=False):
 
2277
             possible_transports=None, ignore_fallbacks=False,
 
2278
             found_repository=None):
2216
2279
        """Return the branch that the branch reference in a_bzrdir points at.
2217
2280
 
2218
2281
        :param a_bzrdir: A BzrDir that contains a branch.
2232
2295
                raise AssertionError("wrong format %r found for %r" %
2233
2296
                    (format, self))
2234
2297
        if location is None:
2235
 
            location = self.get_reference(a_bzrdir)
 
2298
            location = self.get_reference(a_bzrdir, name)
2236
2299
        real_bzrdir = bzrdir.BzrDir.open(
2237
2300
            location, possible_transports=possible_transports)
2238
2301
        result = real_bzrdir.open_branch(name=name, 
2249
2312
        return result
2250
2313
 
2251
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
 
2252
2329
network_format_registry = registry.FormatRegistry()
2253
2330
"""Registry of formats indexed by their network name.
2254
2331
 
2257
2334
BranchFormat.network_name() for more detail.
2258
2335
"""
2259
2336
 
 
2337
format_registry = BranchFormatRegistry(network_format_registry)
 
2338
 
2260
2339
 
2261
2340
# formats which have no format string are not discoverable
2262
2341
# and not independently creatable, so are not registered.
2264
2343
__format6 = BzrBranchFormat6()
2265
2344
__format7 = BzrBranchFormat7()
2266
2345
__format8 = BzrBranchFormat8()
2267
 
BranchFormat.register_format(__format5)
2268
 
BranchFormat.register_format(BranchReferenceFormat())
2269
 
BranchFormat.register_format(__format6)
2270
 
BranchFormat.register_format(__format7)
2271
 
BranchFormat.register_format(__format8)
2272
 
BranchFormat.set_default_format(__format7)
2273
 
_legacy_formats = [BzrBranchFormat4(),
2274
 
    ]
2275
 
network_format_registry.register(
2276
 
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
2277
 
 
2278
 
 
2279
 
class BranchWriteLockResult(object):
 
2346
format_registry.register(__format5)
 
2347
format_registry.register(BranchReferenceFormat())
 
2348
format_registry.register(__format6)
 
2349
format_registry.register(__format7)
 
2350
format_registry.register(__format8)
 
2351
format_registry.set_default(__format7)
 
2352
 
 
2353
 
 
2354
class BranchWriteLockResult(LogicalLockResult):
2280
2355
    """The result of write locking a branch.
2281
2356
 
2282
2357
    :ivar branch_token: The token obtained from the underlying branch lock, or
2285
2360
    """
2286
2361
 
2287
2362
    def __init__(self, unlock, branch_token):
 
2363
        LogicalLockResult.__init__(self, unlock)
2288
2364
        self.branch_token = branch_token
2289
 
        self.unlock = unlock
2290
2365
 
2291
 
    def __str__(self):
 
2366
    def __repr__(self):
2292
2367
        return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
2293
2368
            self.unlock)
2294
2369
 
2379
2454
    def lock_read(self):
2380
2455
        """Lock the branch for read operations.
2381
2456
 
2382
 
        :return: An object with an unlock method which will release the lock
2383
 
            obtained.
 
2457
        :return: A bzrlib.lock.LogicalLockResult.
2384
2458
        """
2385
2459
        if not self.is_locked():
2386
2460
            self._note_lock('r')
2394
2468
            took_lock = False
2395
2469
        try:
2396
2470
            self.control_files.lock_read()
2397
 
            return self
 
2471
            return LogicalLockResult(self.unlock)
2398
2472
        except:
2399
2473
            if took_lock:
2400
2474
                self.repository.unlock()
2556
2630
        result.target_branch = target
2557
2631
        result.old_revno, result.old_revid = target.last_revision_info()
2558
2632
        self.update_references(target)
2559
 
        if result.old_revid != self.last_revision():
 
2633
        if result.old_revid != stop_revision:
2560
2634
            # We assume that during 'push' this repository is closer than
2561
2635
            # the target.
2562
2636
            graph = self.repository.get_graph(target.repository)
2963
3037
        try:
2964
3038
            index = self._partial_revision_history_cache.index(revision_id)
2965
3039
        except ValueError:
2966
 
            self._extend_partial_history(stop_revision=revision_id)
 
3040
            try:
 
3041
                self._extend_partial_history(stop_revision=revision_id)
 
3042
            except errors.RevisionNotPresent, e:
 
3043
                raise errors.GhostRevisionsHaveNoRevno(revision_id, e.revision_id)
2967
3044
            index = len(self._partial_revision_history_cache) - 1
2968
3045
            if self._partial_revision_history_cache[index] != revision_id:
2969
3046
                raise errors.NoSuchRevision(self, revision_id)
3024
3101
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
3025
3102
    """
3026
3103
 
 
3104
    @deprecated_method(deprecated_in((2, 3, 0)))
3027
3105
    def __int__(self):
3028
 
        # DEPRECATED: pull used to return the change in revno
 
3106
        """Return the relative change in revno.
 
3107
 
 
3108
        :deprecated: Use `new_revno` and `old_revno` instead.
 
3109
        """
3029
3110
        return self.new_revno - self.old_revno
3030
3111
 
3031
3112
    def report(self, to_file):
3056
3137
        target, otherwise it will be None.
3057
3138
    """
3058
3139
 
 
3140
    @deprecated_method(deprecated_in((2, 3, 0)))
3059
3141
    def __int__(self):
3060
 
        # DEPRECATED: push used to return the change in revno
 
3142
        """Return the relative change in revno.
 
3143
 
 
3144
        :deprecated: Use `new_revno` and `old_revno` instead.
 
3145
        """
3061
3146
        return self.new_revno - self.old_revno
3062
3147
 
3063
3148
    def report(self, to_file):
3186
3271
    _optimisers = []
3187
3272
    """The available optimised InterBranch types."""
3188
3273
 
3189
 
    @staticmethod
3190
 
    def _get_branch_formats_to_test():
3191
 
        """Return a tuple with the Branch formats to use when testing."""
3192
 
        raise NotImplementedError(InterBranch._get_branch_formats_to_test)
 
3274
    @classmethod
 
3275
    def _get_branch_formats_to_test(klass):
 
3276
        """Return an iterable of format tuples for testing.
 
3277
        
 
3278
        :return: An iterable of (from_format, to_format) to use when testing
 
3279
            this InterBranch class. Each InterBranch class should define this
 
3280
            method itself.
 
3281
        """
 
3282
        raise NotImplementedError(klass._get_branch_formats_to_test)
3193
3283
 
 
3284
    @needs_write_lock
3194
3285
    def pull(self, overwrite=False, stop_revision=None,
3195
3286
             possible_transports=None, local=False):
3196
3287
        """Mirror source into target branch.
3201
3292
        """
3202
3293
        raise NotImplementedError(self.pull)
3203
3294
 
 
3295
    @needs_write_lock
3204
3296
    def update_revisions(self, stop_revision=None, overwrite=False,
3205
 
                         graph=None):
 
3297
                         graph=None, fetch_tags=True):
3206
3298
        """Pull in new perfect-fit revisions.
3207
3299
 
3208
3300
        :param stop_revision: Updated until the given revision
3210
3302
            to see if it is a proper descendant.
3211
3303
        :param graph: A Graph object that can be used to query history
3212
3304
            information. This can be None.
 
3305
        :param fetch_tags: Flag that specifies if tags from source should be
 
3306
            fetched too.
3213
3307
        :return: None
3214
3308
        """
3215
3309
        raise NotImplementedError(self.update_revisions)
3216
3310
 
 
3311
    @needs_write_lock
3217
3312
    def push(self, overwrite=False, stop_revision=None,
3218
3313
             _override_hook_source_branch=None):
3219
3314
        """Mirror the source branch into the target branch.
3222
3317
        """
3223
3318
        raise NotImplementedError(self.push)
3224
3319
 
 
3320
    @needs_write_lock
 
3321
    def copy_content_into(self, revision_id=None):
 
3322
        """Copy the content of source into target
 
3323
 
 
3324
        revision_id: if not None, the revision history in the new branch will
 
3325
                     be truncated to end with revision_id.
 
3326
        """
 
3327
        raise NotImplementedError(self.copy_content_into)
 
3328
 
3225
3329
 
3226
3330
class GenericInterBranch(InterBranch):
3227
 
    """InterBranch implementation that uses public Branch functions.
3228
 
    """
3229
 
 
3230
 
    @staticmethod
3231
 
    def _get_branch_formats_to_test():
3232
 
        return BranchFormat._default_format, BranchFormat._default_format
3233
 
 
 
3331
    """InterBranch implementation that uses public Branch functions."""
 
3332
 
 
3333
    @classmethod
 
3334
    def is_compatible(klass, source, target):
 
3335
        # GenericBranch uses the public API, so always compatible
 
3336
        return True
 
3337
 
 
3338
    @classmethod
 
3339
    def _get_branch_formats_to_test(klass):
 
3340
        return [(format_registry.get_default(), format_registry.get_default())]
 
3341
 
 
3342
    @classmethod
 
3343
    def unwrap_format(klass, format):
 
3344
        if isinstance(format, remote.RemoteBranchFormat):
 
3345
            format._ensure_real()
 
3346
            return format._custom_format
 
3347
        return format
 
3348
 
 
3349
    @needs_write_lock
 
3350
    def copy_content_into(self, revision_id=None):
 
3351
        """Copy the content of source into target
 
3352
 
 
3353
        revision_id: if not None, the revision history in the new branch will
 
3354
                     be truncated to end with revision_id.
 
3355
        """
 
3356
        self.source.update_references(self.target)
 
3357
        self.source._synchronize_history(self.target, revision_id)
 
3358
        try:
 
3359
            parent = self.source.get_parent()
 
3360
        except errors.InaccessibleParent, e:
 
3361
            mutter('parent was not accessible to copy: %s', e)
 
3362
        else:
 
3363
            if parent:
 
3364
                self.target.set_parent(parent)
 
3365
        if self.source._push_should_merge_tags():
 
3366
            self.source.tags.merge_to(self.target.tags)
 
3367
 
 
3368
    @needs_write_lock
3234
3369
    def update_revisions(self, stop_revision=None, overwrite=False,
3235
 
        graph=None):
 
3370
        graph=None, fetch_tags=True):
3236
3371
        """See InterBranch.update_revisions()."""
3237
 
        self.source.lock_read()
3238
 
        try:
3239
 
            other_revno, other_last_revision = self.source.last_revision_info()
3240
 
            stop_revno = None # unknown
3241
 
            if stop_revision is None:
3242
 
                stop_revision = other_last_revision
3243
 
                if _mod_revision.is_null(stop_revision):
3244
 
                    # if there are no commits, we're done.
3245
 
                    return
3246
 
                stop_revno = other_revno
3247
 
 
3248
 
            # what's the current last revision, before we fetch [and change it
3249
 
            # possibly]
3250
 
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
3251
 
            # we fetch here so that we don't process data twice in the common
3252
 
            # case of having something to pull, and so that the check for
3253
 
            # already merged can operate on the just fetched graph, which will
3254
 
            # be cached in memory.
3255
 
            self.target.fetch(self.source, stop_revision)
3256
 
            # Check to see if one is an ancestor of the other
3257
 
            if not overwrite:
3258
 
                if graph is None:
3259
 
                    graph = self.target.repository.get_graph()
3260
 
                if self.target._check_if_descendant_or_diverged(
3261
 
                        stop_revision, last_rev, graph, self.source):
3262
 
                    # stop_revision is a descendant of last_rev, but we aren't
3263
 
                    # overwriting, so we're done.
3264
 
                    return
3265
 
            if stop_revno is None:
3266
 
                if graph is None:
3267
 
                    graph = self.target.repository.get_graph()
3268
 
                this_revno, this_last_revision = \
3269
 
                        self.target.last_revision_info()
3270
 
                stop_revno = graph.find_distance_to_null(stop_revision,
3271
 
                                [(other_last_revision, other_revno),
3272
 
                                 (this_last_revision, this_revno)])
3273
 
            self.target.set_last_revision_info(stop_revno, stop_revision)
3274
 
        finally:
3275
 
            self.source.unlock()
3276
 
 
 
3372
        other_revno, other_last_revision = self.source.last_revision_info()
 
3373
        stop_revno = None # unknown
 
3374
        if stop_revision is None:
 
3375
            stop_revision = other_last_revision
 
3376
            if _mod_revision.is_null(stop_revision):
 
3377
                # if there are no commits, we're done.
 
3378
                return
 
3379
            stop_revno = other_revno
 
3380
 
 
3381
        # what's the current last revision, before we fetch [and change it
 
3382
        # possibly]
 
3383
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
3384
        # we fetch here so that we don't process data twice in the common
 
3385
        # case of having something to pull, and so that the check for
 
3386
        # already merged can operate on the just fetched graph, which will
 
3387
        # be cached in memory.
 
3388
        if fetch_tags:
 
3389
            fetch_spec_factory = fetch.FetchSpecFactory()
 
3390
            fetch_spec_factory.source_branch = self.source
 
3391
            fetch_spec_factory.source_branch_stop_revision_id = stop_revision
 
3392
            fetch_spec_factory.source_repo = self.source.repository
 
3393
            fetch_spec_factory.target_repo = self.target.repository
 
3394
            fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
 
3395
            fetch_spec = fetch_spec_factory.make_fetch_spec()
 
3396
        else:
 
3397
            fetch_spec = _mod_graph.NotInOtherForRevs(self.target.repository,
 
3398
                self.source.repository, revision_ids=[stop_revision]).execute()
 
3399
        self.target.fetch(self.source, fetch_spec=fetch_spec)
 
3400
        # Check to see if one is an ancestor of the other
 
3401
        if not overwrite:
 
3402
            if graph is None:
 
3403
                graph = self.target.repository.get_graph()
 
3404
            if self.target._check_if_descendant_or_diverged(
 
3405
                    stop_revision, last_rev, graph, self.source):
 
3406
                # stop_revision is a descendant of last_rev, but we aren't
 
3407
                # overwriting, so we're done.
 
3408
                return
 
3409
        if stop_revno is None:
 
3410
            if graph is None:
 
3411
                graph = self.target.repository.get_graph()
 
3412
            this_revno, this_last_revision = \
 
3413
                    self.target.last_revision_info()
 
3414
            stop_revno = graph.find_distance_to_null(stop_revision,
 
3415
                            [(other_last_revision, other_revno),
 
3416
                             (this_last_revision, this_revno)])
 
3417
        self.target.set_last_revision_info(stop_revno, stop_revision)
 
3418
 
 
3419
    @needs_write_lock
3277
3420
    def pull(self, overwrite=False, stop_revision=None,
3278
 
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3421
             possible_transports=None, run_hooks=True,
3279
3422
             _override_hook_target=None, local=False):
3280
 
        """See Branch.pull.
 
3423
        """Pull from source into self, updating my master if any.
3281
3424
 
3282
 
        :param _hook_master: Private parameter - set the branch to
3283
 
            be supplied as the master to pull hooks.
3284
3425
        :param run_hooks: Private parameter - if false, this branch
3285
3426
            is being called because it's the master of the primary branch,
3286
3427
            so it should not run its hooks.
3287
 
        :param _override_hook_target: Private parameter - set the branch to be
3288
 
            supplied as the target_branch to pull hooks.
3289
 
        :param local: Only update the local branch, and not the bound branch.
3290
3428
        """
3291
 
        # This type of branch can't be bound.
3292
 
        if local:
 
3429
        bound_location = self.target.get_bound_location()
 
3430
        if local and not bound_location:
3293
3431
            raise errors.LocalRequiresBoundBranch()
3294
 
        result = PullResult()
3295
 
        result.source_branch = self.source
3296
 
        if _override_hook_target is None:
3297
 
            result.target_branch = self.target
3298
 
        else:
3299
 
            result.target_branch = _override_hook_target
3300
 
        self.source.lock_read()
 
3432
        master_branch = None
 
3433
        source_is_master = (self.source.user_url == bound_location)
 
3434
        if not local and bound_location and not source_is_master:
 
3435
            # not pulling from master, so we need to update master.
 
3436
            master_branch = self.target.get_master_branch(possible_transports)
 
3437
            master_branch.lock_write()
3301
3438
        try:
3302
 
            # We assume that during 'pull' the target repository is closer than
3303
 
            # the source one.
3304
 
            self.source.update_references(self.target)
3305
 
            graph = self.target.repository.get_graph(self.source.repository)
3306
 
            # TODO: Branch formats should have a flag that indicates 
3307
 
            # that revno's are expensive, and pull() should honor that flag.
3308
 
            # -- JRV20090506
3309
 
            result.old_revno, result.old_revid = \
3310
 
                self.target.last_revision_info()
3311
 
            self.target.update_revisions(self.source, stop_revision,
3312
 
                overwrite=overwrite, graph=graph)
3313
 
            # TODO: The old revid should be specified when merging tags, 
3314
 
            # so a tags implementation that versions tags can only 
3315
 
            # pull in the most recent changes. -- JRV20090506
3316
 
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3317
 
                overwrite)
3318
 
            result.new_revno, result.new_revid = self.target.last_revision_info()
3319
 
            if _hook_master:
3320
 
                result.master_branch = _hook_master
3321
 
                result.local_branch = result.target_branch
3322
 
            else:
3323
 
                result.master_branch = result.target_branch
3324
 
                result.local_branch = None
3325
 
            if run_hooks:
3326
 
                for hook in Branch.hooks['post_pull']:
3327
 
                    hook(result)
 
3439
            if master_branch:
 
3440
                # pull from source into master.
 
3441
                master_branch.pull(self.source, overwrite, stop_revision,
 
3442
                    run_hooks=False)
 
3443
            return self._pull(overwrite,
 
3444
                stop_revision, _hook_master=master_branch,
 
3445
                run_hooks=run_hooks,
 
3446
                _override_hook_target=_override_hook_target,
 
3447
                merge_tags_to_master=not source_is_master)
3328
3448
        finally:
3329
 
            self.source.unlock()
3330
 
        return result
 
3449
            if master_branch:
 
3450
                master_branch.unlock()
3331
3451
 
3332
3452
    def push(self, overwrite=False, stop_revision=None,
3333
3453
             _override_hook_source_branch=None):
3373
3493
                # push into the master from the source branch.
3374
3494
                self.source._basic_push(master_branch, overwrite, stop_revision)
3375
3495
                # and push into the target branch from the source. Note that we
3376
 
                # push from the source branch again, because its considered the
 
3496
                # push from the source branch again, because it's considered the
3377
3497
                # highest bandwidth repository.
3378
3498
                result = self.source._basic_push(self.target, overwrite,
3379
3499
                    stop_revision)
3395
3515
            _run_hooks()
3396
3516
            return result
3397
3517
 
3398
 
    @classmethod
3399
 
    def is_compatible(self, source, target):
3400
 
        # GenericBranch uses the public API, so always compatible
3401
 
        return True
3402
 
 
3403
 
 
3404
 
class InterToBranch5(GenericInterBranch):
3405
 
 
3406
 
    @staticmethod
3407
 
    def _get_branch_formats_to_test():
3408
 
        return BranchFormat._default_format, BzrBranchFormat5()
3409
 
 
3410
 
    def pull(self, overwrite=False, stop_revision=None,
3411
 
             possible_transports=None, run_hooks=True,
3412
 
             _override_hook_target=None, local=False):
3413
 
        """Pull from source into self, updating my master if any.
3414
 
 
 
3518
    def _pull(self, overwrite=False, stop_revision=None,
 
3519
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3520
             _override_hook_target=None, local=False,
 
3521
             merge_tags_to_master=True):
 
3522
        """See Branch.pull.
 
3523
 
 
3524
        This function is the core worker, used by GenericInterBranch.pull to
 
3525
        avoid duplication when pulling source->master and source->local.
 
3526
 
 
3527
        :param _hook_master: Private parameter - set the branch to
 
3528
            be supplied as the master to pull hooks.
3415
3529
        :param run_hooks: Private parameter - if false, this branch
3416
3530
            is being called because it's the master of the primary branch,
3417
3531
            so it should not run its hooks.
 
3532
            is being called because it's the master of the primary branch,
 
3533
            so it should not run its hooks.
 
3534
        :param _override_hook_target: Private parameter - set the branch to be
 
3535
            supplied as the target_branch to pull hooks.
 
3536
        :param local: Only update the local branch, and not the bound branch.
3418
3537
        """
3419
 
        bound_location = self.target.get_bound_location()
3420
 
        if local and not bound_location:
 
3538
        # This type of branch can't be bound.
 
3539
        if local:
3421
3540
            raise errors.LocalRequiresBoundBranch()
3422
 
        master_branch = None
3423
 
        if not local and bound_location and self.source.user_url != bound_location:
3424
 
            # not pulling from master, so we need to update master.
3425
 
            master_branch = self.target.get_master_branch(possible_transports)
3426
 
            master_branch.lock_write()
 
3541
        result = PullResult()
 
3542
        result.source_branch = self.source
 
3543
        if _override_hook_target is None:
 
3544
            result.target_branch = self.target
 
3545
        else:
 
3546
            result.target_branch = _override_hook_target
 
3547
        self.source.lock_read()
3427
3548
        try:
3428
 
            if master_branch:
3429
 
                # pull from source into master.
3430
 
                master_branch.pull(self.source, overwrite, stop_revision,
3431
 
                    run_hooks=False)
3432
 
            return super(InterToBranch5, self).pull(overwrite,
3433
 
                stop_revision, _hook_master=master_branch,
3434
 
                run_hooks=run_hooks,
3435
 
                _override_hook_target=_override_hook_target)
 
3549
            # We assume that during 'pull' the target repository is closer than
 
3550
            # the source one.
 
3551
            self.source.update_references(self.target)
 
3552
            graph = self.target.repository.get_graph(self.source.repository)
 
3553
            # TODO: Branch formats should have a flag that indicates 
 
3554
            # that revno's are expensive, and pull() should honor that flag.
 
3555
            # -- JRV20090506
 
3556
            result.old_revno, result.old_revid = \
 
3557
                self.target.last_revision_info()
 
3558
            self.target.update_revisions(self.source, stop_revision,
 
3559
                overwrite=overwrite, graph=graph)
 
3560
            # TODO: The old revid should be specified when merging tags, 
 
3561
            # so a tags implementation that versions tags can only 
 
3562
            # pull in the most recent changes. -- JRV20090506
 
3563
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
3564
                overwrite, ignore_master=not merge_tags_to_master)
 
3565
            result.new_revno, result.new_revid = self.target.last_revision_info()
 
3566
            if _hook_master:
 
3567
                result.master_branch = _hook_master
 
3568
                result.local_branch = result.target_branch
 
3569
            else:
 
3570
                result.master_branch = result.target_branch
 
3571
                result.local_branch = None
 
3572
            if run_hooks:
 
3573
                for hook in Branch.hooks['post_pull']:
 
3574
                    hook(result)
3436
3575
        finally:
3437
 
            if master_branch:
3438
 
                master_branch.unlock()
 
3576
            self.source.unlock()
 
3577
        return result
3439
3578
 
3440
3579
 
3441
3580
InterBranch.register_optimiser(GenericInterBranch)
3442
 
InterBranch.register_optimiser(InterToBranch5)