/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: Robert Collins
  • Date: 2010-05-06 11:08:10 UTC
  • mto: This revision was merged to the branch mainline in revision 5223.
  • Revision ID: robertc@robertcollins.net-20100506110810-h3j07fh5gmw54s25
Cleaner matcher matching revised unlocking protocol.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005-2010 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,
32
30
        lockdir,
33
31
        lockable_files,
34
 
        remote,
35
32
        repository,
36
33
        revision as _mod_revision,
37
34
        rio,
 
35
        symbol_versioning,
38
36
        transport,
 
37
        tsort,
39
38
        ui,
40
39
        urlutils,
41
40
        )
42
41
from bzrlib.config import BranchConfig, TransportConfig
 
42
from bzrlib.repofmt.pack_repo import RepositoryFormatKnitPack5RichRoot
43
43
from bzrlib.tag import (
44
44
    BasicTags,
45
45
    DisabledTags,
46
46
    )
47
47
""")
48
48
 
49
 
from bzrlib import (
50
 
    controldir,
51
 
    )
52
 
from bzrlib.decorators import (
53
 
    needs_read_lock,
54
 
    needs_write_lock,
55
 
    only_raises,
56
 
    )
57
 
from bzrlib.hooks import Hooks
 
49
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
 
50
from bzrlib.hooks import HookPoint, Hooks
58
51
from bzrlib.inter import InterObject
59
 
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
 
52
from bzrlib.lock import _RelockDebugMixin
60
53
from bzrlib import registry
61
54
from bzrlib.symbol_versioning import (
62
55
    deprecated_in,
70
63
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
71
64
 
72
65
 
73
 
class Branch(controldir.ControlComponent):
 
66
class Branch(bzrdir.ControlComponent):
74
67
    """Branch holding a history of revisions.
75
68
 
76
69
    :ivar base:
77
70
        Base directory/url of the branch; using control_url and
78
71
        control_transport is more standardized.
79
 
    :ivar hooks: An instance of BranchHooks.
80
 
    :ivar _master_branch_cache: cached result of get_master_branch, see
81
 
        _clear_cached_state.
 
72
 
 
73
    hooks: An instance of BranchHooks.
82
74
    """
83
75
    # this is really an instance variable - FIXME move it there
84
76
    # - RBC 20060112
98
90
        self._revision_id_to_revno_cache = None
99
91
        self._partial_revision_id_to_revno_cache = {}
100
92
        self._partial_revision_history_cache = []
101
 
        self._tags_bytes = None
102
93
        self._last_revision_info_cache = None
103
 
        self._master_branch_cache = None
104
94
        self._merge_sorted_revisions_cache = None
105
95
        self._open_hook()
106
96
        hooks = Branch.hooks['open']
112
102
 
113
103
    def _activate_fallback_location(self, url):
114
104
        """Activate the branch/repository from url as a fallback repository."""
115
 
        for existing_fallback_repo in self.repository._fallback_repositories:
116
 
            if existing_fallback_repo.user_url == url:
117
 
                # This fallback is already configured.  This probably only
118
 
                # happens because BzrDir.sprout is a horrible mess.  To avoid
119
 
                # confusing _unstack we don't add this a second time.
120
 
                mutter('duplicate activation of fallback %r on %r', url, self)
121
 
                return
122
105
        repo = self._get_fallback_repository(url)
123
106
        if repo.has_same_location(self.repository):
124
107
            raise errors.UnstackableLocationError(self.user_url, url)
214
197
        return self.supports_tags() and self.tags.get_tag_dict()
215
198
 
216
199
    def get_config(self):
217
 
        """Get a bzrlib.config.BranchConfig for this Branch.
218
 
 
219
 
        This can then be used to get and set configuration options for the
220
 
        branch.
221
 
 
222
 
        :return: A bzrlib.config.BranchConfig.
223
 
        """
224
200
        return BranchConfig(self)
225
201
 
226
202
    def _get_config(self):
242
218
            possible_transports=[self.bzrdir.root_transport])
243
219
        return a_branch.repository
244
220
 
245
 
    @needs_read_lock
246
221
    def _get_tags_bytes(self):
247
222
        """Get the bytes of a serialised tags dict.
248
223
 
255
230
        :return: The bytes of the tags file.
256
231
        :seealso: Branch._set_tags_bytes.
257
232
        """
258
 
        if self._tags_bytes is None:
259
 
            self._tags_bytes = self._transport.get_bytes('tags')
260
 
        return self._tags_bytes
 
233
        return self._transport.get_bytes('tags')
261
234
 
262
235
    def _get_nick(self, local=False, possible_transports=None):
263
236
        config = self.get_config()
265
238
        if not local and not config.has_explicit_nickname():
266
239
            try:
267
240
                master = self.get_master_branch(possible_transports)
268
 
                if master and self.user_url == master.user_url:
269
 
                    raise errors.RecursiveBind(self.user_url)
270
241
                if master is not None:
271
242
                    # return the master branch value
272
243
                    return master.nick
273
 
            except errors.RecursiveBind, e:
274
 
                raise e
275
244
            except errors.BzrError, e:
276
245
                # Silently fall back to local implicit nick if the master is
277
246
                # unavailable
314
283
        new_history.reverse()
315
284
        return new_history
316
285
 
317
 
    def lock_write(self, token=None):
318
 
        """Lock the branch for write operations.
319
 
 
320
 
        :param token: A token to permit reacquiring a previously held and
321
 
            preserved lock.
322
 
        :return: A BranchWriteLockResult.
323
 
        """
 
286
    def lock_write(self):
324
287
        raise NotImplementedError(self.lock_write)
325
288
 
326
289
    def lock_read(self):
327
 
        """Lock the branch for read operations.
328
 
 
329
 
        :return: A bzrlib.lock.LogicalLockResult.
330
 
        """
331
290
        raise NotImplementedError(self.lock_read)
332
291
 
333
292
    def unlock(self):
667
626
        raise errors.UnsupportedOperation(self.get_reference_info, self)
668
627
 
669
628
    @needs_write_lock
670
 
    def fetch(self, from_branch, last_revision=None):
 
629
    def fetch(self, from_branch, last_revision=None, pb=None):
671
630
        """Copy revisions from from_branch into this branch.
672
631
 
673
632
        :param from_branch: Where to copy from.
674
633
        :param last_revision: What revision to stop at (None for at the end
675
634
                              of the branch.
 
635
        :param pb: An optional progress bar to use.
676
636
        :return: None
677
637
        """
678
 
        return InterBranch.get(from_branch, self).fetch(last_revision)
 
638
        if self.base == from_branch.base:
 
639
            return (0, [])
 
640
        if pb is not None:
 
641
            symbol_versioning.warn(
 
642
                symbol_versioning.deprecated_in((1, 14, 0))
 
643
                % "pb parameter to fetch()")
 
644
        from_branch.lock_read()
 
645
        try:
 
646
            if last_revision is None:
 
647
                last_revision = from_branch.last_revision()
 
648
                last_revision = _mod_revision.ensure_null(last_revision)
 
649
            return self.repository.fetch(from_branch.repository,
 
650
                                         revision_id=last_revision,
 
651
                                         pb=pb)
 
652
        finally:
 
653
            from_branch.unlock()
679
654
 
680
655
    def get_bound_location(self):
681
656
        """Return the URL of the branch we are bound to.
692
667
 
693
668
    def get_commit_builder(self, parents, config=None, timestamp=None,
694
669
                           timezone=None, committer=None, revprops=None,
695
 
                           revision_id=None, lossy=False):
 
670
                           revision_id=None):
696
671
        """Obtain a CommitBuilder for this branch.
697
672
 
698
673
        :param parents: Revision ids of the parents of the new revision.
702
677
        :param committer: Optional committer to set for commit.
703
678
        :param revprops: Optional dictionary of revision properties.
704
679
        :param revision_id: Optional revision id.
705
 
        :param lossy: Whether to discard data that can not be natively
706
 
            represented, when pushing to a foreign VCS 
707
680
        """
708
681
 
709
682
        if config is None:
710
683
            config = self.get_config()
711
684
 
712
685
        return self.repository.get_commit_builder(self, parents, config,
713
 
            timestamp, timezone, committer, revprops, revision_id,
714
 
            lossy)
 
686
            timestamp, timezone, committer, revprops, revision_id)
715
687
 
716
688
    def get_master_branch(self, possible_transports=None):
717
689
        """Return the branch we are bound to.
744
716
        """Print `file` to stdout."""
745
717
        raise NotImplementedError(self.print_file)
746
718
 
747
 
    @deprecated_method(deprecated_in((2, 4, 0)))
748
719
    def set_revision_history(self, rev_history):
749
 
        """See Branch.set_revision_history."""
750
 
        self._set_revision_history(rev_history)
751
 
 
752
 
    @needs_write_lock
753
 
    def _set_revision_history(self, rev_history):
754
 
        if len(rev_history) == 0:
755
 
            revid = _mod_revision.NULL_REVISION
756
 
        else:
757
 
            revid = rev_history[-1]
758
 
        if rev_history != self._lefthand_history(revid):
759
 
            raise errors.NotLefthandHistory(rev_history)
760
 
        self.set_last_revision_info(len(rev_history), revid)
761
 
        self._cache_revision_history(rev_history)
762
 
        for hook in Branch.hooks['set_rh']:
763
 
            hook(self, rev_history)
764
 
 
765
 
    @needs_write_lock
766
 
    def set_last_revision_info(self, revno, revision_id):
767
 
        """Set the last revision of this branch.
768
 
 
769
 
        The caller is responsible for checking that the revno is correct
770
 
        for this revision id.
771
 
 
772
 
        It may be possible to set the branch last revision to an id not
773
 
        present in the repository.  However, branches can also be
774
 
        configured to check constraints on history, in which case this may not
775
 
        be permitted.
776
 
        """
777
 
        raise NotImplementedError(self.last_revision_info)
778
 
 
779
 
    @needs_write_lock
780
 
    def generate_revision_history(self, revision_id, last_rev=None,
781
 
                                  other_branch=None):
782
 
        """See Branch.generate_revision_history"""
783
 
        graph = self.repository.get_graph()
784
 
        known_revision_ids = [
785
 
            self.last_revision_info(),
786
 
            (_mod_revision.NULL_REVISION, 0),
787
 
            ]
788
 
        if last_rev is not None:
789
 
            if not graph.is_ancestor(last_rev, revision_id):
790
 
                # our previous tip is not merged into stop_revision
791
 
                raise errors.DivergedBranches(self, other_branch)
792
 
        revno = graph.find_distance_to_null(revision_id, known_revision_ids)
793
 
        self.set_last_revision_info(revno, revision_id)
 
720
        raise NotImplementedError(self.set_revision_history)
794
721
 
795
722
    @needs_write_lock
796
723
    def set_parent(self, url):
840
767
 
841
768
    def _unstack(self):
842
769
        """Change a branch to be unstacked, copying data as needed.
843
 
 
 
770
        
844
771
        Don't call this directly, use set_stacked_on_url(None).
845
772
        """
846
773
        pb = ui.ui_factory.nested_progress_bar()
855
782
            old_repository = self.repository
856
783
            if len(old_repository._fallback_repositories) != 1:
857
784
                raise AssertionError("can't cope with fallback repositories "
858
 
                    "of %r (fallbacks: %r)" % (old_repository,
859
 
                        old_repository._fallback_repositories))
860
 
            # Open the new repository object.
861
 
            # Repositories don't offer an interface to remove fallback
862
 
            # repositories today; take the conceptually simpler option and just
863
 
            # reopen it.  We reopen it starting from the URL so that we
864
 
            # get a separate connection for RemoteRepositories and can
865
 
            # stream from one of them to the other.  This does mean doing
866
 
            # separate SSH connection setup, but unstacking is not a
867
 
            # common operation so it's tolerable.
868
 
            new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
869
 
            new_repository = new_bzrdir.find_repository()
870
 
            if new_repository._fallback_repositories:
871
 
                raise AssertionError("didn't expect %r to have "
872
 
                    "fallback_repositories"
873
 
                    % (self.repository,))
874
 
            # Replace self.repository with the new repository.
875
 
            # Do our best to transfer the lock state (i.e. lock-tokens and
876
 
            # lock count) of self.repository to the new repository.
877
 
            lock_token = old_repository.lock_write().repository_token
878
 
            self.repository = new_repository
879
 
            if isinstance(self, remote.RemoteBranch):
880
 
                # Remote branches can have a second reference to the old
881
 
                # repository that need to be replaced.
882
 
                if self._real_branch is not None:
883
 
                    self._real_branch.repository = new_repository
884
 
            self.repository.lock_write(token=lock_token)
885
 
            if lock_token is not None:
886
 
                old_repository.leave_lock_in_place()
 
785
                    "of %r" % (self.repository,))
 
786
            # unlock it, including unlocking the fallback
887
787
            old_repository.unlock()
888
 
            if lock_token is not None:
889
 
                # XXX: self.repository.leave_lock_in_place() before this
890
 
                # function will not be preserved.  Fortunately that doesn't
891
 
                # affect the current default format (2a), and would be a
892
 
                # corner-case anyway.
893
 
                #  - Andrew Bennetts, 2010/06/30
894
 
                self.repository.dont_leave_lock_in_place()
895
 
            old_lock_count = 0
896
 
            while True:
897
 
                try:
898
 
                    old_repository.unlock()
899
 
                except errors.LockNotHeld:
900
 
                    break
901
 
                old_lock_count += 1
902
 
            if old_lock_count == 0:
903
 
                raise AssertionError(
904
 
                    'old_repository should have been locked at least once.')
905
 
            for i in range(old_lock_count-1):
 
788
            old_repository.lock_read()
 
789
            try:
 
790
                # Repositories don't offer an interface to remove fallback
 
791
                # repositories today; take the conceptually simpler option and just
 
792
                # reopen it.  We reopen it starting from the URL so that we
 
793
                # get a separate connection for RemoteRepositories and can
 
794
                # stream from one of them to the other.  This does mean doing
 
795
                # separate SSH connection setup, but unstacking is not a
 
796
                # common operation so it's tolerable.
 
797
                new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
 
798
                new_repository = new_bzrdir.find_repository()
 
799
                self.repository = new_repository
 
800
                if self.repository._fallback_repositories:
 
801
                    raise AssertionError("didn't expect %r to have "
 
802
                        "fallback_repositories"
 
803
                        % (self.repository,))
 
804
                # this is not paired with an unlock because it's just restoring
 
805
                # the previous state; the lock's released when set_stacked_on_url
 
806
                # returns
906
807
                self.repository.lock_write()
907
 
            # Fetch from the old repository into the new.
908
 
            old_repository.lock_read()
909
 
            try:
910
808
                # XXX: If you unstack a branch while it has a working tree
911
809
                # with a pending merge, the pending-merged revisions will no
912
810
                # longer be present.  You can (probably) revert and remerge.
913
 
                try:
914
 
                    tags_to_fetch = set(self.tags.get_reverse_tag_dict())
915
 
                except errors.TagsNotSupported:
916
 
                    tags_to_fetch = set()
917
 
                fetch_spec = _mod_graph.NotInOtherForRevs(self.repository,
918
 
                    old_repository, required_ids=[self.last_revision()],
919
 
                    if_present_ids=tags_to_fetch, find_ghosts=True).execute()
920
 
                self.repository.fetch(old_repository, fetch_spec=fetch_spec)
 
811
                #
 
812
                # XXX: This only fetches up to the tip of the repository; it
 
813
                # doesn't bring across any tags.  That's fairly consistent
 
814
                # with how branch works, but perhaps not ideal.
 
815
                self.repository.fetch(old_repository,
 
816
                    revision_id=self.last_revision(),
 
817
                    find_ghosts=True)
921
818
            finally:
922
819
                old_repository.unlock()
923
820
        finally:
928
825
 
929
826
        :seealso: Branch._get_tags_bytes.
930
827
        """
931
 
        return _run_with_write_locked_target(self, self._set_tags_bytes_locked,
932
 
                bytes)
933
 
 
934
 
    def _set_tags_bytes_locked(self, bytes):
935
 
        self._tags_bytes = bytes
936
 
        return self._transport.put_bytes('tags', bytes)
 
828
        return _run_with_write_locked_target(self, self._transport.put_bytes,
 
829
            'tags', bytes)
937
830
 
938
831
    def _cache_revision_history(self, rev_history):
939
832
        """Set the cached revision history to rev_history.
966
859
        self._revision_history_cache = None
967
860
        self._revision_id_to_revno_cache = None
968
861
        self._last_revision_info_cache = None
969
 
        self._master_branch_cache = None
970
862
        self._merge_sorted_revisions_cache = None
971
863
        self._partial_revision_history_cache = []
972
864
        self._partial_revision_id_to_revno_cache = {}
973
 
        self._tags_bytes = None
974
865
 
975
866
    def _gen_revision_history(self):
976
867
        """Return sequence of revision hashes on to this branch.
1026
917
        :return: A tuple (revno, revision_id).
1027
918
        """
1028
919
        if self._last_revision_info_cache is None:
1029
 
            self._last_revision_info_cache = self._read_last_revision_info()
 
920
            self._last_revision_info_cache = self._last_revision_info()
1030
921
        return self._last_revision_info_cache
1031
922
 
1032
 
    def _read_last_revision_info(self):
1033
 
        raise NotImplementedError(self._read_last_revision_info)
1034
 
 
1035
 
    @deprecated_method(deprecated_in((2, 4, 0)))
 
923
    def _last_revision_info(self):
 
924
        rh = self.revision_history()
 
925
        revno = len(rh)
 
926
        if revno:
 
927
            return (revno, rh[-1])
 
928
        else:
 
929
            return (0, _mod_revision.NULL_REVISION)
 
930
 
 
931
    @deprecated_method(deprecated_in((1, 6, 0)))
 
932
    def missing_revisions(self, other, stop_revision=None):
 
933
        """Return a list of new revisions that would perfectly fit.
 
934
 
 
935
        If self and other have not diverged, return a list of the revisions
 
936
        present in other, but missing from self.
 
937
        """
 
938
        self_history = self.revision_history()
 
939
        self_len = len(self_history)
 
940
        other_history = other.revision_history()
 
941
        other_len = len(other_history)
 
942
        common_index = min(self_len, other_len) -1
 
943
        if common_index >= 0 and \
 
944
            self_history[common_index] != other_history[common_index]:
 
945
            raise errors.DivergedBranches(self, other)
 
946
 
 
947
        if stop_revision is None:
 
948
            stop_revision = other_len
 
949
        else:
 
950
            if stop_revision > other_len:
 
951
                raise errors.NoSuchRevision(self, stop_revision)
 
952
        return other_history[self_len:stop_revision]
 
953
 
 
954
    @needs_write_lock
 
955
    def update_revisions(self, other, stop_revision=None, overwrite=False,
 
956
                         graph=None):
 
957
        """Pull in new perfect-fit revisions.
 
958
 
 
959
        :param other: Another Branch to pull from
 
960
        :param stop_revision: Updated until the given revision
 
961
        :param overwrite: Always set the branch pointer, rather than checking
 
962
            to see if it is a proper descendant.
 
963
        :param graph: A Graph object that can be used to query history
 
964
            information. This can be None.
 
965
        :return: None
 
966
        """
 
967
        return InterBranch.get(other, self).update_revisions(stop_revision,
 
968
            overwrite, graph)
 
969
 
1036
970
    def import_last_revision_info(self, source_repo, revno, revid):
1037
971
        """Set the last revision info, importing from another repo if necessary.
1038
972
 
 
973
        This is used by the bound branch code to upload a revision to
 
974
        the master branch first before updating the tip of the local branch.
 
975
 
1039
976
        :param source_repo: Source repository to optionally fetch from
1040
977
        :param revno: Revision number of the new tip
1041
978
        :param revid: Revision id of the new tip
1044
981
            self.repository.fetch(source_repo, revision_id=revid)
1045
982
        self.set_last_revision_info(revno, revid)
1046
983
 
1047
 
    def import_last_revision_info_and_tags(self, source, revno, revid,
1048
 
                                           lossy=False):
1049
 
        """Set the last revision info, importing from another repo if necessary.
1050
 
 
1051
 
        This is used by the bound branch code to upload a revision to
1052
 
        the master branch first before updating the tip of the local branch.
1053
 
        Revisions referenced by source's tags are also transferred.
1054
 
 
1055
 
        :param source: Source branch to optionally fetch from
1056
 
        :param revno: Revision number of the new tip
1057
 
        :param revid: Revision id of the new tip
1058
 
        :param lossy: Whether to discard metadata that can not be
1059
 
            natively represented
1060
 
        :return: Tuple with the new revision number and revision id
1061
 
            (should only be different from the arguments when lossy=True)
1062
 
        """
1063
 
        if not self.repository.has_same_location(source.repository):
1064
 
            self.fetch(source, revid)
1065
 
        self.set_last_revision_info(revno, revid)
1066
 
        return (revno, revid)
1067
 
 
1068
984
    def revision_id_to_revno(self, revision_id):
1069
985
        """Given a revision id, return its revno"""
1070
986
        if _mod_revision.is_null(revision_id):
1090
1006
            self._extend_partial_history(distance_from_last)
1091
1007
        return self._partial_revision_history_cache[distance_from_last]
1092
1008
 
 
1009
    @needs_write_lock
1093
1010
    def pull(self, source, overwrite=False, stop_revision=None,
1094
1011
             possible_transports=None, *args, **kwargs):
1095
1012
        """Mirror source into this branch.
1291
1208
        return result
1292
1209
 
1293
1210
    @needs_read_lock
1294
 
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None,
1295
 
            repository=None):
 
1211
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None):
1296
1212
        """Create a new line of development from the branch, into to_bzrdir.
1297
1213
 
1298
1214
        to_bzrdir controls the branch format.
1303
1219
        if (repository_policy is not None and
1304
1220
            repository_policy.requires_stacking()):
1305
1221
            to_bzrdir._format.require_stacking(_skip_repo=True)
1306
 
        result = to_bzrdir.create_branch(repository=repository)
 
1222
        result = to_bzrdir.create_branch()
1307
1223
        result.lock_write()
1308
1224
        try:
1309
1225
            if repository_policy is not None:
1310
1226
                repository_policy.configure_branch(result)
1311
1227
            self.copy_content_into(result, revision_id=revision_id)
1312
 
            master_branch = self.get_master_branch()
1313
 
            if master_branch is None:
1314
 
                result.set_parent(self.bzrdir.root_transport.base)
1315
 
            else:
1316
 
                result.set_parent(master_branch.bzrdir.root_transport.base)
 
1228
            result.set_parent(self.bzrdir.root_transport.base)
1317
1229
        finally:
1318
1230
            result.unlock()
1319
1231
        return result
1343
1255
                revno = 1
1344
1256
        destination.set_last_revision_info(revno, revision_id)
1345
1257
 
 
1258
    @needs_read_lock
1346
1259
    def copy_content_into(self, destination, revision_id=None):
1347
1260
        """Copy the content of self into destination.
1348
1261
 
1349
1262
        revision_id: if not None, the revision history in the new branch will
1350
1263
                     be truncated to end with revision_id.
1351
1264
        """
1352
 
        return InterBranch.get(self, destination).copy_content_into(
1353
 
            revision_id=revision_id)
 
1265
        self.update_references(destination)
 
1266
        self._synchronize_history(destination, revision_id)
 
1267
        try:
 
1268
            parent = self.get_parent()
 
1269
        except errors.InaccessibleParent, e:
 
1270
            mutter('parent was not accessible to copy: %s', e)
 
1271
        else:
 
1272
            if parent:
 
1273
                destination.set_parent(parent)
 
1274
        if self._push_should_merge_tags():
 
1275
            self.tags.merge_to(destination.tags)
1354
1276
 
1355
1277
    def update_references(self, target):
1356
1278
        if not getattr(self._format, 'supports_reference_locations', False):
1401
1323
        """Return the most suitable metadir for a checkout of this branch.
1402
1324
        Weaves are used if this branch's repository uses weaves.
1403
1325
        """
1404
 
        format = self.repository.bzrdir.checkout_metadir()
1405
 
        format.set_branch_format(self._format)
 
1326
        if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
 
1327
            from bzrlib.repofmt import weaverepo
 
1328
            format = bzrdir.BzrDirMetaFormat1()
 
1329
            format.repository_format = weaverepo.RepositoryFormat7()
 
1330
        else:
 
1331
            format = self.repository.bzrdir.checkout_metadir()
 
1332
            format.set_branch_format(self._format)
1406
1333
        return format
1407
1334
 
1408
1335
    def create_clone_on_transport(self, to_transport, revision_id=None,
1409
 
        stacked_on=None, create_prefix=False, use_existing_dir=False,
1410
 
        no_tree=None):
 
1336
        stacked_on=None, create_prefix=False, use_existing_dir=False):
1411
1337
        """Create a clone of this branch and its bzrdir.
1412
1338
 
1413
1339
        :param to_transport: The transport to clone onto.
1420
1346
        """
1421
1347
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1422
1348
        # clone call. Or something. 20090224 RBC/spiv.
1423
 
        # XXX: Should this perhaps clone colocated branches as well, 
1424
 
        # rather than just the default branch? 20100319 JRV
1425
1349
        if revision_id is None:
1426
1350
            revision_id = self.last_revision()
1427
1351
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1428
1352
            revision_id=revision_id, stacked_on=stacked_on,
1429
 
            create_prefix=create_prefix, use_existing_dir=use_existing_dir,
1430
 
            no_tree=no_tree)
 
1353
            create_prefix=create_prefix, use_existing_dir=use_existing_dir)
1431
1354
        return dir_to.open_branch()
1432
1355
 
1433
1356
    def create_checkout(self, to_location, revision_id=None,
1548
1471
        else:
1549
1472
            raise AssertionError("invalid heads: %r" % (heads,))
1550
1473
 
1551
 
    def heads_to_fetch(self):
1552
 
        """Return the heads that must and that should be fetched to copy this
1553
 
        branch into another repo.
1554
 
 
1555
 
        :returns: a 2-tuple of (must_fetch, if_present_fetch).  must_fetch is a
1556
 
            set of heads that must be fetched.  if_present_fetch is a set of
1557
 
            heads that must be fetched if present, but no error is necessary if
1558
 
            they are not present.
1559
 
        """
1560
 
        # For bzr native formats must_fetch is just the tip, and if_present_fetch
1561
 
        # are the tags.
1562
 
        must_fetch = set([self.last_revision()])
1563
 
        try:
1564
 
            if_present_fetch = set(self.tags.get_reverse_tag_dict())
1565
 
        except errors.TagsNotSupported:
1566
 
            if_present_fetch = set()
1567
 
        must_fetch.discard(_mod_revision.NULL_REVISION)
1568
 
        if_present_fetch.discard(_mod_revision.NULL_REVISION)
1569
 
        return must_fetch, if_present_fetch
1570
 
 
1571
 
 
1572
 
class BranchFormat(controldir.ControlComponentFormat):
 
1474
 
 
1475
class BranchFormat(object):
1573
1476
    """An encapsulation of the initialization and open routines for a format.
1574
1477
 
1575
1478
    Formats provide three things:
1578
1481
     * an open routine.
1579
1482
 
1580
1483
    Formats are placed in an dict by their format string for reference
1581
 
    during branch opening. It's not required that these be instances, they
 
1484
    during branch opening. Its not required that these be instances, they
1582
1485
    can be classes themselves with class methods - it simply depends on
1583
1486
    whether state is needed for a given format or not.
1584
1487
 
1587
1490
    object will be created every time regardless.
1588
1491
    """
1589
1492
 
 
1493
    _default_format = None
 
1494
    """The default format used for new branches."""
 
1495
 
 
1496
    _formats = {}
 
1497
    """The known formats."""
 
1498
 
1590
1499
    can_set_append_revisions_only = True
1591
1500
 
1592
1501
    def __eq__(self, other):
1601
1510
        try:
1602
1511
            transport = a_bzrdir.get_branch_transport(None, name=name)
1603
1512
            format_string = transport.get_bytes("format")
1604
 
            return format_registry.get(format_string)
 
1513
            return klass._formats[format_string]
1605
1514
        except errors.NoSuchFile:
1606
1515
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1607
1516
        except KeyError:
1608
1517
            raise errors.UnknownFormatError(format=format_string, kind='branch')
1609
1518
 
1610
1519
    @classmethod
1611
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1612
1520
    def get_default_format(klass):
1613
1521
        """Return the current default format."""
1614
 
        return format_registry.get_default()
1615
 
 
1616
 
    @classmethod
1617
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1618
 
    def get_formats(klass):
1619
 
        """Get all the known formats.
1620
 
 
1621
 
        Warning: This triggers a load of all lazy registered formats: do not
1622
 
        use except when that is desireed.
1623
 
        """
1624
 
        return format_registry._get_all()
1625
 
 
1626
 
    def get_reference(self, a_bzrdir, name=None):
 
1522
        return klass._default_format
 
1523
 
 
1524
    def get_reference(self, a_bzrdir):
1627
1525
        """Get the target reference of the branch in a_bzrdir.
1628
1526
 
1629
1527
        format probing must have been completed before calling
1631
1529
        in a_bzrdir is correct.
1632
1530
 
1633
1531
        :param a_bzrdir: The bzrdir to get the branch data from.
1634
 
        :param name: Name of the colocated branch to fetch
1635
1532
        :return: None if the branch is not a reference branch.
1636
1533
        """
1637
1534
        return None
1638
1535
 
1639
1536
    @classmethod
1640
 
    def set_reference(self, a_bzrdir, name, to_branch):
 
1537
    def set_reference(self, a_bzrdir, to_branch):
1641
1538
        """Set the target reference of the branch in a_bzrdir.
1642
1539
 
1643
1540
        format probing must have been completed before calling
1645
1542
        in a_bzrdir is correct.
1646
1543
 
1647
1544
        :param a_bzrdir: The bzrdir to set the branch reference for.
1648
 
        :param name: Name of colocated branch to set, None for default
1649
1545
        :param to_branch: branch that the checkout is to reference
1650
1546
        """
1651
1547
        raise NotImplementedError(self.set_reference)
1666
1562
        for hook in hooks:
1667
1563
            hook(params)
1668
1564
 
1669
 
    def initialize(self, a_bzrdir, name=None, repository=None):
 
1565
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
 
1566
                           lock_type='metadir', set_format=True):
 
1567
        """Initialize a branch in a bzrdir, with specified files
 
1568
 
 
1569
        :param a_bzrdir: The bzrdir to initialize the branch in
 
1570
        :param utf8_files: The files to create as a list of
 
1571
            (filename, content) tuples
 
1572
        :param name: Name of colocated branch to create, if any
 
1573
        :param set_format: If True, set the format with
 
1574
            self.get_format_string.  (BzrBranch4 has its format set
 
1575
            elsewhere)
 
1576
        :return: a branch in this format
 
1577
        """
 
1578
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
 
1579
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
1580
        lock_map = {
 
1581
            'metadir': ('lock', lockdir.LockDir),
 
1582
            'branch4': ('branch-lock', lockable_files.TransportLock),
 
1583
        }
 
1584
        lock_name, lock_class = lock_map[lock_type]
 
1585
        control_files = lockable_files.LockableFiles(branch_transport,
 
1586
            lock_name, lock_class)
 
1587
        control_files.create_lock()
 
1588
        try:
 
1589
            control_files.lock_write()
 
1590
        except errors.LockContention:
 
1591
            if lock_type != 'branch4':
 
1592
                raise
 
1593
            lock_taken = False
 
1594
        else:
 
1595
            lock_taken = True
 
1596
        if set_format:
 
1597
            utf8_files += [('format', self.get_format_string())]
 
1598
        try:
 
1599
            for (filename, content) in utf8_files:
 
1600
                branch_transport.put_bytes(
 
1601
                    filename, content,
 
1602
                    mode=a_bzrdir._get_file_mode())
 
1603
        finally:
 
1604
            if lock_taken:
 
1605
                control_files.unlock()
 
1606
        branch = self.open(a_bzrdir, name, _found=True)
 
1607
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
 
1608
        return branch
 
1609
 
 
1610
    def initialize(self, a_bzrdir, name=None):
1670
1611
        """Create a branch of this format in a_bzrdir.
1671
1612
        
1672
1613
        :param name: Name of the colocated branch to create.
1706
1647
        """
1707
1648
        raise NotImplementedError(self.network_name)
1708
1649
 
1709
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
1710
 
            found_repository=None):
 
1650
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
1711
1651
        """Return the branch object for a_bzrdir
1712
1652
 
1713
1653
        :param a_bzrdir: A BzrDir that contains a branch.
1720
1660
        raise NotImplementedError(self.open)
1721
1661
 
1722
1662
    @classmethod
1723
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1724
1663
    def register_format(klass, format):
1725
 
        """Register a metadir format.
1726
 
 
1727
 
        See MetaDirBranchFormatFactory for the ability to register a format
1728
 
        without loading the code the format needs until it is actually used.
1729
 
        """
1730
 
        format_registry.register(format)
 
1664
        """Register a metadir format."""
 
1665
        klass._formats[format.get_format_string()] = format
 
1666
        # Metadir formats have a network name of their format string, and get
 
1667
        # registered as class factories.
 
1668
        network_format_registry.register(format.get_format_string(), format.__class__)
1731
1669
 
1732
1670
    @classmethod
1733
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1734
1671
    def set_default_format(klass, format):
1735
 
        format_registry.set_default(format)
 
1672
        klass._default_format = format
1736
1673
 
1737
1674
    def supports_set_append_revisions_only(self):
1738
1675
        """True if this format supports set_append_revisions_only."""
1742
1679
        """True if this format records a stacked-on branch."""
1743
1680
        return False
1744
1681
 
1745
 
    def supports_leaving_lock(self):
1746
 
        """True if this format supports leaving locks in place."""
1747
 
        return False # by default
1748
 
 
1749
1682
    @classmethod
1750
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1751
1683
    def unregister_format(klass, format):
1752
 
        format_registry.remove(format)
 
1684
        del klass._formats[format.get_format_string()]
1753
1685
 
1754
1686
    def __str__(self):
1755
1687
        return self.get_format_description().rstrip()
1759
1691
        return False  # by default
1760
1692
 
1761
1693
 
1762
 
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
1763
 
    """A factory for a BranchFormat object, permitting simple lazy registration.
1764
 
    
1765
 
    While none of the built in BranchFormats are lazy registered yet,
1766
 
    bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
1767
 
    use it, and the bzr-loom plugin uses it as well (see
1768
 
    bzrlib.plugins.loom.formats).
1769
 
    """
1770
 
 
1771
 
    def __init__(self, format_string, module_name, member_name):
1772
 
        """Create a MetaDirBranchFormatFactory.
1773
 
 
1774
 
        :param format_string: The format string the format has.
1775
 
        :param module_name: Module to load the format class from.
1776
 
        :param member_name: Attribute name within the module for the format class.
1777
 
        """
1778
 
        registry._LazyObjectGetter.__init__(self, module_name, member_name)
1779
 
        self._format_string = format_string
1780
 
        
1781
 
    def get_format_string(self):
1782
 
        """See BranchFormat.get_format_string."""
1783
 
        return self._format_string
1784
 
 
1785
 
    def __call__(self):
1786
 
        """Used for network_format_registry support."""
1787
 
        return self.get_obj()()
1788
 
 
1789
 
 
1790
1694
class BranchHooks(Hooks):
1791
1695
    """A dictionary mapping hook name to a list of callables for branch hooks.
1792
1696
 
1800
1704
        These are all empty initially, because by default nothing should get
1801
1705
        notified.
1802
1706
        """
1803
 
        Hooks.__init__(self, "bzrlib.branch", "Branch.hooks")
1804
 
        self.add_hook('set_rh',
 
1707
        Hooks.__init__(self)
 
1708
        self.create_hook(HookPoint('set_rh',
1805
1709
            "Invoked whenever the revision history has been set via "
1806
1710
            "set_revision_history. The api signature is (branch, "
1807
1711
            "revision_history), and the branch will be write-locked. "
1808
1712
            "The set_rh hook can be expensive for bzr to trigger, a better "
1809
 
            "hook to use is Branch.post_change_branch_tip.", (0, 15))
1810
 
        self.add_hook('open',
 
1713
            "hook to use is Branch.post_change_branch_tip.", (0, 15), None))
 
1714
        self.create_hook(HookPoint('open',
1811
1715
            "Called with the Branch object that has been opened after a "
1812
 
            "branch is opened.", (1, 8))
1813
 
        self.add_hook('post_push',
 
1716
            "branch is opened.", (1, 8), None))
 
1717
        self.create_hook(HookPoint('post_push',
1814
1718
            "Called after a push operation completes. post_push is called "
1815
1719
            "with a bzrlib.branch.BranchPushResult object and only runs in the "
1816
 
            "bzr client.", (0, 15))
1817
 
        self.add_hook('post_pull',
 
1720
            "bzr client.", (0, 15), None))
 
1721
        self.create_hook(HookPoint('post_pull',
1818
1722
            "Called after a pull operation completes. post_pull is called "
1819
1723
            "with a bzrlib.branch.PullResult object and only runs in the "
1820
 
            "bzr client.", (0, 15))
1821
 
        self.add_hook('pre_commit',
1822
 
            "Called after a commit is calculated but before it is "
 
1724
            "bzr client.", (0, 15), None))
 
1725
        self.create_hook(HookPoint('pre_commit',
 
1726
            "Called after a commit is calculated but before it is is "
1823
1727
            "completed. pre_commit is called with (local, master, old_revno, "
1824
1728
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
1825
1729
            "). old_revid is NULL_REVISION for the first commit to a branch, "
1827
1731
            "basis revision. hooks MUST NOT modify this delta. "
1828
1732
            " future_tree is an in-memory tree obtained from "
1829
1733
            "CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1830
 
            "tree.", (0,91))
1831
 
        self.add_hook('post_commit',
 
1734
            "tree.", (0,91), None))
 
1735
        self.create_hook(HookPoint('post_commit',
1832
1736
            "Called in the bzr client after a commit has completed. "
1833
1737
            "post_commit is called with (local, master, old_revno, old_revid, "
1834
1738
            "new_revno, new_revid). old_revid is NULL_REVISION for the first "
1835
 
            "commit to a branch.", (0, 15))
1836
 
        self.add_hook('post_uncommit',
 
1739
            "commit to a branch.", (0, 15), None))
 
1740
        self.create_hook(HookPoint('post_uncommit',
1837
1741
            "Called in the bzr client after an uncommit completes. "
1838
1742
            "post_uncommit is called with (local, master, old_revno, "
1839
1743
            "old_revid, new_revno, new_revid) where local is the local branch "
1840
1744
            "or None, master is the target branch, and an empty branch "
1841
 
            "receives new_revno of 0, new_revid of None.", (0, 15))
1842
 
        self.add_hook('pre_change_branch_tip',
 
1745
            "receives new_revno of 0, new_revid of None.", (0, 15), None))
 
1746
        self.create_hook(HookPoint('pre_change_branch_tip',
1843
1747
            "Called in bzr client and server before a change to the tip of a "
1844
1748
            "branch is made. pre_change_branch_tip is called with a "
1845
1749
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1846
 
            "commit, uncommit will all trigger this hook.", (1, 6))
1847
 
        self.add_hook('post_change_branch_tip',
 
1750
            "commit, uncommit will all trigger this hook.", (1, 6), None))
 
1751
        self.create_hook(HookPoint('post_change_branch_tip',
1848
1752
            "Called in bzr client and server after a change to the tip of a "
1849
1753
            "branch is made. post_change_branch_tip is called with a "
1850
1754
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1851
 
            "commit, uncommit will all trigger this hook.", (1, 4))
1852
 
        self.add_hook('transform_fallback_location',
 
1755
            "commit, uncommit will all trigger this hook.", (1, 4), None))
 
1756
        self.create_hook(HookPoint('transform_fallback_location',
1853
1757
            "Called when a stacked branch is activating its fallback "
1854
1758
            "locations. transform_fallback_location is called with (branch, "
1855
1759
            "url), and should return a new url. Returning the same url "
1860
1764
            "fallback locations have not been activated. When there are "
1861
1765
            "multiple hooks installed for transform_fallback_location, "
1862
1766
            "all are called with the url returned from the previous hook."
1863
 
            "The order is however undefined.", (1, 9))
1864
 
        self.add_hook('automatic_tag_name',
1865
 
            "Called to determine an automatic tag name for a revision. "
 
1767
            "The order is however undefined.", (1, 9), None))
 
1768
        self.create_hook(HookPoint('automatic_tag_name',
 
1769
            "Called to determine an automatic tag name for a revision."
1866
1770
            "automatic_tag_name is called with (branch, revision_id) and "
1867
1771
            "should return a tag name or None if no tag name could be "
1868
1772
            "determined. The first non-None tag name returned will be used.",
1869
 
            (2, 2))
1870
 
        self.add_hook('post_branch_init',
 
1773
            (2, 2), None))
 
1774
        self.create_hook(HookPoint('post_branch_init',
1871
1775
            "Called after new branch initialization completes. "
1872
1776
            "post_branch_init is called with a "
1873
1777
            "bzrlib.branch.BranchInitHookParams. "
1874
1778
            "Note that init, branch and checkout (both heavyweight and "
1875
 
            "lightweight) will all trigger this hook.", (2, 2))
1876
 
        self.add_hook('post_switch',
 
1779
            "lightweight) will all trigger this hook.", (2, 2), None))
 
1780
        self.create_hook(HookPoint('post_switch',
1877
1781
            "Called after a checkout switches branch. "
1878
1782
            "post_switch is called with a "
1879
 
            "bzrlib.branch.SwitchHookParams.", (2, 2))
 
1783
            "bzrlib.branch.SwitchHookParams.", (2, 2), None))
1880
1784
 
1881
1785
 
1882
1786
 
1959
1863
        return self.__dict__ == other.__dict__
1960
1864
 
1961
1865
    def __repr__(self):
1962
 
        return "<%s of %s>" % (self.__class__.__name__, self.branch)
 
1866
        if self.branch:
 
1867
            return "<%s of %s>" % (self.__class__.__name__, self.branch)
 
1868
        else:
 
1869
            return "<%s of format:%s bzrdir:%s>" % (
 
1870
                self.__class__.__name__, self.branch,
 
1871
                self.format, self.bzrdir)
1963
1872
 
1964
1873
 
1965
1874
class SwitchHookParams(object):
1995
1904
            self.revision_id)
1996
1905
 
1997
1906
 
 
1907
class BzrBranchFormat4(BranchFormat):
 
1908
    """Bzr branch format 4.
 
1909
 
 
1910
    This format has:
 
1911
     - a revision-history file.
 
1912
     - a branch-lock lock file [ to be shared with the bzrdir ]
 
1913
    """
 
1914
 
 
1915
    def get_format_description(self):
 
1916
        """See BranchFormat.get_format_description()."""
 
1917
        return "Branch format 4"
 
1918
 
 
1919
    def initialize(self, a_bzrdir, name=None):
 
1920
        """Create a branch of this format in a_bzrdir."""
 
1921
        utf8_files = [('revision-history', ''),
 
1922
                      ('branch-name', ''),
 
1923
                      ]
 
1924
        return self._initialize_helper(a_bzrdir, utf8_files, name=name,
 
1925
                                       lock_type='branch4', set_format=False)
 
1926
 
 
1927
    def __init__(self):
 
1928
        super(BzrBranchFormat4, self).__init__()
 
1929
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
 
1930
 
 
1931
    def network_name(self):
 
1932
        """The network name for this format is the control dirs disk label."""
 
1933
        return self._matchingbzrdir.get_format_string()
 
1934
 
 
1935
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1936
        """See BranchFormat.open()."""
 
1937
        if not _found:
 
1938
            # we are being called directly and must probe.
 
1939
            raise NotImplementedError
 
1940
        return BzrBranch(_format=self,
 
1941
                         _control_files=a_bzrdir._control_files,
 
1942
                         a_bzrdir=a_bzrdir,
 
1943
                         name=name,
 
1944
                         _repository=a_bzrdir.open_repository())
 
1945
 
 
1946
    def __str__(self):
 
1947
        return "Bazaar-NG branch format 4"
 
1948
 
 
1949
 
1998
1950
class BranchFormatMetadir(BranchFormat):
1999
1951
    """Common logic for meta-dir based branch formats."""
2000
1952
 
2002
1954
        """What class to instantiate on open calls."""
2003
1955
        raise NotImplementedError(self._branch_class)
2004
1956
 
2005
 
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
2006
 
                           repository=None):
2007
 
        """Initialize a branch in a bzrdir, with specified files
2008
 
 
2009
 
        :param a_bzrdir: The bzrdir to initialize the branch in
2010
 
        :param utf8_files: The files to create as a list of
2011
 
            (filename, content) tuples
2012
 
        :param name: Name of colocated branch to create, if any
2013
 
        :return: a branch in this format
2014
 
        """
2015
 
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
2016
 
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
2017
 
        control_files = lockable_files.LockableFiles(branch_transport,
2018
 
            'lock', lockdir.LockDir)
2019
 
        control_files.create_lock()
2020
 
        control_files.lock_write()
2021
 
        try:
2022
 
            utf8_files += [('format', self.get_format_string())]
2023
 
            for (filename, content) in utf8_files:
2024
 
                branch_transport.put_bytes(
2025
 
                    filename, content,
2026
 
                    mode=a_bzrdir._get_file_mode())
2027
 
        finally:
2028
 
            control_files.unlock()
2029
 
        branch = self.open(a_bzrdir, name, _found=True,
2030
 
                found_repository=repository)
2031
 
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2032
 
        return branch
2033
 
 
2034
1957
    def network_name(self):
2035
1958
        """A simple byte string uniquely identifying this format for RPC calls.
2036
1959
 
2038
1961
        """
2039
1962
        return self.get_format_string()
2040
1963
 
2041
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
2042
 
            found_repository=None):
 
1964
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
2043
1965
        """See BranchFormat.open()."""
2044
1966
        if not _found:
2045
1967
            format = BranchFormat.find_format(a_bzrdir, name=name)
2050
1972
        try:
2051
1973
            control_files = lockable_files.LockableFiles(transport, 'lock',
2052
1974
                                                         lockdir.LockDir)
2053
 
            if found_repository is None:
2054
 
                found_repository = a_bzrdir.find_repository()
2055
1975
            return self._branch_class()(_format=self,
2056
1976
                              _control_files=control_files,
2057
1977
                              name=name,
2058
1978
                              a_bzrdir=a_bzrdir,
2059
 
                              _repository=found_repository,
 
1979
                              _repository=a_bzrdir.find_repository(),
2060
1980
                              ignore_fallbacks=ignore_fallbacks)
2061
1981
        except errors.NoSuchFile:
2062
1982
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
2069
1989
    def supports_tags(self):
2070
1990
        return True
2071
1991
 
2072
 
    def supports_leaving_lock(self):
2073
 
        return True
2074
 
 
2075
1992
 
2076
1993
class BzrBranchFormat5(BranchFormatMetadir):
2077
1994
    """Bzr branch format 5.
2097
2014
        """See BranchFormat.get_format_description()."""
2098
2015
        return "Branch format 5"
2099
2016
 
2100
 
    def initialize(self, a_bzrdir, name=None, repository=None):
 
2017
    def initialize(self, a_bzrdir, name=None):
2101
2018
        """Create a branch of this format in a_bzrdir."""
2102
2019
        utf8_files = [('revision-history', ''),
2103
2020
                      ('branch-name', ''),
2104
2021
                      ]
2105
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
2022
        return self._initialize_helper(a_bzrdir, utf8_files, name)
2106
2023
 
2107
2024
    def supports_tags(self):
2108
2025
        return False
2130
2047
        """See BranchFormat.get_format_description()."""
2131
2048
        return "Branch format 6"
2132
2049
 
2133
 
    def initialize(self, a_bzrdir, name=None, repository=None):
 
2050
    def initialize(self, a_bzrdir, name=None):
2134
2051
        """Create a branch of this format in a_bzrdir."""
2135
2052
        utf8_files = [('last-revision', '0 null:\n'),
2136
2053
                      ('branch.conf', ''),
2137
2054
                      ('tags', ''),
2138
2055
                      ]
2139
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
2056
        return self._initialize_helper(a_bzrdir, utf8_files, name)
2140
2057
 
2141
2058
    def make_tags(self, branch):
2142
2059
        """See bzrlib.branch.BranchFormat.make_tags()."""
2160
2077
        """See BranchFormat.get_format_description()."""
2161
2078
        return "Branch format 8"
2162
2079
 
2163
 
    def initialize(self, a_bzrdir, name=None, repository=None):
 
2080
    def initialize(self, a_bzrdir, name=None):
2164
2081
        """Create a branch of this format in a_bzrdir."""
2165
2082
        utf8_files = [('last-revision', '0 null:\n'),
2166
2083
                      ('branch.conf', ''),
2167
2084
                      ('tags', ''),
2168
2085
                      ('references', '')
2169
2086
                      ]
2170
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
2087
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2088
 
 
2089
    def __init__(self):
 
2090
        super(BzrBranchFormat8, self).__init__()
 
2091
        self._matchingbzrdir.repository_format = \
 
2092
            RepositoryFormatKnitPack5RichRoot()
2171
2093
 
2172
2094
    def make_tags(self, branch):
2173
2095
        """See bzrlib.branch.BranchFormat.make_tags()."""
2182
2104
    supports_reference_locations = True
2183
2105
 
2184
2106
 
2185
 
class BzrBranchFormat7(BranchFormatMetadir):
 
2107
class BzrBranchFormat7(BzrBranchFormat8):
2186
2108
    """Branch format with last-revision, tags, and a stacked location pointer.
2187
2109
 
2188
2110
    The stacked location pointer is passed down to the repository and requires
2191
2113
    This format was introduced in bzr 1.6.
2192
2114
    """
2193
2115
 
2194
 
    def initialize(self, a_bzrdir, name=None, repository=None):
 
2116
    def initialize(self, a_bzrdir, name=None):
2195
2117
        """Create a branch of this format in a_bzrdir."""
2196
2118
        utf8_files = [('last-revision', '0 null:\n'),
2197
2119
                      ('branch.conf', ''),
2198
2120
                      ('tags', ''),
2199
2121
                      ]
2200
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
2122
        return self._initialize_helper(a_bzrdir, utf8_files, name)
2201
2123
 
2202
2124
    def _branch_class(self):
2203
2125
        return BzrBranch7
2213
2135
    def supports_set_append_revisions_only(self):
2214
2136
        return True
2215
2137
 
2216
 
    def supports_stacking(self):
2217
 
        return True
2218
 
 
2219
 
    def make_tags(self, branch):
2220
 
        """See bzrlib.branch.BranchFormat.make_tags()."""
2221
 
        return BasicTags(branch)
2222
 
 
2223
2138
    supports_reference_locations = False
2224
2139
 
2225
2140
 
2242
2157
        """See BranchFormat.get_format_description()."""
2243
2158
        return "Checkout reference format 1"
2244
2159
 
2245
 
    def get_reference(self, a_bzrdir, name=None):
 
2160
    def get_reference(self, a_bzrdir):
2246
2161
        """See BranchFormat.get_reference()."""
2247
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
2162
        transport = a_bzrdir.get_branch_transport(None)
2248
2163
        return transport.get_bytes('location')
2249
2164
 
2250
 
    def set_reference(self, a_bzrdir, name, to_branch):
 
2165
    def set_reference(self, a_bzrdir, to_branch):
2251
2166
        """See BranchFormat.set_reference()."""
2252
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
2167
        transport = a_bzrdir.get_branch_transport(None)
2253
2168
        location = transport.put_bytes('location', to_branch.base)
2254
2169
 
2255
 
    def initialize(self, a_bzrdir, name=None, target_branch=None,
2256
 
            repository=None):
 
2170
    def initialize(self, a_bzrdir, name=None, target_branch=None):
2257
2171
        """Create a branch of this format in a_bzrdir."""
2258
2172
        if target_branch is None:
2259
2173
            # this format does not implement branch itself, thus the implicit
2287
2201
        return clone
2288
2202
 
2289
2203
    def open(self, a_bzrdir, name=None, _found=False, location=None,
2290
 
             possible_transports=None, ignore_fallbacks=False,
2291
 
             found_repository=None):
 
2204
             possible_transports=None, ignore_fallbacks=False):
2292
2205
        """Return the branch that the branch reference in a_bzrdir points at.
2293
2206
 
2294
2207
        :param a_bzrdir: A BzrDir that contains a branch.
2308
2221
                raise AssertionError("wrong format %r found for %r" %
2309
2222
                    (format, self))
2310
2223
        if location is None:
2311
 
            location = self.get_reference(a_bzrdir, name)
 
2224
            location = self.get_reference(a_bzrdir)
2312
2225
        real_bzrdir = bzrdir.BzrDir.open(
2313
2226
            location, possible_transports=possible_transports)
2314
2227
        result = real_bzrdir.open_branch(name=name, 
2325
2238
        return result
2326
2239
 
2327
2240
 
2328
 
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
2329
 
    """Branch format registry."""
2330
 
 
2331
 
    def __init__(self, other_registry=None):
2332
 
        super(BranchFormatRegistry, self).__init__(other_registry)
2333
 
        self._default_format = None
2334
 
 
2335
 
    def set_default(self, format):
2336
 
        self._default_format = format
2337
 
 
2338
 
    def get_default(self):
2339
 
        return self._default_format
2340
 
 
2341
 
 
2342
2241
network_format_registry = registry.FormatRegistry()
2343
2242
"""Registry of formats indexed by their network name.
2344
2243
 
2347
2246
BranchFormat.network_name() for more detail.
2348
2247
"""
2349
2248
 
2350
 
format_registry = BranchFormatRegistry(network_format_registry)
2351
 
 
2352
2249
 
2353
2250
# formats which have no format string are not discoverable
2354
2251
# and not independently creatable, so are not registered.
2356
2253
__format6 = BzrBranchFormat6()
2357
2254
__format7 = BzrBranchFormat7()
2358
2255
__format8 = BzrBranchFormat8()
2359
 
format_registry.register(__format5)
2360
 
format_registry.register(BranchReferenceFormat())
2361
 
format_registry.register(__format6)
2362
 
format_registry.register(__format7)
2363
 
format_registry.register(__format8)
2364
 
format_registry.set_default(__format7)
2365
 
 
2366
 
 
2367
 
class BranchWriteLockResult(LogicalLockResult):
2368
 
    """The result of write locking a branch.
2369
 
 
2370
 
    :ivar branch_token: The token obtained from the underlying branch lock, or
2371
 
        None.
2372
 
    :ivar unlock: A callable which will unlock the lock.
2373
 
    """
2374
 
 
2375
 
    def __init__(self, unlock, branch_token):
2376
 
        LogicalLockResult.__init__(self, unlock)
2377
 
        self.branch_token = branch_token
2378
 
 
2379
 
    def __repr__(self):
2380
 
        return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
2381
 
            self.unlock)
 
2256
BranchFormat.register_format(__format5)
 
2257
BranchFormat.register_format(BranchReferenceFormat())
 
2258
BranchFormat.register_format(__format6)
 
2259
BranchFormat.register_format(__format7)
 
2260
BranchFormat.register_format(__format8)
 
2261
BranchFormat.set_default_format(__format7)
 
2262
_legacy_formats = [BzrBranchFormat4(),
 
2263
    ]
 
2264
network_format_registry.register(
 
2265
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
2382
2266
 
2383
2267
 
2384
2268
class BzrBranch(Branch, _RelockDebugMixin):
2440
2324
        return self.control_files.is_locked()
2441
2325
 
2442
2326
    def lock_write(self, token=None):
2443
 
        """Lock the branch for write operations.
2444
 
 
2445
 
        :param token: A token to permit reacquiring a previously held and
2446
 
            preserved lock.
2447
 
        :return: A BranchWriteLockResult.
2448
 
        """
2449
2327
        if not self.is_locked():
2450
2328
            self._note_lock('w')
2451
2329
        # All-in-one needs to always unlock/lock.
2457
2335
        else:
2458
2336
            took_lock = False
2459
2337
        try:
2460
 
            return BranchWriteLockResult(self.unlock,
2461
 
                self.control_files.lock_write(token=token))
 
2338
            return self.control_files.lock_write(token=token)
2462
2339
        except:
2463
2340
            if took_lock:
2464
2341
                self.repository.unlock()
2465
2342
            raise
2466
2343
 
2467
2344
    def lock_read(self):
2468
 
        """Lock the branch for read operations.
2469
 
 
2470
 
        :return: A bzrlib.lock.LogicalLockResult.
2471
 
        """
2472
2345
        if not self.is_locked():
2473
2346
            self._note_lock('r')
2474
2347
        # All-in-one needs to always unlock/lock.
2481
2354
            took_lock = False
2482
2355
        try:
2483
2356
            self.control_files.lock_read()
2484
 
            return LogicalLockResult(self.unlock)
2485
2357
        except:
2486
2358
            if took_lock:
2487
2359
                self.repository.unlock()
2515
2387
        """See Branch.print_file."""
2516
2388
        return self.repository.print_file(file, revision_id)
2517
2389
 
 
2390
    def _write_revision_history(self, history):
 
2391
        """Factored out of set_revision_history.
 
2392
 
 
2393
        This performs the actual writing to disk.
 
2394
        It is intended to be called by BzrBranch5.set_revision_history."""
 
2395
        self._transport.put_bytes(
 
2396
            'revision-history', '\n'.join(history),
 
2397
            mode=self.bzrdir._get_file_mode())
 
2398
 
 
2399
    @needs_write_lock
 
2400
    def set_revision_history(self, rev_history):
 
2401
        """See Branch.set_revision_history."""
 
2402
        if 'evil' in debug.debug_flags:
 
2403
            mutter_callsite(3, "set_revision_history scales with history.")
 
2404
        check_not_reserved_id = _mod_revision.check_not_reserved_id
 
2405
        for rev_id in rev_history:
 
2406
            check_not_reserved_id(rev_id)
 
2407
        if Branch.hooks['post_change_branch_tip']:
 
2408
            # Don't calculate the last_revision_info() if there are no hooks
 
2409
            # that will use it.
 
2410
            old_revno, old_revid = self.last_revision_info()
 
2411
        if len(rev_history) == 0:
 
2412
            revid = _mod_revision.NULL_REVISION
 
2413
        else:
 
2414
            revid = rev_history[-1]
 
2415
        self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
 
2416
        self._write_revision_history(rev_history)
 
2417
        self._clear_cached_state()
 
2418
        self._cache_revision_history(rev_history)
 
2419
        for hook in Branch.hooks['set_rh']:
 
2420
            hook(self, rev_history)
 
2421
        if Branch.hooks['post_change_branch_tip']:
 
2422
            self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2423
 
 
2424
    def _synchronize_history(self, destination, revision_id):
 
2425
        """Synchronize last revision and revision history between branches.
 
2426
 
 
2427
        This version is most efficient when the destination is also a
 
2428
        BzrBranch5, but works for BzrBranch6 as long as the revision
 
2429
        history is the true lefthand parent history, and all of the revisions
 
2430
        are in the destination's repository.  If not, set_revision_history
 
2431
        will fail.
 
2432
 
 
2433
        :param destination: The branch to copy the history into
 
2434
        :param revision_id: The revision-id to truncate history at.  May
 
2435
          be None to copy complete history.
 
2436
        """
 
2437
        if not isinstance(destination._format, BzrBranchFormat5):
 
2438
            super(BzrBranch, self)._synchronize_history(
 
2439
                destination, revision_id)
 
2440
            return
 
2441
        if revision_id == _mod_revision.NULL_REVISION:
 
2442
            new_history = []
 
2443
        else:
 
2444
            new_history = self.revision_history()
 
2445
        if revision_id is not None and new_history != []:
 
2446
            try:
 
2447
                new_history = new_history[:new_history.index(revision_id) + 1]
 
2448
            except ValueError:
 
2449
                rev = self.repository.get_revision(revision_id)
 
2450
                new_history = rev.get_history(self.repository)[1:]
 
2451
        destination.set_revision_history(new_history)
 
2452
 
2518
2453
    @needs_write_lock
2519
2454
    def set_last_revision_info(self, revno, revision_id):
2520
 
        if not revision_id or not isinstance(revision_id, basestring):
2521
 
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
 
2455
        """Set the last revision of this branch.
 
2456
 
 
2457
        The caller is responsible for checking that the revno is correct
 
2458
        for this revision id.
 
2459
 
 
2460
        It may be possible to set the branch last revision to an id not
 
2461
        present in the repository.  However, branches can also be
 
2462
        configured to check constraints on history, in which case this may not
 
2463
        be permitted.
 
2464
        """
2522
2465
        revision_id = _mod_revision.ensure_null(revision_id)
2523
 
        old_revno, old_revid = self.last_revision_info()
2524
 
        if self._get_append_revisions_only():
2525
 
            self._check_history_violation(revision_id)
2526
 
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
2527
 
        self._write_last_revision_info(revno, revision_id)
2528
 
        self._clear_cached_state()
2529
 
        self._last_revision_info_cache = revno, revision_id
2530
 
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2466
        # this old format stores the full history, but this api doesn't
 
2467
        # provide it, so we must generate, and might as well check it's
 
2468
        # correct
 
2469
        history = self._lefthand_history(revision_id)
 
2470
        if len(history) != revno:
 
2471
            raise AssertionError('%d != %d' % (len(history), revno))
 
2472
        self.set_revision_history(history)
 
2473
 
 
2474
    def _gen_revision_history(self):
 
2475
        history = self._transport.get_bytes('revision-history').split('\n')
 
2476
        if history[-1:] == ['']:
 
2477
            # There shouldn't be a trailing newline, but just in case.
 
2478
            history.pop()
 
2479
        return history
 
2480
 
 
2481
    @needs_write_lock
 
2482
    def generate_revision_history(self, revision_id, last_rev=None,
 
2483
        other_branch=None):
 
2484
        """Create a new revision history that will finish with revision_id.
 
2485
 
 
2486
        :param revision_id: the new tip to use.
 
2487
        :param last_rev: The previous last_revision. If not None, then this
 
2488
            must be a ancestory of revision_id, or DivergedBranches is raised.
 
2489
        :param other_branch: The other branch that DivergedBranches should
 
2490
            raise with respect to.
 
2491
        """
 
2492
        self.set_revision_history(self._lefthand_history(revision_id,
 
2493
            last_rev, other_branch))
2531
2494
 
2532
2495
    def basis_tree(self):
2533
2496
        """See Branch.basis_tree."""
2542
2505
                pass
2543
2506
        return None
2544
2507
 
 
2508
    def _basic_push(self, target, overwrite, stop_revision):
 
2509
        """Basic implementation of push without bound branches or hooks.
 
2510
 
 
2511
        Must be called with source read locked and target write locked.
 
2512
        """
 
2513
        result = BranchPushResult()
 
2514
        result.source_branch = self
 
2515
        result.target_branch = target
 
2516
        result.old_revno, result.old_revid = target.last_revision_info()
 
2517
        self.update_references(target)
 
2518
        if result.old_revid != self.last_revision():
 
2519
            # We assume that during 'push' this repository is closer than
 
2520
            # the target.
 
2521
            graph = self.repository.get_graph(target.repository)
 
2522
            target.update_revisions(self, stop_revision,
 
2523
                overwrite=overwrite, graph=graph)
 
2524
        if self._push_should_merge_tags():
 
2525
            result.tag_conflicts = self.tags.merge_to(target.tags,
 
2526
                overwrite)
 
2527
        result.new_revno, result.new_revid = target.last_revision_info()
 
2528
        return result
 
2529
 
2545
2530
    def get_stacked_on_url(self):
2546
2531
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
2547
2532
 
2558
2543
            self._transport.put_bytes('parent', url + '\n',
2559
2544
                mode=self.bzrdir._get_file_mode())
2560
2545
 
 
2546
 
 
2547
class BzrBranch5(BzrBranch):
 
2548
    """A format 5 branch. This supports new features over plain branches.
 
2549
 
 
2550
    It has support for a master_branch which is the data for bound branches.
 
2551
    """
 
2552
 
 
2553
    def get_bound_location(self):
 
2554
        try:
 
2555
            return self._transport.get_bytes('bound')[:-1]
 
2556
        except errors.NoSuchFile:
 
2557
            return None
 
2558
 
 
2559
    @needs_read_lock
 
2560
    def get_master_branch(self, possible_transports=None):
 
2561
        """Return the branch we are bound to.
 
2562
 
 
2563
        :return: Either a Branch, or None
 
2564
 
 
2565
        This could memoise the branch, but if thats done
 
2566
        it must be revalidated on each new lock.
 
2567
        So for now we just don't memoise it.
 
2568
        # RBC 20060304 review this decision.
 
2569
        """
 
2570
        bound_loc = self.get_bound_location()
 
2571
        if not bound_loc:
 
2572
            return None
 
2573
        try:
 
2574
            return Branch.open(bound_loc,
 
2575
                               possible_transports=possible_transports)
 
2576
        except (errors.NotBranchError, errors.ConnectionError), e:
 
2577
            raise errors.BoundBranchConnectionFailure(
 
2578
                    self, bound_loc, e)
 
2579
 
2561
2580
    @needs_write_lock
2562
 
    def unbind(self):
2563
 
        """If bound, unbind"""
2564
 
        return self.set_bound_location(None)
 
2581
    def set_bound_location(self, location):
 
2582
        """Set the target where this branch is bound to.
 
2583
 
 
2584
        :param location: URL to the target branch
 
2585
        """
 
2586
        if location:
 
2587
            self._transport.put_bytes('bound', location+'\n',
 
2588
                mode=self.bzrdir._get_file_mode())
 
2589
        else:
 
2590
            try:
 
2591
                self._transport.delete('bound')
 
2592
            except errors.NoSuchFile:
 
2593
                return False
 
2594
            return True
2565
2595
 
2566
2596
    @needs_write_lock
2567
2597
    def bind(self, other):
2589
2619
        # history around
2590
2620
        self.set_bound_location(other.base)
2591
2621
 
2592
 
    def get_bound_location(self):
2593
 
        try:
2594
 
            return self._transport.get_bytes('bound')[:-1]
2595
 
        except errors.NoSuchFile:
2596
 
            return None
2597
 
 
2598
 
    @needs_read_lock
2599
 
    def get_master_branch(self, possible_transports=None):
2600
 
        """Return the branch we are bound to.
2601
 
 
2602
 
        :return: Either a Branch, or None
2603
 
        """
2604
 
        if self._master_branch_cache is None:
2605
 
            self._master_branch_cache = self._get_master_branch(
2606
 
                possible_transports)
2607
 
        return self._master_branch_cache
2608
 
 
2609
 
    def _get_master_branch(self, possible_transports):
2610
 
        bound_loc = self.get_bound_location()
2611
 
        if not bound_loc:
2612
 
            return None
2613
 
        try:
2614
 
            return Branch.open(bound_loc,
2615
 
                               possible_transports=possible_transports)
2616
 
        except (errors.NotBranchError, errors.ConnectionError), e:
2617
 
            raise errors.BoundBranchConnectionFailure(
2618
 
                    self, bound_loc, e)
2619
 
 
2620
2622
    @needs_write_lock
2621
 
    def set_bound_location(self, location):
2622
 
        """Set the target where this branch is bound to.
2623
 
 
2624
 
        :param location: URL to the target branch
2625
 
        """
2626
 
        self._master_branch_cache = None
2627
 
        if location:
2628
 
            self._transport.put_bytes('bound', location+'\n',
2629
 
                mode=self.bzrdir._get_file_mode())
2630
 
        else:
2631
 
            try:
2632
 
                self._transport.delete('bound')
2633
 
            except errors.NoSuchFile:
2634
 
                return False
2635
 
            return True
 
2623
    def unbind(self):
 
2624
        """If bound, unbind"""
 
2625
        return self.set_bound_location(None)
2636
2626
 
2637
2627
    @needs_write_lock
2638
2628
    def update(self, possible_transports=None):
2651
2641
            return old_tip
2652
2642
        return None
2653
2643
 
2654
 
    def _read_last_revision_info(self):
2655
 
        revision_string = self._transport.get_bytes('last-revision')
2656
 
        revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
2657
 
        revision_id = cache_utf8.get_cached_utf8(revision_id)
2658
 
        revno = int(revno)
2659
 
        return revno, revision_id
2660
 
 
2661
 
    def _write_last_revision_info(self, revno, revision_id):
2662
 
        """Simply write out the revision id, with no checks.
2663
 
 
2664
 
        Use set_last_revision_info to perform this safely.
2665
 
 
2666
 
        Does not update the revision_history cache.
2667
 
        """
2668
 
        revision_id = _mod_revision.ensure_null(revision_id)
2669
 
        out_string = '%d %s\n' % (revno, revision_id)
2670
 
        self._transport.put_bytes('last-revision', out_string,
2671
 
            mode=self.bzrdir._get_file_mode())
2672
 
 
2673
 
 
2674
 
class FullHistoryBzrBranch(BzrBranch):
2675
 
    """Bzr branch which contains the full revision history."""
2676
 
 
2677
 
    @needs_write_lock
2678
 
    def set_last_revision_info(self, revno, revision_id):
2679
 
        if not revision_id or not isinstance(revision_id, basestring):
2680
 
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2681
 
        revision_id = _mod_revision.ensure_null(revision_id)
2682
 
        # this old format stores the full history, but this api doesn't
2683
 
        # provide it, so we must generate, and might as well check it's
2684
 
        # correct
2685
 
        history = self._lefthand_history(revision_id)
2686
 
        if len(history) != revno:
2687
 
            raise AssertionError('%d != %d' % (len(history), revno))
2688
 
        self._set_revision_history(history)
2689
 
 
2690
 
    def _read_last_revision_info(self):
2691
 
        rh = self.revision_history()
2692
 
        revno = len(rh)
2693
 
        if revno:
2694
 
            return (revno, rh[-1])
2695
 
        else:
2696
 
            return (0, _mod_revision.NULL_REVISION)
2697
 
 
2698
 
    @deprecated_method(deprecated_in((2, 4, 0)))
2699
 
    @needs_write_lock
2700
 
    def set_revision_history(self, rev_history):
2701
 
        """See Branch.set_revision_history."""
2702
 
        self._set_revision_history(rev_history)
2703
 
 
2704
 
    def _set_revision_history(self, rev_history):
2705
 
        if 'evil' in debug.debug_flags:
2706
 
            mutter_callsite(3, "set_revision_history scales with history.")
2707
 
        check_not_reserved_id = _mod_revision.check_not_reserved_id
2708
 
        for rev_id in rev_history:
2709
 
            check_not_reserved_id(rev_id)
2710
 
        if Branch.hooks['post_change_branch_tip']:
2711
 
            # Don't calculate the last_revision_info() if there are no hooks
2712
 
            # that will use it.
2713
 
            old_revno, old_revid = self.last_revision_info()
2714
 
        if len(rev_history) == 0:
2715
 
            revid = _mod_revision.NULL_REVISION
2716
 
        else:
2717
 
            revid = rev_history[-1]
2718
 
        self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
2719
 
        self._write_revision_history(rev_history)
2720
 
        self._clear_cached_state()
2721
 
        self._cache_revision_history(rev_history)
2722
 
        for hook in Branch.hooks['set_rh']:
2723
 
            hook(self, rev_history)
2724
 
        if Branch.hooks['post_change_branch_tip']:
2725
 
            self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2726
 
 
2727
 
    def _write_revision_history(self, history):
2728
 
        """Factored out of set_revision_history.
2729
 
 
2730
 
        This performs the actual writing to disk.
2731
 
        It is intended to be called by set_revision_history."""
2732
 
        self._transport.put_bytes(
2733
 
            'revision-history', '\n'.join(history),
2734
 
            mode=self.bzrdir._get_file_mode())
2735
 
 
2736
 
    def _gen_revision_history(self):
2737
 
        history = self._transport.get_bytes('revision-history').split('\n')
2738
 
        if history[-1:] == ['']:
2739
 
            # There shouldn't be a trailing newline, but just in case.
2740
 
            history.pop()
2741
 
        return history
2742
 
 
2743
 
    def _synchronize_history(self, destination, revision_id):
2744
 
        if not isinstance(destination, FullHistoryBzrBranch):
2745
 
            super(BzrBranch, self)._synchronize_history(
2746
 
                destination, revision_id)
2747
 
            return
2748
 
        if revision_id == _mod_revision.NULL_REVISION:
2749
 
            new_history = []
2750
 
        else:
2751
 
            new_history = self.revision_history()
2752
 
        if revision_id is not None and new_history != []:
2753
 
            try:
2754
 
                new_history = new_history[:new_history.index(revision_id) + 1]
2755
 
            except ValueError:
2756
 
                rev = self.repository.get_revision(revision_id)
2757
 
                new_history = rev.get_history(self.repository)[1:]
2758
 
        destination._set_revision_history(new_history)
2759
 
 
2760
 
    @needs_write_lock
2761
 
    def generate_revision_history(self, revision_id, last_rev=None,
2762
 
        other_branch=None):
2763
 
        """Create a new revision history that will finish with revision_id.
2764
 
 
2765
 
        :param revision_id: the new tip to use.
2766
 
        :param last_rev: The previous last_revision. If not None, then this
2767
 
            must be a ancestory of revision_id, or DivergedBranches is raised.
2768
 
        :param other_branch: The other branch that DivergedBranches should
2769
 
            raise with respect to.
2770
 
        """
2771
 
        self._set_revision_history(self._lefthand_history(revision_id,
2772
 
            last_rev, other_branch))
2773
 
 
2774
 
 
2775
 
class BzrBranch5(FullHistoryBzrBranch):
2776
 
    """A format 5 branch. This supports new features over plain branches.
2777
 
 
2778
 
    It has support for a master_branch which is the data for bound branches.
2779
 
    """
2780
 
 
2781
 
 
2782
 
class BzrBranch8(BzrBranch):
 
2644
 
 
2645
class BzrBranch8(BzrBranch5):
2783
2646
    """A branch that stores tree-reference locations."""
2784
2647
 
2785
2648
    def _open_hook(self):
2811
2674
        self._last_revision_info_cache = None
2812
2675
        self._reference_info = None
2813
2676
 
 
2677
    def _last_revision_info(self):
 
2678
        revision_string = self._transport.get_bytes('last-revision')
 
2679
        revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
 
2680
        revision_id = cache_utf8.get_cached_utf8(revision_id)
 
2681
        revno = int(revno)
 
2682
        return revno, revision_id
 
2683
 
 
2684
    def _write_last_revision_info(self, revno, revision_id):
 
2685
        """Simply write out the revision id, with no checks.
 
2686
 
 
2687
        Use set_last_revision_info to perform this safely.
 
2688
 
 
2689
        Does not update the revision_history cache.
 
2690
        Intended to be called by set_last_revision_info and
 
2691
        _write_revision_history.
 
2692
        """
 
2693
        revision_id = _mod_revision.ensure_null(revision_id)
 
2694
        out_string = '%d %s\n' % (revno, revision_id)
 
2695
        self._transport.put_bytes('last-revision', out_string,
 
2696
            mode=self.bzrdir._get_file_mode())
 
2697
 
 
2698
    @needs_write_lock
 
2699
    def set_last_revision_info(self, revno, revision_id):
 
2700
        revision_id = _mod_revision.ensure_null(revision_id)
 
2701
        old_revno, old_revid = self.last_revision_info()
 
2702
        if self._get_append_revisions_only():
 
2703
            self._check_history_violation(revision_id)
 
2704
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
 
2705
        self._write_last_revision_info(revno, revision_id)
 
2706
        self._clear_cached_state()
 
2707
        self._last_revision_info_cache = revno, revision_id
 
2708
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2709
 
 
2710
    def _synchronize_history(self, destination, revision_id):
 
2711
        """Synchronize last revision and revision history between branches.
 
2712
 
 
2713
        :see: Branch._synchronize_history
 
2714
        """
 
2715
        # XXX: The base Branch has a fast implementation of this method based
 
2716
        # on set_last_revision_info, but BzrBranch/BzrBranch5 have a slower one
 
2717
        # that uses set_revision_history.  This class inherits from BzrBranch5,
 
2718
        # but wants the fast implementation, so it calls
 
2719
        # Branch._synchronize_history directly.
 
2720
        Branch._synchronize_history(self, destination, revision_id)
 
2721
 
2814
2722
    def _check_history_violation(self, revision_id):
2815
 
        current_revid = self.last_revision()
2816
 
        last_revision = _mod_revision.ensure_null(current_revid)
 
2723
        last_revision = _mod_revision.ensure_null(self.last_revision())
2817
2724
        if _mod_revision.is_null(last_revision):
2818
2725
            return
2819
 
        graph = self.repository.get_graph()
2820
 
        for lh_ancestor in graph.iter_lefthand_ancestry(revision_id):
2821
 
            if lh_ancestor == current_revid:
2822
 
                return
2823
 
        raise errors.AppendRevisionsOnlyViolation(self.user_url)
 
2726
        if last_revision not in self._lefthand_history(revision_id):
 
2727
            raise errors.AppendRevisionsOnlyViolation(self.user_url)
2824
2728
 
2825
2729
    def _gen_revision_history(self):
2826
2730
        """Generate the revision history from last revision
2829
2733
        self._extend_partial_history(stop_index=last_revno-1)
2830
2734
        return list(reversed(self._partial_revision_history_cache))
2831
2735
 
 
2736
    def _write_revision_history(self, history):
 
2737
        """Factored out of set_revision_history.
 
2738
 
 
2739
        This performs the actual writing to disk, with format-specific checks.
 
2740
        It is intended to be called by BzrBranch5.set_revision_history.
 
2741
        """
 
2742
        if len(history) == 0:
 
2743
            last_revision = 'null:'
 
2744
        else:
 
2745
            if history != self._lefthand_history(history[-1]):
 
2746
                raise errors.NotLefthandHistory(history)
 
2747
            last_revision = history[-1]
 
2748
        if self._get_append_revisions_only():
 
2749
            self._check_history_violation(last_revision)
 
2750
        self._write_last_revision_info(len(history), last_revision)
 
2751
 
2832
2752
    @needs_write_lock
2833
2753
    def _set_parent_location(self, url):
2834
2754
        """Set the parent branch"""
2920
2840
 
2921
2841
    def set_bound_location(self, location):
2922
2842
        """See Branch.set_push_location."""
2923
 
        self._master_branch_cache = None
2924
2843
        result = None
2925
2844
        config = self.get_config()
2926
2845
        if location is None:
2966
2885
        return self.get_config(
2967
2886
            ).get_user_option_as_bool('append_revisions_only')
2968
2887
 
 
2888
    @needs_write_lock
 
2889
    def generate_revision_history(self, revision_id, last_rev=None,
 
2890
                                  other_branch=None):
 
2891
        """See BzrBranch5.generate_revision_history"""
 
2892
        history = self._lefthand_history(revision_id, last_rev, other_branch)
 
2893
        revno = len(history)
 
2894
        self.set_last_revision_info(revno, revision_id)
 
2895
 
2969
2896
    @needs_read_lock
2970
2897
    def get_rev_id(self, revno, history=None):
2971
2898
        """Find the revision id of the specified revno."""
2995
2922
        try:
2996
2923
            index = self._partial_revision_history_cache.index(revision_id)
2997
2924
        except ValueError:
2998
 
            try:
2999
 
                self._extend_partial_history(stop_revision=revision_id)
3000
 
            except errors.RevisionNotPresent, e:
3001
 
                raise errors.GhostRevisionsHaveNoRevno(revision_id, e.revision_id)
 
2925
            self._extend_partial_history(stop_revision=revision_id)
3002
2926
            index = len(self._partial_revision_history_cache) - 1
3003
2927
            if self._partial_revision_history_cache[index] != revision_id:
3004
2928
                raise errors.NoSuchRevision(self, revision_id)
3059
2983
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
3060
2984
    """
3061
2985
 
3062
 
    @deprecated_method(deprecated_in((2, 3, 0)))
3063
2986
    def __int__(self):
3064
 
        """Return the relative change in revno.
3065
 
 
3066
 
        :deprecated: Use `new_revno` and `old_revno` instead.
3067
 
        """
 
2987
        # DEPRECATED: pull used to return the change in revno
3068
2988
        return self.new_revno - self.old_revno
3069
2989
 
3070
2990
    def report(self, to_file):
3095
3015
        target, otherwise it will be None.
3096
3016
    """
3097
3017
 
3098
 
    @deprecated_method(deprecated_in((2, 3, 0)))
3099
3018
    def __int__(self):
3100
 
        """Return the relative change in revno.
3101
 
 
3102
 
        :deprecated: Use `new_revno` and `old_revno` instead.
3103
 
        """
 
3019
        # DEPRECATED: push used to return the change in revno
3104
3020
        return self.new_revno - self.old_revno
3105
3021
 
3106
3022
    def report(self, to_file):
3229
3145
    _optimisers = []
3230
3146
    """The available optimised InterBranch types."""
3231
3147
 
3232
 
    @classmethod
3233
 
    def _get_branch_formats_to_test(klass):
3234
 
        """Return an iterable of format tuples for testing.
3235
 
        
3236
 
        :return: An iterable of (from_format, to_format) to use when testing
3237
 
            this InterBranch class. Each InterBranch class should define this
3238
 
            method itself.
3239
 
        """
3240
 
        raise NotImplementedError(klass._get_branch_formats_to_test)
 
3148
    @staticmethod
 
3149
    def _get_branch_formats_to_test():
 
3150
        """Return a tuple with the Branch formats to use when testing."""
 
3151
        raise NotImplementedError(InterBranch._get_branch_formats_to_test)
3241
3152
 
3242
 
    @needs_write_lock
3243
3153
    def pull(self, overwrite=False, stop_revision=None,
3244
3154
             possible_transports=None, local=False):
3245
3155
        """Mirror source into target branch.
3250
3160
        """
3251
3161
        raise NotImplementedError(self.pull)
3252
3162
 
3253
 
    @needs_write_lock
 
3163
    def update_revisions(self, stop_revision=None, overwrite=False,
 
3164
                         graph=None):
 
3165
        """Pull in new perfect-fit revisions.
 
3166
 
 
3167
        :param stop_revision: Updated until the given revision
 
3168
        :param overwrite: Always set the branch pointer, rather than checking
 
3169
            to see if it is a proper descendant.
 
3170
        :param graph: A Graph object that can be used to query history
 
3171
            information. This can be None.
 
3172
        :return: None
 
3173
        """
 
3174
        raise NotImplementedError(self.update_revisions)
 
3175
 
3254
3176
    def push(self, overwrite=False, stop_revision=None,
3255
3177
             _override_hook_source_branch=None):
3256
3178
        """Mirror the source branch into the target branch.
3259
3181
        """
3260
3182
        raise NotImplementedError(self.push)
3261
3183
 
3262
 
    @needs_write_lock
3263
 
    def copy_content_into(self, revision_id=None):
3264
 
        """Copy the content of source into target
3265
 
 
3266
 
        revision_id: if not None, the revision history in the new branch will
3267
 
                     be truncated to end with revision_id.
3268
 
        """
3269
 
        raise NotImplementedError(self.copy_content_into)
3270
 
 
3271
 
    @needs_write_lock
3272
 
    def fetch(self, stop_revision=None):
3273
 
        """Fetch revisions.
3274
 
 
3275
 
        :param stop_revision: Last revision to fetch
3276
 
        """
3277
 
        raise NotImplementedError(self.fetch)
3278
 
 
3279
3184
 
3280
3185
class GenericInterBranch(InterBranch):
3281
 
    """InterBranch implementation that uses public Branch functions."""
3282
 
 
3283
 
    @classmethod
3284
 
    def is_compatible(klass, source, target):
3285
 
        # GenericBranch uses the public API, so always compatible
3286
 
        return True
3287
 
 
3288
 
    @classmethod
3289
 
    def _get_branch_formats_to_test(klass):
3290
 
        return [(format_registry.get_default(), format_registry.get_default())]
3291
 
 
3292
 
    @classmethod
3293
 
    def unwrap_format(klass, format):
3294
 
        if isinstance(format, remote.RemoteBranchFormat):
3295
 
            format._ensure_real()
3296
 
            return format._custom_format
3297
 
        return format
3298
 
 
3299
 
    @needs_write_lock
3300
 
    def copy_content_into(self, revision_id=None):
3301
 
        """Copy the content of source into target
3302
 
 
3303
 
        revision_id: if not None, the revision history in the new branch will
3304
 
                     be truncated to end with revision_id.
3305
 
        """
3306
 
        self.source.update_references(self.target)
3307
 
        self.source._synchronize_history(self.target, revision_id)
3308
 
        try:
3309
 
            parent = self.source.get_parent()
3310
 
        except errors.InaccessibleParent, e:
3311
 
            mutter('parent was not accessible to copy: %s', e)
3312
 
        else:
3313
 
            if parent:
3314
 
                self.target.set_parent(parent)
3315
 
        if self.source._push_should_merge_tags():
3316
 
            self.source.tags.merge_to(self.target.tags)
3317
 
 
3318
 
    @needs_write_lock
3319
 
    def fetch(self, stop_revision=None):
3320
 
        if self.target.base == self.source.base:
3321
 
            return (0, [])
 
3186
    """InterBranch implementation that uses public Branch functions.
 
3187
    """
 
3188
 
 
3189
    @staticmethod
 
3190
    def _get_branch_formats_to_test():
 
3191
        return BranchFormat._default_format, BranchFormat._default_format
 
3192
 
 
3193
    def update_revisions(self, stop_revision=None, overwrite=False,
 
3194
        graph=None):
 
3195
        """See InterBranch.update_revisions()."""
3322
3196
        self.source.lock_read()
3323
3197
        try:
3324
 
            fetch_spec_factory = fetch.FetchSpecFactory()
3325
 
            fetch_spec_factory.source_branch = self.source
3326
 
            fetch_spec_factory.source_branch_stop_revision_id = stop_revision
3327
 
            fetch_spec_factory.source_repo = self.source.repository
3328
 
            fetch_spec_factory.target_repo = self.target.repository
3329
 
            fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
3330
 
            fetch_spec = fetch_spec_factory.make_fetch_spec()
3331
 
            return self.target.repository.fetch(self.source.repository,
3332
 
                fetch_spec=fetch_spec)
 
3198
            other_revno, other_last_revision = self.source.last_revision_info()
 
3199
            stop_revno = None # unknown
 
3200
            if stop_revision is None:
 
3201
                stop_revision = other_last_revision
 
3202
                if _mod_revision.is_null(stop_revision):
 
3203
                    # if there are no commits, we're done.
 
3204
                    return
 
3205
                stop_revno = other_revno
 
3206
 
 
3207
            # what's the current last revision, before we fetch [and change it
 
3208
            # possibly]
 
3209
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
3210
            # we fetch here so that we don't process data twice in the common
 
3211
            # case of having something to pull, and so that the check for
 
3212
            # already merged can operate on the just fetched graph, which will
 
3213
            # be cached in memory.
 
3214
            self.target.fetch(self.source, stop_revision)
 
3215
            # Check to see if one is an ancestor of the other
 
3216
            if not overwrite:
 
3217
                if graph is None:
 
3218
                    graph = self.target.repository.get_graph()
 
3219
                if self.target._check_if_descendant_or_diverged(
 
3220
                        stop_revision, last_rev, graph, self.source):
 
3221
                    # stop_revision is a descendant of last_rev, but we aren't
 
3222
                    # overwriting, so we're done.
 
3223
                    return
 
3224
            if stop_revno is None:
 
3225
                if graph is None:
 
3226
                    graph = self.target.repository.get_graph()
 
3227
                this_revno, this_last_revision = \
 
3228
                        self.target.last_revision_info()
 
3229
                stop_revno = graph.find_distance_to_null(stop_revision,
 
3230
                                [(other_last_revision, other_revno),
 
3231
                                 (this_last_revision, this_revno)])
 
3232
            self.target.set_last_revision_info(stop_revno, stop_revision)
3333
3233
        finally:
3334
3234
            self.source.unlock()
3335
3235
 
3336
 
    @needs_write_lock
3337
 
    def _update_revisions(self, stop_revision=None, overwrite=False,
3338
 
            graph=None):
3339
 
        other_revno, other_last_revision = self.source.last_revision_info()
3340
 
        stop_revno = None # unknown
3341
 
        if stop_revision is None:
3342
 
            stop_revision = other_last_revision
3343
 
            if _mod_revision.is_null(stop_revision):
3344
 
                # if there are no commits, we're done.
3345
 
                return
3346
 
            stop_revno = other_revno
3347
 
 
3348
 
        # what's the current last revision, before we fetch [and change it
3349
 
        # possibly]
3350
 
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
3351
 
        # we fetch here so that we don't process data twice in the common
3352
 
        # case of having something to pull, and so that the check for
3353
 
        # already merged can operate on the just fetched graph, which will
3354
 
        # be cached in memory.
3355
 
        self.fetch(stop_revision=stop_revision)
3356
 
        # Check to see if one is an ancestor of the other
3357
 
        if not overwrite:
3358
 
            if graph is None:
3359
 
                graph = self.target.repository.get_graph()
3360
 
            if self.target._check_if_descendant_or_diverged(
3361
 
                    stop_revision, last_rev, graph, self.source):
3362
 
                # stop_revision is a descendant of last_rev, but we aren't
3363
 
                # overwriting, so we're done.
3364
 
                return
3365
 
        if stop_revno is None:
3366
 
            if graph is None:
3367
 
                graph = self.target.repository.get_graph()
3368
 
            this_revno, this_last_revision = \
3369
 
                    self.target.last_revision_info()
3370
 
            stop_revno = graph.find_distance_to_null(stop_revision,
3371
 
                            [(other_last_revision, other_revno),
3372
 
                             (this_last_revision, this_revno)])
3373
 
        self.target.set_last_revision_info(stop_revno, stop_revision)
3374
 
 
3375
 
    @needs_write_lock
3376
3236
    def pull(self, overwrite=False, stop_revision=None,
3377
 
             possible_transports=None, run_hooks=True,
 
3237
             possible_transports=None, _hook_master=None, run_hooks=True,
3378
3238
             _override_hook_target=None, local=False):
3379
 
        """Pull from source into self, updating my master if any.
 
3239
        """See Branch.pull.
3380
3240
 
 
3241
        :param _hook_master: Private parameter - set the branch to
 
3242
            be supplied as the master to pull hooks.
3381
3243
        :param run_hooks: Private parameter - if false, this branch
3382
3244
            is being called because it's the master of the primary branch,
3383
3245
            so it should not run its hooks.
 
3246
        :param _override_hook_target: Private parameter - set the branch to be
 
3247
            supplied as the target_branch to pull hooks.
 
3248
        :param local: Only update the local branch, and not the bound branch.
3384
3249
        """
3385
 
        bound_location = self.target.get_bound_location()
3386
 
        if local and not bound_location:
 
3250
        # This type of branch can't be bound.
 
3251
        if local:
3387
3252
            raise errors.LocalRequiresBoundBranch()
3388
 
        master_branch = None
3389
 
        source_is_master = (self.source.user_url == bound_location)
3390
 
        if not local and bound_location and not source_is_master:
3391
 
            # not pulling from master, so we need to update master.
3392
 
            master_branch = self.target.get_master_branch(possible_transports)
3393
 
            master_branch.lock_write()
 
3253
        result = PullResult()
 
3254
        result.source_branch = self.source
 
3255
        if _override_hook_target is None:
 
3256
            result.target_branch = self.target
 
3257
        else:
 
3258
            result.target_branch = _override_hook_target
 
3259
        self.source.lock_read()
3394
3260
        try:
3395
 
            if master_branch:
3396
 
                # pull from source into master.
3397
 
                master_branch.pull(self.source, overwrite, stop_revision,
3398
 
                    run_hooks=False)
3399
 
            return self._pull(overwrite,
3400
 
                stop_revision, _hook_master=master_branch,
3401
 
                run_hooks=run_hooks,
3402
 
                _override_hook_target=_override_hook_target,
3403
 
                merge_tags_to_master=not source_is_master)
 
3261
            # We assume that during 'pull' the target repository is closer than
 
3262
            # the source one.
 
3263
            self.source.update_references(self.target)
 
3264
            graph = self.target.repository.get_graph(self.source.repository)
 
3265
            # TODO: Branch formats should have a flag that indicates 
 
3266
            # that revno's are expensive, and pull() should honor that flag.
 
3267
            # -- JRV20090506
 
3268
            result.old_revno, result.old_revid = \
 
3269
                self.target.last_revision_info()
 
3270
            self.target.update_revisions(self.source, stop_revision,
 
3271
                overwrite=overwrite, graph=graph)
 
3272
            # TODO: The old revid should be specified when merging tags, 
 
3273
            # so a tags implementation that versions tags can only 
 
3274
            # pull in the most recent changes. -- JRV20090506
 
3275
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
3276
                overwrite)
 
3277
            result.new_revno, result.new_revid = self.target.last_revision_info()
 
3278
            if _hook_master:
 
3279
                result.master_branch = _hook_master
 
3280
                result.local_branch = result.target_branch
 
3281
            else:
 
3282
                result.master_branch = result.target_branch
 
3283
                result.local_branch = None
 
3284
            if run_hooks:
 
3285
                for hook in Branch.hooks['post_pull']:
 
3286
                    hook(result)
3404
3287
        finally:
3405
 
            if master_branch:
3406
 
                master_branch.unlock()
 
3288
            self.source.unlock()
 
3289
        return result
3407
3290
 
3408
3291
    def push(self, overwrite=False, stop_revision=None,
3409
3292
             _override_hook_source_branch=None):
3427
3310
        finally:
3428
3311
            self.source.unlock()
3429
3312
 
3430
 
    def _basic_push(self, overwrite, stop_revision):
3431
 
        """Basic implementation of push without bound branches or hooks.
3432
 
 
3433
 
        Must be called with source read locked and target write locked.
3434
 
        """
3435
 
        result = BranchPushResult()
3436
 
        result.source_branch = self.source
3437
 
        result.target_branch = self.target
3438
 
        result.old_revno, result.old_revid = self.target.last_revision_info()
3439
 
        self.source.update_references(self.target)
3440
 
        if result.old_revid != stop_revision:
3441
 
            # We assume that during 'push' this repository is closer than
3442
 
            # the target.
3443
 
            graph = self.source.repository.get_graph(self.target.repository)
3444
 
            self._update_revisions(stop_revision, overwrite=overwrite,
3445
 
                    graph=graph)
3446
 
        if self.source._push_should_merge_tags():
3447
 
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3448
 
                overwrite)
3449
 
        result.new_revno, result.new_revid = self.target.last_revision_info()
3450
 
        return result
3451
 
 
3452
3313
    def _push_with_bound_branches(self, overwrite, stop_revision,
3453
3314
            _override_hook_source_branch=None):
3454
3315
        """Push from source into target, and into target's master if any.
3469
3330
            master_branch.lock_write()
3470
3331
            try:
3471
3332
                # push into the master from the source branch.
3472
 
                master_inter = InterBranch.get(self.source, master_branch)
3473
 
                master_inter._basic_push(overwrite, stop_revision)
3474
 
                # and push into the target branch from the source. Note that
3475
 
                # we push from the source branch again, because it's considered
3476
 
                # the highest bandwidth repository.
3477
 
                result = self._basic_push(overwrite, stop_revision)
 
3333
                self.source._basic_push(master_branch, overwrite, stop_revision)
 
3334
                # and push into the target branch from the source. Note that we
 
3335
                # push from the source branch again, because its considered the
 
3336
                # highest bandwidth repository.
 
3337
                result = self.source._basic_push(self.target, overwrite,
 
3338
                    stop_revision)
3478
3339
                result.master_branch = master_branch
3479
3340
                result.local_branch = self.target
3480
3341
                _run_hooks()
3483
3344
                master_branch.unlock()
3484
3345
        else:
3485
3346
            # no master branch
3486
 
            result = self._basic_push(overwrite, stop_revision)
 
3347
            result = self.source._basic_push(self.target, overwrite,
 
3348
                stop_revision)
3487
3349
            # TODO: Why set master_branch and local_branch if there's no
3488
3350
            # binding?  Maybe cleaner to just leave them unset? -- mbp
3489
3351
            # 20070504
3492
3354
            _run_hooks()
3493
3355
            return result
3494
3356
 
3495
 
    def _pull(self, overwrite=False, stop_revision=None,
3496
 
             possible_transports=None, _hook_master=None, run_hooks=True,
3497
 
             _override_hook_target=None, local=False,
3498
 
             merge_tags_to_master=True):
3499
 
        """See Branch.pull.
3500
 
 
3501
 
        This function is the core worker, used by GenericInterBranch.pull to
3502
 
        avoid duplication when pulling source->master and source->local.
3503
 
 
3504
 
        :param _hook_master: Private parameter - set the branch to
3505
 
            be supplied as the master to pull hooks.
 
3357
    @classmethod
 
3358
    def is_compatible(self, source, target):
 
3359
        # GenericBranch uses the public API, so always compatible
 
3360
        return True
 
3361
 
 
3362
 
 
3363
class InterToBranch5(GenericInterBranch):
 
3364
 
 
3365
    @staticmethod
 
3366
    def _get_branch_formats_to_test():
 
3367
        return BranchFormat._default_format, BzrBranchFormat5()
 
3368
 
 
3369
    def pull(self, overwrite=False, stop_revision=None,
 
3370
             possible_transports=None, run_hooks=True,
 
3371
             _override_hook_target=None, local=False):
 
3372
        """Pull from source into self, updating my master if any.
 
3373
 
3506
3374
        :param run_hooks: Private parameter - if false, this branch
3507
3375
            is being called because it's the master of the primary branch,
3508
3376
            so it should not run its hooks.
3509
 
            is being called because it's the master of the primary branch,
3510
 
            so it should not run its hooks.
3511
 
        :param _override_hook_target: Private parameter - set the branch to be
3512
 
            supplied as the target_branch to pull hooks.
3513
 
        :param local: Only update the local branch, and not the bound branch.
3514
3377
        """
3515
 
        # This type of branch can't be bound.
3516
 
        if local:
 
3378
        bound_location = self.target.get_bound_location()
 
3379
        if local and not bound_location:
3517
3380
            raise errors.LocalRequiresBoundBranch()
3518
 
        result = PullResult()
3519
 
        result.source_branch = self.source
3520
 
        if _override_hook_target is None:
3521
 
            result.target_branch = self.target
3522
 
        else:
3523
 
            result.target_branch = _override_hook_target
3524
 
        self.source.lock_read()
 
3381
        master_branch = None
 
3382
        if not local and bound_location and self.source.user_url != bound_location:
 
3383
            # not pulling from master, so we need to update master.
 
3384
            master_branch = self.target.get_master_branch(possible_transports)
 
3385
            master_branch.lock_write()
3525
3386
        try:
3526
 
            # We assume that during 'pull' the target repository is closer than
3527
 
            # the source one.
3528
 
            self.source.update_references(self.target)
3529
 
            graph = self.target.repository.get_graph(self.source.repository)
3530
 
            # TODO: Branch formats should have a flag that indicates 
3531
 
            # that revno's are expensive, and pull() should honor that flag.
3532
 
            # -- JRV20090506
3533
 
            result.old_revno, result.old_revid = \
3534
 
                self.target.last_revision_info()
3535
 
            self._update_revisions(stop_revision, overwrite=overwrite,
3536
 
                graph=graph)
3537
 
            # TODO: The old revid should be specified when merging tags, 
3538
 
            # so a tags implementation that versions tags can only 
3539
 
            # pull in the most recent changes. -- JRV20090506
3540
 
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3541
 
                overwrite, ignore_master=not merge_tags_to_master)
3542
 
            result.new_revno, result.new_revid = self.target.last_revision_info()
3543
 
            if _hook_master:
3544
 
                result.master_branch = _hook_master
3545
 
                result.local_branch = result.target_branch
3546
 
            else:
3547
 
                result.master_branch = result.target_branch
3548
 
                result.local_branch = None
3549
 
            if run_hooks:
3550
 
                for hook in Branch.hooks['post_pull']:
3551
 
                    hook(result)
 
3387
            if master_branch:
 
3388
                # pull from source into master.
 
3389
                master_branch.pull(self.source, overwrite, stop_revision,
 
3390
                    run_hooks=False)
 
3391
            return super(InterToBranch5, self).pull(overwrite,
 
3392
                stop_revision, _hook_master=master_branch,
 
3393
                run_hooks=run_hooks,
 
3394
                _override_hook_target=_override_hook_target)
3552
3395
        finally:
3553
 
            self.source.unlock()
3554
 
        return result
 
3396
            if master_branch:
 
3397
                master_branch.unlock()
3555
3398
 
3556
3399
 
3557
3400
InterBranch.register_optimiser(GenericInterBranch)
 
3401
InterBranch.register_optimiser(InterToBranch5)