/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Jelmer Vernooij
  • Date: 2011-03-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
62
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
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
636
668
        raise errors.UnsupportedOperation(self.get_reference_info, self)
637
669
 
638
670
    @needs_write_lock
639
 
    def fetch(self, from_branch, last_revision=None, pb=None):
 
671
    def fetch(self, from_branch, last_revision=None, fetch_spec=None):
640
672
        """Copy revisions from from_branch into this branch.
641
673
 
642
674
        :param from_branch: Where to copy from.
643
675
        :param last_revision: What revision to stop at (None for at the end
644
676
                              of the branch.
645
 
        :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.
646
681
        :return: None
647
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.")
648
686
        if self.base == from_branch.base:
649
687
            return (0, [])
650
 
        if pb is not None:
651
 
            symbol_versioning.warn(
652
 
                symbol_versioning.deprecated_in((1, 14, 0))
653
 
                % "pb parameter to fetch()")
654
688
        from_branch.lock_read()
655
689
        try:
656
 
            if last_revision is None:
 
690
            if last_revision is None and fetch_spec is None:
657
691
                last_revision = from_branch.last_revision()
658
692
                last_revision = _mod_revision.ensure_null(last_revision)
659
693
            return self.repository.fetch(from_branch.repository,
660
694
                                         revision_id=last_revision,
661
 
                                         pb=pb)
 
695
                                         fetch_spec=fetch_spec)
662
696
        finally:
663
697
            from_branch.unlock()
664
698
 
777
811
 
778
812
    def _unstack(self):
779
813
        """Change a branch to be unstacked, copying data as needed.
780
 
        
 
814
 
781
815
        Don't call this directly, use set_stacked_on_url(None).
782
816
        """
783
817
        pb = ui.ui_factory.nested_progress_bar()
792
826
            old_repository = self.repository
793
827
            if len(old_repository._fallback_repositories) != 1:
794
828
                raise AssertionError("can't cope with fallback repositories "
795
 
                    "of %r" % (self.repository,))
796
 
            # 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()
797
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.
798
879
            old_repository.lock_read()
799
880
            try:
800
 
                # Repositories don't offer an interface to remove fallback
801
 
                # repositories today; take the conceptually simpler option and just
802
 
                # reopen it.  We reopen it starting from the URL so that we
803
 
                # get a separate connection for RemoteRepositories and can
804
 
                # stream from one of them to the other.  This does mean doing
805
 
                # separate SSH connection setup, but unstacking is not a
806
 
                # common operation so it's tolerable.
807
 
                new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
808
 
                new_repository = new_bzrdir.find_repository()
809
 
                self.repository = new_repository
810
 
                if self.repository._fallback_repositories:
811
 
                    raise AssertionError("didn't expect %r to have "
812
 
                        "fallback_repositories"
813
 
                        % (self.repository,))
814
 
                # this is not paired with an unlock because it's just restoring
815
 
                # the previous state; the lock's released when set_stacked_on_url
816
 
                # returns
817
 
                self.repository.lock_write()
818
881
                # XXX: If you unstack a branch while it has a working tree
819
882
                # with a pending merge, the pending-merged revisions will no
820
883
                # longer be present.  You can (probably) revert and remerge.
821
 
                #
822
 
                # XXX: This only fetches up to the tip of the repository; it
823
 
                # doesn't bring across any tags.  That's fairly consistent
824
 
                # with how branch works, but perhaps not ideal.
825
 
                self.repository.fetch(old_repository,
826
 
                    revision_id=self.last_revision(),
827
 
                    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)
828
892
            finally:
829
893
                old_repository.unlock()
830
894
        finally:
835
899
 
836
900
        :seealso: Branch._get_tags_bytes.
837
901
        """
838
 
        return _run_with_write_locked_target(self, self._transport.put_bytes,
839
 
            '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)
840
908
 
841
909
    def _cache_revision_history(self, rev_history):
842
910
        """Set the cached revision history to rev_history.
872
940
        self._merge_sorted_revisions_cache = None
873
941
        self._partial_revision_history_cache = []
874
942
        self._partial_revision_id_to_revno_cache = {}
 
943
        self._tags_bytes = None
875
944
 
876
945
    def _gen_revision_history(self):
877
946
        """Return sequence of revision hashes on to this branch.
938
1007
        else:
939
1008
            return (0, _mod_revision.NULL_REVISION)
940
1009
 
941
 
    @deprecated_method(deprecated_in((1, 6, 0)))
942
 
    def missing_revisions(self, other, stop_revision=None):
943
 
        """Return a list of new revisions that would perfectly fit.
944
 
 
945
 
        If self and other have not diverged, return a list of the revisions
946
 
        present in other, but missing from self.
947
 
        """
948
 
        self_history = self.revision_history()
949
 
        self_len = len(self_history)
950
 
        other_history = other.revision_history()
951
 
        other_len = len(other_history)
952
 
        common_index = min(self_len, other_len) -1
953
 
        if common_index >= 0 and \
954
 
            self_history[common_index] != other_history[common_index]:
955
 
            raise errors.DivergedBranches(self, other)
956
 
 
957
 
        if stop_revision is None:
958
 
            stop_revision = other_len
959
 
        else:
960
 
            if stop_revision > other_len:
961
 
                raise errors.NoSuchRevision(self, stop_revision)
962
 
        return other_history[self_len:stop_revision]
963
 
 
964
 
    @needs_write_lock
965
1010
    def update_revisions(self, other, stop_revision=None, overwrite=False,
966
 
                         graph=None):
 
1011
                         graph=None, fetch_tags=True):
967
1012
        """Pull in new perfect-fit revisions.
968
1013
 
969
1014
        :param other: Another Branch to pull from
972
1017
            to see if it is a proper descendant.
973
1018
        :param graph: A Graph object that can be used to query history
974
1019
            information. This can be None.
 
1020
        :param fetch_tags: Flag that specifies if tags from other should be
 
1021
            fetched too.
975
1022
        :return: None
976
1023
        """
977
1024
        return InterBranch.get(other, self).update_revisions(stop_revision,
978
 
            overwrite, graph)
 
1025
            overwrite, graph, fetch_tags=fetch_tags)
979
1026
 
 
1027
    @deprecated_method(deprecated_in((2, 4, 0)))
980
1028
    def import_last_revision_info(self, source_repo, revno, revid):
981
1029
        """Set the last revision info, importing from another repo if necessary.
982
1030
 
983
 
        This is used by the bound branch code to upload a revision to
984
 
        the master branch first before updating the tip of the local branch.
985
 
 
986
1031
        :param source_repo: Source repository to optionally fetch from
987
1032
        :param revno: Revision number of the new tip
988
1033
        :param revid: Revision id of the new tip
991
1036
            self.repository.fetch(source_repo, revision_id=revid)
992
1037
        self.set_last_revision_info(revno, revid)
993
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
 
994
1061
    def revision_id_to_revno(self, revision_id):
995
1062
        """Given a revision id, return its revno"""
996
1063
        if _mod_revision.is_null(revision_id):
1016
1083
            self._extend_partial_history(distance_from_last)
1017
1084
        return self._partial_revision_history_cache[distance_from_last]
1018
1085
 
1019
 
    @needs_write_lock
1020
1086
    def pull(self, source, overwrite=False, stop_revision=None,
1021
1087
             possible_transports=None, *args, **kwargs):
1022
1088
        """Mirror source into this branch.
1218
1284
        return result
1219
1285
 
1220
1286
    @needs_read_lock
1221
 
    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):
1222
1289
        """Create a new line of development from the branch, into to_bzrdir.
1223
1290
 
1224
1291
        to_bzrdir controls the branch format.
1229
1296
        if (repository_policy is not None and
1230
1297
            repository_policy.requires_stacking()):
1231
1298
            to_bzrdir._format.require_stacking(_skip_repo=True)
1232
 
        result = to_bzrdir.create_branch()
 
1299
        result = to_bzrdir.create_branch(repository=repository)
1233
1300
        result.lock_write()
1234
1301
        try:
1235
1302
            if repository_policy is not None:
1265
1332
                revno = 1
1266
1333
        destination.set_last_revision_info(revno, revision_id)
1267
1334
 
1268
 
    @needs_read_lock
1269
1335
    def copy_content_into(self, destination, revision_id=None):
1270
1336
        """Copy the content of self into destination.
1271
1337
 
1272
1338
        revision_id: if not None, the revision history in the new branch will
1273
1339
                     be truncated to end with revision_id.
1274
1340
        """
1275
 
        self.update_references(destination)
1276
 
        self._synchronize_history(destination, revision_id)
1277
 
        try:
1278
 
            parent = self.get_parent()
1279
 
        except errors.InaccessibleParent, e:
1280
 
            mutter('parent was not accessible to copy: %s', e)
1281
 
        else:
1282
 
            if parent:
1283
 
                destination.set_parent(parent)
1284
 
        if self._push_should_merge_tags():
1285
 
            self.tags.merge_to(destination.tags)
 
1341
        return InterBranch.get(self, destination).copy_content_into(
 
1342
            revision_id=revision_id)
1286
1343
 
1287
1344
    def update_references(self, target):
1288
1345
        if not getattr(self._format, 'supports_reference_locations', False):
1333
1390
        """Return the most suitable metadir for a checkout of this branch.
1334
1391
        Weaves are used if this branch's repository uses weaves.
1335
1392
        """
1336
 
        if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
1337
 
            from bzrlib.repofmt import weaverepo
1338
 
            format = bzrdir.BzrDirMetaFormat1()
1339
 
            format.repository_format = weaverepo.RepositoryFormat7()
1340
 
        else:
1341
 
            format = self.repository.bzrdir.checkout_metadir()
1342
 
            format.set_branch_format(self._format)
 
1393
        format = self.repository.bzrdir.checkout_metadir()
 
1394
        format.set_branch_format(self._format)
1343
1395
        return format
1344
1396
 
1345
1397
    def create_clone_on_transport(self, to_transport, revision_id=None,
1346
 
        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):
1347
1400
        """Create a clone of this branch and its bzrdir.
1348
1401
 
1349
1402
        :param to_transport: The transport to clone onto.
1362
1415
            revision_id = self.last_revision()
1363
1416
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1364
1417
            revision_id=revision_id, stacked_on=stacked_on,
1365
 
            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)
1366
1420
        return dir_to.open_branch()
1367
1421
 
1368
1422
    def create_checkout(self, to_location, revision_id=None,
1483
1537
        else:
1484
1538
            raise AssertionError("invalid heads: %r" % (heads,))
1485
1539
 
1486
 
 
1487
 
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):
1488
1562
    """An encapsulation of the initialization and open routines for a format.
1489
1563
 
1490
1564
    Formats provide three things:
1493
1567
     * an open routine.
1494
1568
 
1495
1569
    Formats are placed in an dict by their format string for reference
1496
 
    during branch opening. Its not required that these be instances, they
 
1570
    during branch opening. It's not required that these be instances, they
1497
1571
    can be classes themselves with class methods - it simply depends on
1498
1572
    whether state is needed for a given format or not.
1499
1573
 
1502
1576
    object will be created every time regardless.
1503
1577
    """
1504
1578
 
1505
 
    _default_format = None
1506
 
    """The default format used for new branches."""
1507
 
 
1508
 
    _formats = {}
1509
 
    """The known formats."""
1510
 
 
1511
1579
    can_set_append_revisions_only = True
1512
1580
 
1513
1581
    def __eq__(self, other):
1522
1590
        try:
1523
1591
            transport = a_bzrdir.get_branch_transport(None, name=name)
1524
1592
            format_string = transport.get_bytes("format")
1525
 
            return klass._formats[format_string]
 
1593
            return format_registry.get(format_string)
1526
1594
        except errors.NoSuchFile:
1527
1595
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1528
1596
        except KeyError:
1529
1597
            raise errors.UnknownFormatError(format=format_string, kind='branch')
1530
1598
 
1531
1599
    @classmethod
 
1600
    @deprecated_method(deprecated_in((2, 4, 0)))
1532
1601
    def get_default_format(klass):
1533
1602
        """Return the current default format."""
1534
 
        return klass._default_format
 
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()
1535
1614
 
1536
1615
    def get_reference(self, a_bzrdir, name=None):
1537
1616
        """Get the target reference of the branch in a_bzrdir.
1577
1656
            hook(params)
1578
1657
 
1579
1658
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
1580
 
                           lock_type='metadir', set_format=True):
 
1659
                           repository=None):
1581
1660
        """Initialize a branch in a bzrdir, with specified files
1582
1661
 
1583
1662
        :param a_bzrdir: The bzrdir to initialize the branch in
1584
1663
        :param utf8_files: The files to create as a list of
1585
1664
            (filename, content) tuples
1586
1665
        :param name: Name of colocated branch to create, if any
1587
 
        :param set_format: If True, set the format with
1588
 
            self.get_format_string.  (BzrBranch4 has its format set
1589
 
            elsewhere)
1590
1666
        :return: a branch in this format
1591
1667
        """
1592
1668
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
1593
1669
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
1594
 
        lock_map = {
1595
 
            'metadir': ('lock', lockdir.LockDir),
1596
 
            'branch4': ('branch-lock', lockable_files.TransportLock),
1597
 
        }
1598
 
        lock_name, lock_class = lock_map[lock_type]
1599
1670
        control_files = lockable_files.LockableFiles(branch_transport,
1600
 
            lock_name, lock_class)
 
1671
            'lock', lockdir.LockDir)
1601
1672
        control_files.create_lock()
 
1673
        control_files.lock_write()
1602
1674
        try:
1603
 
            control_files.lock_write()
1604
 
        except errors.LockContention:
1605
 
            if lock_type != 'branch4':
1606
 
                raise
1607
 
            lock_taken = False
1608
 
        else:
1609
 
            lock_taken = True
1610
 
        if set_format:
1611
1675
            utf8_files += [('format', self.get_format_string())]
1612
 
        try:
1613
1676
            for (filename, content) in utf8_files:
1614
1677
                branch_transport.put_bytes(
1615
1678
                    filename, content,
1616
1679
                    mode=a_bzrdir._get_file_mode())
1617
1680
        finally:
1618
 
            if lock_taken:
1619
 
                control_files.unlock()
1620
 
        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)
1621
1684
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
1622
1685
        return branch
1623
1686
 
1624
 
    def initialize(self, a_bzrdir, name=None):
 
1687
    def initialize(self, a_bzrdir, name=None, repository=None):
1625
1688
        """Create a branch of this format in a_bzrdir.
1626
1689
        
1627
1690
        :param name: Name of the colocated branch to create.
1661
1724
        """
1662
1725
        raise NotImplementedError(self.network_name)
1663
1726
 
1664
 
    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):
1665
1729
        """Return the branch object for a_bzrdir
1666
1730
 
1667
1731
        :param a_bzrdir: A BzrDir that contains a branch.
1674
1738
        raise NotImplementedError(self.open)
1675
1739
 
1676
1740
    @classmethod
 
1741
    @deprecated_method(deprecated_in((2, 4, 0)))
1677
1742
    def register_format(klass, format):
1678
 
        """Register a metadir format."""
1679
 
        klass._formats[format.get_format_string()] = format
1680
 
        # Metadir formats have a network name of their format string, and get
1681
 
        # registered as class factories.
1682
 
        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)
1683
1749
 
1684
1750
    @classmethod
 
1751
    @deprecated_method(deprecated_in((2, 4, 0)))
1685
1752
    def set_default_format(klass, format):
1686
 
        klass._default_format = format
 
1753
        format_registry.set_default(format)
1687
1754
 
1688
1755
    def supports_set_append_revisions_only(self):
1689
1756
        """True if this format supports set_append_revisions_only."""
1693
1760
        """True if this format records a stacked-on branch."""
1694
1761
        return False
1695
1762
 
 
1763
    def supports_leaving_lock(self):
 
1764
        """True if this format supports leaving locks in place."""
 
1765
        return False # by default
 
1766
 
1696
1767
    @classmethod
 
1768
    @deprecated_method(deprecated_in((2, 4, 0)))
1697
1769
    def unregister_format(klass, format):
1698
 
        del klass._formats[format.get_format_string()]
 
1770
        format_registry.remove(format)
1699
1771
 
1700
1772
    def __str__(self):
1701
1773
        return self.get_format_description().rstrip()
1705
1777
        return False  # by default
1706
1778
 
1707
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
 
1708
1808
class BranchHooks(Hooks):
1709
1809
    """A dictionary mapping hook name to a list of callables for branch hooks.
1710
1810
 
1737
1837
            "with a bzrlib.branch.PullResult object and only runs in the "
1738
1838
            "bzr client.", (0, 15), None))
1739
1839
        self.create_hook(HookPoint('pre_commit',
1740
 
            "Called after a commit is calculated but before it is is "
 
1840
            "Called after a commit is calculated but before it is "
1741
1841
            "completed. pre_commit is called with (local, master, old_revno, "
1742
1842
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
1743
1843
            "). old_revid is NULL_REVISION for the first commit to a branch, "
1780
1880
            "all are called with the url returned from the previous hook."
1781
1881
            "The order is however undefined.", (1, 9), None))
1782
1882
        self.create_hook(HookPoint('automatic_tag_name',
1783
 
            "Called to determine an automatic tag name for a revision."
 
1883
            "Called to determine an automatic tag name for a revision. "
1784
1884
            "automatic_tag_name is called with (branch, revision_id) and "
1785
1885
            "should return a tag name or None if no tag name could be "
1786
1886
            "determined. The first non-None tag name returned will be used.",
1877
1977
        return self.__dict__ == other.__dict__
1878
1978
 
1879
1979
    def __repr__(self):
1880
 
        if self.branch:
1881
 
            return "<%s of %s>" % (self.__class__.__name__, self.branch)
1882
 
        else:
1883
 
            return "<%s of format:%s bzrdir:%s>" % (
1884
 
                self.__class__.__name__, self.branch,
1885
 
                self.format, self.bzrdir)
 
1980
        return "<%s of %s>" % (self.__class__.__name__, self.branch)
1886
1981
 
1887
1982
 
1888
1983
class SwitchHookParams(object):
1918
2013
            self.revision_id)
1919
2014
 
1920
2015
 
1921
 
class BzrBranchFormat4(BranchFormat):
1922
 
    """Bzr branch format 4.
1923
 
 
1924
 
    This format has:
1925
 
     - a revision-history file.
1926
 
     - a branch-lock lock file [ to be shared with the bzrdir ]
1927
 
    """
1928
 
 
1929
 
    def get_format_description(self):
1930
 
        """See BranchFormat.get_format_description()."""
1931
 
        return "Branch format 4"
1932
 
 
1933
 
    def initialize(self, a_bzrdir, name=None):
1934
 
        """Create a branch of this format in a_bzrdir."""
1935
 
        utf8_files = [('revision-history', ''),
1936
 
                      ('branch-name', ''),
1937
 
                      ]
1938
 
        return self._initialize_helper(a_bzrdir, utf8_files, name=name,
1939
 
                                       lock_type='branch4', set_format=False)
1940
 
 
1941
 
    def __init__(self):
1942
 
        super(BzrBranchFormat4, self).__init__()
1943
 
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
1944
 
 
1945
 
    def network_name(self):
1946
 
        """The network name for this format is the control dirs disk label."""
1947
 
        return self._matchingbzrdir.get_format_string()
1948
 
 
1949
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
1950
 
        """See BranchFormat.open()."""
1951
 
        if not _found:
1952
 
            # we are being called directly and must probe.
1953
 
            raise NotImplementedError
1954
 
        return BzrBranch(_format=self,
1955
 
                         _control_files=a_bzrdir._control_files,
1956
 
                         a_bzrdir=a_bzrdir,
1957
 
                         name=name,
1958
 
                         _repository=a_bzrdir.open_repository())
1959
 
 
1960
 
    def __str__(self):
1961
 
        return "Bazaar-NG branch format 4"
1962
 
 
1963
 
 
1964
2016
class BranchFormatMetadir(BranchFormat):
1965
2017
    """Common logic for meta-dir based branch formats."""
1966
2018
 
1975
2027
        """
1976
2028
        return self.get_format_string()
1977
2029
 
1978
 
    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):
1979
2032
        """See BranchFormat.open()."""
1980
2033
        if not _found:
1981
2034
            format = BranchFormat.find_format(a_bzrdir, name=name)
1986
2039
        try:
1987
2040
            control_files = lockable_files.LockableFiles(transport, 'lock',
1988
2041
                                                         lockdir.LockDir)
 
2042
            if found_repository is None:
 
2043
                found_repository = a_bzrdir.find_repository()
1989
2044
            return self._branch_class()(_format=self,
1990
2045
                              _control_files=control_files,
1991
2046
                              name=name,
1992
2047
                              a_bzrdir=a_bzrdir,
1993
 
                              _repository=a_bzrdir.find_repository(),
 
2048
                              _repository=found_repository,
1994
2049
                              ignore_fallbacks=ignore_fallbacks)
1995
2050
        except errors.NoSuchFile:
1996
2051
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
2003
2058
    def supports_tags(self):
2004
2059
        return True
2005
2060
 
 
2061
    def supports_leaving_lock(self):
 
2062
        return True
 
2063
 
2006
2064
 
2007
2065
class BzrBranchFormat5(BranchFormatMetadir):
2008
2066
    """Bzr branch format 5.
2028
2086
        """See BranchFormat.get_format_description()."""
2029
2087
        return "Branch format 5"
2030
2088
 
2031
 
    def initialize(self, a_bzrdir, name=None):
 
2089
    def initialize(self, a_bzrdir, name=None, repository=None):
2032
2090
        """Create a branch of this format in a_bzrdir."""
2033
2091
        utf8_files = [('revision-history', ''),
2034
2092
                      ('branch-name', ''),
2035
2093
                      ]
2036
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2094
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2037
2095
 
2038
2096
    def supports_tags(self):
2039
2097
        return False
2061
2119
        """See BranchFormat.get_format_description()."""
2062
2120
        return "Branch format 6"
2063
2121
 
2064
 
    def initialize(self, a_bzrdir, name=None):
 
2122
    def initialize(self, a_bzrdir, name=None, repository=None):
2065
2123
        """Create a branch of this format in a_bzrdir."""
2066
2124
        utf8_files = [('last-revision', '0 null:\n'),
2067
2125
                      ('branch.conf', ''),
2068
2126
                      ('tags', ''),
2069
2127
                      ]
2070
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2128
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2071
2129
 
2072
2130
    def make_tags(self, branch):
2073
2131
        """See bzrlib.branch.BranchFormat.make_tags()."""
2091
2149
        """See BranchFormat.get_format_description()."""
2092
2150
        return "Branch format 8"
2093
2151
 
2094
 
    def initialize(self, a_bzrdir, name=None):
 
2152
    def initialize(self, a_bzrdir, name=None, repository=None):
2095
2153
        """Create a branch of this format in a_bzrdir."""
2096
2154
        utf8_files = [('last-revision', '0 null:\n'),
2097
2155
                      ('branch.conf', ''),
2098
2156
                      ('tags', ''),
2099
2157
                      ('references', '')
2100
2158
                      ]
2101
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2159
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2102
2160
 
2103
2161
    def __init__(self):
2104
2162
        super(BzrBranchFormat8, self).__init__()
2127
2185
    This format was introduced in bzr 1.6.
2128
2186
    """
2129
2187
 
2130
 
    def initialize(self, a_bzrdir, name=None):
 
2188
    def initialize(self, a_bzrdir, name=None, repository=None):
2131
2189
        """Create a branch of this format in a_bzrdir."""
2132
2190
        utf8_files = [('last-revision', '0 null:\n'),
2133
2191
                      ('branch.conf', ''),
2134
2192
                      ('tags', ''),
2135
2193
                      ]
2136
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2194
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2137
2195
 
2138
2196
    def _branch_class(self):
2139
2197
        return BzrBranch7
2181
2239
        transport = a_bzrdir.get_branch_transport(None, name=name)
2182
2240
        location = transport.put_bytes('location', to_branch.base)
2183
2241
 
2184
 
    def initialize(self, a_bzrdir, name=None, target_branch=None):
 
2242
    def initialize(self, a_bzrdir, name=None, target_branch=None,
 
2243
            repository=None):
2185
2244
        """Create a branch of this format in a_bzrdir."""
2186
2245
        if target_branch is None:
2187
2246
            # this format does not implement branch itself, thus the implicit
2215
2274
        return clone
2216
2275
 
2217
2276
    def open(self, a_bzrdir, name=None, _found=False, location=None,
2218
 
             possible_transports=None, ignore_fallbacks=False):
 
2277
             possible_transports=None, ignore_fallbacks=False,
 
2278
             found_repository=None):
2219
2279
        """Return the branch that the branch reference in a_bzrdir points at.
2220
2280
 
2221
2281
        :param a_bzrdir: A BzrDir that contains a branch.
2252
2312
        return result
2253
2313
 
2254
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
 
2255
2329
network_format_registry = registry.FormatRegistry()
2256
2330
"""Registry of formats indexed by their network name.
2257
2331
 
2260
2334
BranchFormat.network_name() for more detail.
2261
2335
"""
2262
2336
 
 
2337
format_registry = BranchFormatRegistry(network_format_registry)
 
2338
 
2263
2339
 
2264
2340
# formats which have no format string are not discoverable
2265
2341
# and not independently creatable, so are not registered.
2267
2343
__format6 = BzrBranchFormat6()
2268
2344
__format7 = BzrBranchFormat7()
2269
2345
__format8 = BzrBranchFormat8()
2270
 
BranchFormat.register_format(__format5)
2271
 
BranchFormat.register_format(BranchReferenceFormat())
2272
 
BranchFormat.register_format(__format6)
2273
 
BranchFormat.register_format(__format7)
2274
 
BranchFormat.register_format(__format8)
2275
 
BranchFormat.set_default_format(__format7)
2276
 
_legacy_formats = [BzrBranchFormat4(),
2277
 
    ]
2278
 
network_format_registry.register(
2279
 
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
 
2346
format_registry.register(__format5)
 
2347
format_registry.register(BranchReferenceFormat())
 
2348
format_registry.register(__format6)
 
2349
format_registry.register(__format7)
 
2350
format_registry.register(__format8)
 
2351
format_registry.set_default(__format7)
2280
2352
 
2281
2353
 
2282
2354
class BranchWriteLockResult(LogicalLockResult):
2558
2630
        result.target_branch = target
2559
2631
        result.old_revno, result.old_revid = target.last_revision_info()
2560
2632
        self.update_references(target)
2561
 
        if result.old_revid != self.last_revision():
 
2633
        if result.old_revid != stop_revision:
2562
2634
            # We assume that during 'push' this repository is closer than
2563
2635
            # the target.
2564
2636
            graph = self.repository.get_graph(target.repository)
2965
3037
        try:
2966
3038
            index = self._partial_revision_history_cache.index(revision_id)
2967
3039
        except ValueError:
2968
 
            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)
2969
3044
            index = len(self._partial_revision_history_cache) - 1
2970
3045
            if self._partial_revision_history_cache[index] != revision_id:
2971
3046
                raise errors.NoSuchRevision(self, revision_id)
3026
3101
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
3027
3102
    """
3028
3103
 
 
3104
    @deprecated_method(deprecated_in((2, 3, 0)))
3029
3105
    def __int__(self):
3030
 
        # 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
        """
3031
3110
        return self.new_revno - self.old_revno
3032
3111
 
3033
3112
    def report(self, to_file):
3058
3137
        target, otherwise it will be None.
3059
3138
    """
3060
3139
 
 
3140
    @deprecated_method(deprecated_in((2, 3, 0)))
3061
3141
    def __int__(self):
3062
 
        # 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
        """
3063
3146
        return self.new_revno - self.old_revno
3064
3147
 
3065
3148
    def report(self, to_file):
3188
3271
    _optimisers = []
3189
3272
    """The available optimised InterBranch types."""
3190
3273
 
3191
 
    @staticmethod
3192
 
    def _get_branch_formats_to_test():
3193
 
        """Return a tuple with the Branch formats to use when testing."""
3194
 
        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)
3195
3283
 
 
3284
    @needs_write_lock
3196
3285
    def pull(self, overwrite=False, stop_revision=None,
3197
3286
             possible_transports=None, local=False):
3198
3287
        """Mirror source into target branch.
3203
3292
        """
3204
3293
        raise NotImplementedError(self.pull)
3205
3294
 
 
3295
    @needs_write_lock
3206
3296
    def update_revisions(self, stop_revision=None, overwrite=False,
3207
 
                         graph=None):
 
3297
                         graph=None, fetch_tags=True):
3208
3298
        """Pull in new perfect-fit revisions.
3209
3299
 
3210
3300
        :param stop_revision: Updated until the given revision
3212
3302
            to see if it is a proper descendant.
3213
3303
        :param graph: A Graph object that can be used to query history
3214
3304
            information. This can be None.
 
3305
        :param fetch_tags: Flag that specifies if tags from source should be
 
3306
            fetched too.
3215
3307
        :return: None
3216
3308
        """
3217
3309
        raise NotImplementedError(self.update_revisions)
3218
3310
 
 
3311
    @needs_write_lock
3219
3312
    def push(self, overwrite=False, stop_revision=None,
3220
3313
             _override_hook_source_branch=None):
3221
3314
        """Mirror the source branch into the target branch.
3224
3317
        """
3225
3318
        raise NotImplementedError(self.push)
3226
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
 
3227
3329
 
3228
3330
class GenericInterBranch(InterBranch):
3229
 
    """InterBranch implementation that uses public Branch functions.
3230
 
    """
3231
 
 
3232
 
    @staticmethod
3233
 
    def _get_branch_formats_to_test():
3234
 
        return BranchFormat._default_format, BranchFormat._default_format
3235
 
 
 
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
3236
3369
    def update_revisions(self, stop_revision=None, overwrite=False,
3237
 
        graph=None):
 
3370
        graph=None, fetch_tags=True):
3238
3371
        """See InterBranch.update_revisions()."""
3239
 
        self.source.lock_read()
3240
 
        try:
3241
 
            other_revno, other_last_revision = self.source.last_revision_info()
3242
 
            stop_revno = None # unknown
3243
 
            if stop_revision is None:
3244
 
                stop_revision = other_last_revision
3245
 
                if _mod_revision.is_null(stop_revision):
3246
 
                    # if there are no commits, we're done.
3247
 
                    return
3248
 
                stop_revno = other_revno
3249
 
 
3250
 
            # what's the current last revision, before we fetch [and change it
3251
 
            # possibly]
3252
 
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
3253
 
            # we fetch here so that we don't process data twice in the common
3254
 
            # case of having something to pull, and so that the check for
3255
 
            # already merged can operate on the just fetched graph, which will
3256
 
            # be cached in memory.
3257
 
            self.target.fetch(self.source, stop_revision)
3258
 
            # Check to see if one is an ancestor of the other
3259
 
            if not overwrite:
3260
 
                if graph is None:
3261
 
                    graph = self.target.repository.get_graph()
3262
 
                if self.target._check_if_descendant_or_diverged(
3263
 
                        stop_revision, last_rev, graph, self.source):
3264
 
                    # stop_revision is a descendant of last_rev, but we aren't
3265
 
                    # overwriting, so we're done.
3266
 
                    return
3267
 
            if stop_revno is None:
3268
 
                if graph is None:
3269
 
                    graph = self.target.repository.get_graph()
3270
 
                this_revno, this_last_revision = \
3271
 
                        self.target.last_revision_info()
3272
 
                stop_revno = graph.find_distance_to_null(stop_revision,
3273
 
                                [(other_last_revision, other_revno),
3274
 
                                 (this_last_revision, this_revno)])
3275
 
            self.target.set_last_revision_info(stop_revno, stop_revision)
3276
 
        finally:
3277
 
            self.source.unlock()
3278
 
 
 
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
3279
3420
    def pull(self, overwrite=False, stop_revision=None,
3280
 
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3421
             possible_transports=None, run_hooks=True,
3281
3422
             _override_hook_target=None, local=False):
3282
 
        """See Branch.pull.
 
3423
        """Pull from source into self, updating my master if any.
3283
3424
 
3284
 
        :param _hook_master: Private parameter - set the branch to
3285
 
            be supplied as the master to pull hooks.
3286
3425
        :param run_hooks: Private parameter - if false, this branch
3287
3426
            is being called because it's the master of the primary branch,
3288
3427
            so it should not run its hooks.
3289
 
        :param _override_hook_target: Private parameter - set the branch to be
3290
 
            supplied as the target_branch to pull hooks.
3291
 
        :param local: Only update the local branch, and not the bound branch.
3292
3428
        """
3293
 
        # This type of branch can't be bound.
3294
 
        if local:
 
3429
        bound_location = self.target.get_bound_location()
 
3430
        if local and not bound_location:
3295
3431
            raise errors.LocalRequiresBoundBranch()
3296
 
        result = PullResult()
3297
 
        result.source_branch = self.source
3298
 
        if _override_hook_target is None:
3299
 
            result.target_branch = self.target
3300
 
        else:
3301
 
            result.target_branch = _override_hook_target
3302
 
        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()
3303
3438
        try:
3304
 
            # We assume that during 'pull' the target repository is closer than
3305
 
            # the source one.
3306
 
            self.source.update_references(self.target)
3307
 
            graph = self.target.repository.get_graph(self.source.repository)
3308
 
            # TODO: Branch formats should have a flag that indicates 
3309
 
            # that revno's are expensive, and pull() should honor that flag.
3310
 
            # -- JRV20090506
3311
 
            result.old_revno, result.old_revid = \
3312
 
                self.target.last_revision_info()
3313
 
            self.target.update_revisions(self.source, stop_revision,
3314
 
                overwrite=overwrite, graph=graph)
3315
 
            # TODO: The old revid should be specified when merging tags, 
3316
 
            # so a tags implementation that versions tags can only 
3317
 
            # pull in the most recent changes. -- JRV20090506
3318
 
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3319
 
                overwrite)
3320
 
            result.new_revno, result.new_revid = self.target.last_revision_info()
3321
 
            if _hook_master:
3322
 
                result.master_branch = _hook_master
3323
 
                result.local_branch = result.target_branch
3324
 
            else:
3325
 
                result.master_branch = result.target_branch
3326
 
                result.local_branch = None
3327
 
            if run_hooks:
3328
 
                for hook in Branch.hooks['post_pull']:
3329
 
                    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)
3330
3448
        finally:
3331
 
            self.source.unlock()
3332
 
        return result
 
3449
            if master_branch:
 
3450
                master_branch.unlock()
3333
3451
 
3334
3452
    def push(self, overwrite=False, stop_revision=None,
3335
3453
             _override_hook_source_branch=None):
3375
3493
                # push into the master from the source branch.
3376
3494
                self.source._basic_push(master_branch, overwrite, stop_revision)
3377
3495
                # and push into the target branch from the source. Note that we
3378
 
                # push from the source branch again, because its considered the
 
3496
                # push from the source branch again, because it's considered the
3379
3497
                # highest bandwidth repository.
3380
3498
                result = self.source._basic_push(self.target, overwrite,
3381
3499
                    stop_revision)
3397
3515
            _run_hooks()
3398
3516
            return result
3399
3517
 
3400
 
    @classmethod
3401
 
    def is_compatible(self, source, target):
3402
 
        # GenericBranch uses the public API, so always compatible
3403
 
        return True
3404
 
 
3405
 
 
3406
 
class InterToBranch5(GenericInterBranch):
3407
 
 
3408
 
    @staticmethod
3409
 
    def _get_branch_formats_to_test():
3410
 
        return BranchFormat._default_format, BzrBranchFormat5()
3411
 
 
3412
 
    def pull(self, overwrite=False, stop_revision=None,
3413
 
             possible_transports=None, run_hooks=True,
3414
 
             _override_hook_target=None, local=False):
3415
 
        """Pull from source into self, updating my master if any.
3416
 
 
 
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.
3417
3529
        :param run_hooks: Private parameter - if false, this branch
3418
3530
            is being called because it's the master of the primary branch,
3419
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.
3420
3537
        """
3421
 
        bound_location = self.target.get_bound_location()
3422
 
        if local and not bound_location:
 
3538
        # This type of branch can't be bound.
 
3539
        if local:
3423
3540
            raise errors.LocalRequiresBoundBranch()
3424
 
        master_branch = None
3425
 
        if not local and bound_location and self.source.user_url != bound_location:
3426
 
            # not pulling from master, so we need to update master.
3427
 
            master_branch = self.target.get_master_branch(possible_transports)
3428
 
            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()
3429
3548
        try:
3430
 
            if master_branch:
3431
 
                # pull from source into master.
3432
 
                master_branch.pull(self.source, overwrite, stop_revision,
3433
 
                    run_hooks=False)
3434
 
            return super(InterToBranch5, self).pull(overwrite,
3435
 
                stop_revision, _hook_master=master_branch,
3436
 
                run_hooks=run_hooks,
3437
 
                _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)
3438
3575
        finally:
3439
 
            if master_branch:
3440
 
                master_branch.unlock()
 
3576
            self.source.unlock()
 
3577
        return result
3441
3578
 
3442
3579
 
3443
3580
InterBranch.register_optimiser(GenericInterBranch)
3444
 
InterBranch.register_optimiser(InterToBranch5)