~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Robert Collins
  • Date: 2010-05-11 08:36:16 UTC
  • mto: This revision was merged to the branch mainline in revision 5223.
  • Revision ID: robertc@robertcollins.net-20100511083616-b8fjb19zomwupid0
Make all lock methods return Result objects, rather than lock_read returning self, as per John's review.

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
24
24
from bzrlib import (
25
25
        bzrdir,
26
26
        cache_utf8,
27
 
        cleanup,
28
27
        config as _mod_config,
29
28
        debug,
30
29
        errors,
31
 
        fetch,
32
 
        graph as _mod_graph,
33
30
        lockdir,
34
31
        lockable_files,
35
 
        remote,
36
32
        repository,
37
33
        revision as _mod_revision,
38
34
        rio,
 
35
        symbol_versioning,
39
36
        transport,
 
37
        tsort,
40
38
        ui,
41
39
        urlutils,
42
40
        )
43
41
from bzrlib.config import BranchConfig, TransportConfig
 
42
from bzrlib.repofmt.pack_repo import RepositoryFormatKnitPack5RichRoot
44
43
from bzrlib.tag import (
45
44
    BasicTags,
46
45
    DisabledTags,
47
46
    )
48
47
""")
49
48
 
50
 
from bzrlib import (
51
 
    controldir,
52
 
    )
53
 
from bzrlib.decorators import (
54
 
    needs_read_lock,
55
 
    needs_write_lock,
56
 
    only_raises,
57
 
    )
58
 
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
59
51
from bzrlib.inter import InterObject
60
52
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
61
53
from bzrlib import registry
71
63
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
72
64
 
73
65
 
74
 
class Branch(controldir.ControlComponent):
 
66
class Branch(bzrdir.ControlComponent):
75
67
    """Branch holding a history of revisions.
76
68
 
77
69
    :ivar base:
78
70
        Base directory/url of the branch; using control_url and
79
71
        control_transport is more standardized.
80
 
    :ivar hooks: An instance of BranchHooks.
81
 
    :ivar _master_branch_cache: cached result of get_master_branch, see
82
 
        _clear_cached_state.
 
72
 
 
73
    hooks: An instance of BranchHooks.
83
74
    """
84
75
    # this is really an instance variable - FIXME move it there
85
76
    # - RBC 20060112
99
90
        self._revision_id_to_revno_cache = None
100
91
        self._partial_revision_id_to_revno_cache = {}
101
92
        self._partial_revision_history_cache = []
102
 
        self._tags_bytes = None
103
93
        self._last_revision_info_cache = None
104
 
        self._master_branch_cache = None
105
94
        self._merge_sorted_revisions_cache = None
106
95
        self._open_hook()
107
96
        hooks = Branch.hooks['open']
113
102
 
114
103
    def _activate_fallback_location(self, url):
115
104
        """Activate the branch/repository from url as a fallback repository."""
116
 
        for existing_fallback_repo in self.repository._fallback_repositories:
117
 
            if existing_fallback_repo.user_url == url:
118
 
                # This fallback is already configured.  This probably only
119
 
                # happens because BzrDir.sprout is a horrible mess.  To avoid
120
 
                # confusing _unstack we don't add this a second time.
121
 
                mutter('duplicate activation of fallback %r on %r', url, self)
122
 
                return
123
105
        repo = self._get_fallback_repository(url)
124
106
        if repo.has_same_location(self.repository):
125
107
            raise errors.UnstackableLocationError(self.user_url, url)
215
197
        return self.supports_tags() and self.tags.get_tag_dict()
216
198
 
217
199
    def get_config(self):
218
 
        """Get a bzrlib.config.BranchConfig for this Branch.
219
 
 
220
 
        This can then be used to get and set configuration options for the
221
 
        branch.
222
 
 
223
 
        :return: A bzrlib.config.BranchConfig.
224
 
        """
225
200
        return BranchConfig(self)
226
201
 
227
202
    def _get_config(self):
243
218
            possible_transports=[self.bzrdir.root_transport])
244
219
        return a_branch.repository
245
220
 
246
 
    @needs_read_lock
247
221
    def _get_tags_bytes(self):
248
222
        """Get the bytes of a serialised tags dict.
249
223
 
256
230
        :return: The bytes of the tags file.
257
231
        :seealso: Branch._set_tags_bytes.
258
232
        """
259
 
        if self._tags_bytes is None:
260
 
            self._tags_bytes = self._transport.get_bytes('tags')
261
 
        return self._tags_bytes
 
233
        return self._transport.get_bytes('tags')
262
234
 
263
235
    def _get_nick(self, local=False, possible_transports=None):
264
236
        config = self.get_config()
266
238
        if not local and not config.has_explicit_nickname():
267
239
            try:
268
240
                master = self.get_master_branch(possible_transports)
269
 
                if master and self.user_url == master.user_url:
270
 
                    raise errors.RecursiveBind(self.user_url)
271
241
                if master is not None:
272
242
                    # return the master branch value
273
243
                    return master.nick
274
 
            except errors.RecursiveBind, e:
275
 
                raise e
276
244
            except errors.BzrError, e:
277
245
                # Silently fall back to local implicit nick if the master is
278
246
                # unavailable
455
423
            after. If None, the rest of history is included.
456
424
        :param stop_rule: if stop_revision_id is not None, the precise rule
457
425
            to use for termination:
458
 
 
459
426
            * 'exclude' - leave the stop revision out of the result (default)
460
427
            * 'include' - the stop revision is the last item in the result
461
428
            * 'with-merges' - include the stop revision and all of its
463
430
            * 'with-merges-without-common-ancestry' - filter out revisions 
464
431
              that are in both ancestries
465
432
        :param direction: either 'reverse' or 'forward':
466
 
 
467
433
            * reverse means return the start_revision_id first, i.e.
468
434
              start at the most recent revision and go backwards in history
469
435
            * forward returns tuples in the opposite order to reverse.
513
479
        rev_iter = iter(merge_sorted_revisions)
514
480
        if start_revision_id is not None:
515
481
            for node in rev_iter:
516
 
                rev_id = node.key
 
482
                rev_id = node.key[-1]
517
483
                if rev_id != start_revision_id:
518
484
                    continue
519
485
                else:
525
491
        if stop_revision_id is None:
526
492
            # Yield everything
527
493
            for node in rev_iter:
528
 
                rev_id = node.key
 
494
                rev_id = node.key[-1]
529
495
                yield (rev_id, node.merge_depth, node.revno,
530
496
                       node.end_of_merge)
531
497
        elif stop_rule == 'exclude':
532
498
            for node in rev_iter:
533
 
                rev_id = node.key
 
499
                rev_id = node.key[-1]
534
500
                if rev_id == stop_revision_id:
535
501
                    return
536
502
                yield (rev_id, node.merge_depth, node.revno,
537
503
                       node.end_of_merge)
538
504
        elif stop_rule == 'include':
539
505
            for node in rev_iter:
540
 
                rev_id = node.key
 
506
                rev_id = node.key[-1]
541
507
                yield (rev_id, node.merge_depth, node.revno,
542
508
                       node.end_of_merge)
543
509
                if rev_id == stop_revision_id:
549
515
            ancestors = graph.find_unique_ancestors(start_revision_id,
550
516
                                                    [stop_revision_id])
551
517
            for node in rev_iter:
552
 
                rev_id = node.key
 
518
                rev_id = node.key[-1]
553
519
                if rev_id not in ancestors:
554
520
                    continue
555
521
                yield (rev_id, node.merge_depth, node.revno,
565
531
            reached_stop_revision_id = False
566
532
            revision_id_whitelist = []
567
533
            for node in rev_iter:
568
 
                rev_id = node.key
 
534
                rev_id = node.key[-1]
569
535
                if rev_id == left_parent:
570
536
                    # reached the left parent after the stop_revision
571
537
                    return
670
636
        raise errors.UnsupportedOperation(self.get_reference_info, self)
671
637
 
672
638
    @needs_write_lock
673
 
    def fetch(self, from_branch, last_revision=None, limit=None):
 
639
    def fetch(self, from_branch, last_revision=None, pb=None):
674
640
        """Copy revisions from from_branch into this branch.
675
641
 
676
642
        :param from_branch: Where to copy from.
677
643
        :param last_revision: What revision to stop at (None for at the end
678
644
                              of the branch.
679
 
        :param limit: Optional rough limit of revisions to fetch
 
645
        :param pb: An optional progress bar to use.
680
646
        :return: None
681
647
        """
682
 
        return InterBranch.get(from_branch, self).fetch(last_revision, limit=limit)
 
648
        if self.base == from_branch.base:
 
649
            return (0, [])
 
650
        if pb is not None:
 
651
            symbol_versioning.warn(
 
652
                symbol_versioning.deprecated_in((1, 14, 0))
 
653
                % "pb parameter to fetch()")
 
654
        from_branch.lock_read()
 
655
        try:
 
656
            if last_revision is None:
 
657
                last_revision = from_branch.last_revision()
 
658
                last_revision = _mod_revision.ensure_null(last_revision)
 
659
            return self.repository.fetch(from_branch.repository,
 
660
                                         revision_id=last_revision,
 
661
                                         pb=pb)
 
662
        finally:
 
663
            from_branch.unlock()
683
664
 
684
665
    def get_bound_location(self):
685
666
        """Return the URL of the branch we are bound to.
696
677
 
697
678
    def get_commit_builder(self, parents, config=None, timestamp=None,
698
679
                           timezone=None, committer=None, revprops=None,
699
 
                           revision_id=None, lossy=False):
 
680
                           revision_id=None):
700
681
        """Obtain a CommitBuilder for this branch.
701
682
 
702
683
        :param parents: Revision ids of the parents of the new revision.
706
687
        :param committer: Optional committer to set for commit.
707
688
        :param revprops: Optional dictionary of revision properties.
708
689
        :param revision_id: Optional revision id.
709
 
        :param lossy: Whether to discard data that can not be natively
710
 
            represented, when pushing to a foreign VCS 
711
690
        """
712
691
 
713
692
        if config is None:
714
693
            config = self.get_config()
715
694
 
716
695
        return self.repository.get_commit_builder(self, parents, config,
717
 
            timestamp, timezone, committer, revprops, revision_id,
718
 
            lossy)
 
696
            timestamp, timezone, committer, revprops, revision_id)
719
697
 
720
698
    def get_master_branch(self, possible_transports=None):
721
699
        """Return the branch we are bound to.
748
726
        """Print `file` to stdout."""
749
727
        raise NotImplementedError(self.print_file)
750
728
 
751
 
    @deprecated_method(deprecated_in((2, 4, 0)))
752
729
    def set_revision_history(self, rev_history):
753
 
        """See Branch.set_revision_history."""
754
 
        self._set_revision_history(rev_history)
755
 
 
756
 
    @needs_write_lock
757
 
    def _set_revision_history(self, rev_history):
758
 
        if len(rev_history) == 0:
759
 
            revid = _mod_revision.NULL_REVISION
760
 
        else:
761
 
            revid = rev_history[-1]
762
 
        if rev_history != self._lefthand_history(revid):
763
 
            raise errors.NotLefthandHistory(rev_history)
764
 
        self.set_last_revision_info(len(rev_history), revid)
765
 
        self._cache_revision_history(rev_history)
766
 
        for hook in Branch.hooks['set_rh']:
767
 
            hook(self, rev_history)
768
 
 
769
 
    @needs_write_lock
770
 
    def set_last_revision_info(self, revno, revision_id):
771
 
        """Set the last revision of this branch.
772
 
 
773
 
        The caller is responsible for checking that the revno is correct
774
 
        for this revision id.
775
 
 
776
 
        It may be possible to set the branch last revision to an id not
777
 
        present in the repository.  However, branches can also be
778
 
        configured to check constraints on history, in which case this may not
779
 
        be permitted.
780
 
        """
781
 
        raise NotImplementedError(self.set_last_revision_info)
782
 
 
783
 
    @needs_write_lock
784
 
    def generate_revision_history(self, revision_id, last_rev=None,
785
 
                                  other_branch=None):
786
 
        """See Branch.generate_revision_history"""
787
 
        graph = self.repository.get_graph()
788
 
        known_revision_ids = [
789
 
            self.last_revision_info(),
790
 
            (_mod_revision.NULL_REVISION, 0),
791
 
            ]
792
 
        if last_rev is not None:
793
 
            if not graph.is_ancestor(last_rev, revision_id):
794
 
                # our previous tip is not merged into stop_revision
795
 
                raise errors.DivergedBranches(self, other_branch)
796
 
        revno = graph.find_distance_to_null(revision_id, known_revision_ids)
797
 
        self.set_last_revision_info(revno, revision_id)
 
730
        raise NotImplementedError(self.set_revision_history)
798
731
 
799
732
    @needs_write_lock
800
733
    def set_parent(self, url):
844
777
 
845
778
    def _unstack(self):
846
779
        """Change a branch to be unstacked, copying data as needed.
847
 
 
 
780
        
848
781
        Don't call this directly, use set_stacked_on_url(None).
849
782
        """
850
783
        pb = ui.ui_factory.nested_progress_bar()
859
792
            old_repository = self.repository
860
793
            if len(old_repository._fallback_repositories) != 1:
861
794
                raise AssertionError("can't cope with fallback repositories "
862
 
                    "of %r (fallbacks: %r)" % (old_repository,
863
 
                        old_repository._fallback_repositories))
864
 
            # Open the new repository object.
865
 
            # Repositories don't offer an interface to remove fallback
866
 
            # repositories today; take the conceptually simpler option and just
867
 
            # reopen it.  We reopen it starting from the URL so that we
868
 
            # get a separate connection for RemoteRepositories and can
869
 
            # stream from one of them to the other.  This does mean doing
870
 
            # separate SSH connection setup, but unstacking is not a
871
 
            # common operation so it's tolerable.
872
 
            new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
873
 
            new_repository = new_bzrdir.find_repository()
874
 
            if new_repository._fallback_repositories:
875
 
                raise AssertionError("didn't expect %r to have "
876
 
                    "fallback_repositories"
877
 
                    % (self.repository,))
878
 
            # Replace self.repository with the new repository.
879
 
            # Do our best to transfer the lock state (i.e. lock-tokens and
880
 
            # lock count) of self.repository to the new repository.
881
 
            lock_token = old_repository.lock_write().repository_token
882
 
            self.repository = new_repository
883
 
            if isinstance(self, remote.RemoteBranch):
884
 
                # Remote branches can have a second reference to the old
885
 
                # repository that need to be replaced.
886
 
                if self._real_branch is not None:
887
 
                    self._real_branch.repository = new_repository
888
 
            self.repository.lock_write(token=lock_token)
889
 
            if lock_token is not None:
890
 
                old_repository.leave_lock_in_place()
 
795
                    "of %r" % (self.repository,))
 
796
            # unlock it, including unlocking the fallback
891
797
            old_repository.unlock()
892
 
            if lock_token is not None:
893
 
                # XXX: self.repository.leave_lock_in_place() before this
894
 
                # function will not be preserved.  Fortunately that doesn't
895
 
                # affect the current default format (2a), and would be a
896
 
                # corner-case anyway.
897
 
                #  - Andrew Bennetts, 2010/06/30
898
 
                self.repository.dont_leave_lock_in_place()
899
 
            old_lock_count = 0
900
 
            while True:
901
 
                try:
902
 
                    old_repository.unlock()
903
 
                except errors.LockNotHeld:
904
 
                    break
905
 
                old_lock_count += 1
906
 
            if old_lock_count == 0:
907
 
                raise AssertionError(
908
 
                    'old_repository should have been locked at least once.')
909
 
            for i in range(old_lock_count-1):
 
798
            old_repository.lock_read()
 
799
            try:
 
800
                # Repositories don't offer an interface to remove fallback
 
801
                # repositories today; take the conceptually simpler option and just
 
802
                # reopen it.  We reopen it starting from the URL so that we
 
803
                # get a separate connection for RemoteRepositories and can
 
804
                # stream from one of them to the other.  This does mean doing
 
805
                # separate SSH connection setup, but unstacking is not a
 
806
                # common operation so it's tolerable.
 
807
                new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
 
808
                new_repository = new_bzrdir.find_repository()
 
809
                self.repository = new_repository
 
810
                if self.repository._fallback_repositories:
 
811
                    raise AssertionError("didn't expect %r to have "
 
812
                        "fallback_repositories"
 
813
                        % (self.repository,))
 
814
                # this is not paired with an unlock because it's just restoring
 
815
                # the previous state; the lock's released when set_stacked_on_url
 
816
                # returns
910
817
                self.repository.lock_write()
911
 
            # Fetch from the old repository into the new.
912
 
            old_repository.lock_read()
913
 
            try:
914
818
                # XXX: If you unstack a branch while it has a working tree
915
819
                # with a pending merge, the pending-merged revisions will no
916
820
                # longer be present.  You can (probably) revert and remerge.
917
 
                try:
918
 
                    tags_to_fetch = set(self.tags.get_reverse_tag_dict())
919
 
                except errors.TagsNotSupported:
920
 
                    tags_to_fetch = set()
921
 
                fetch_spec = _mod_graph.NotInOtherForRevs(self.repository,
922
 
                    old_repository, required_ids=[self.last_revision()],
923
 
                    if_present_ids=tags_to_fetch, find_ghosts=True).execute()
924
 
                self.repository.fetch(old_repository, fetch_spec=fetch_spec)
 
821
                #
 
822
                # XXX: This only fetches up to the tip of the repository; it
 
823
                # doesn't bring across any tags.  That's fairly consistent
 
824
                # with how branch works, but perhaps not ideal.
 
825
                self.repository.fetch(old_repository,
 
826
                    revision_id=self.last_revision(),
 
827
                    find_ghosts=True)
925
828
            finally:
926
829
                old_repository.unlock()
927
830
        finally:
932
835
 
933
836
        :seealso: Branch._get_tags_bytes.
934
837
        """
935
 
        op = cleanup.OperationWithCleanups(self._set_tags_bytes_locked)
936
 
        op.add_cleanup(self.lock_write().unlock)
937
 
        return op.run_simple(bytes)
938
 
 
939
 
    def _set_tags_bytes_locked(self, bytes):
940
 
        self._tags_bytes = bytes
941
 
        return self._transport.put_bytes('tags', bytes)
 
838
        return _run_with_write_locked_target(self, self._transport.put_bytes,
 
839
            'tags', bytes)
942
840
 
943
841
    def _cache_revision_history(self, rev_history):
944
842
        """Set the cached revision history to rev_history.
971
869
        self._revision_history_cache = None
972
870
        self._revision_id_to_revno_cache = None
973
871
        self._last_revision_info_cache = None
974
 
        self._master_branch_cache = None
975
872
        self._merge_sorted_revisions_cache = None
976
873
        self._partial_revision_history_cache = []
977
874
        self._partial_revision_id_to_revno_cache = {}
978
 
        self._tags_bytes = None
979
875
 
980
876
    def _gen_revision_history(self):
981
877
        """Return sequence of revision hashes on to this branch.
1031
927
        :return: A tuple (revno, revision_id).
1032
928
        """
1033
929
        if self._last_revision_info_cache is None:
1034
 
            self._last_revision_info_cache = self._read_last_revision_info()
 
930
            self._last_revision_info_cache = self._last_revision_info()
1035
931
        return self._last_revision_info_cache
1036
932
 
1037
 
    def _read_last_revision_info(self):
1038
 
        raise NotImplementedError(self._read_last_revision_info)
1039
 
 
1040
 
    @deprecated_method(deprecated_in((2, 4, 0)))
 
933
    def _last_revision_info(self):
 
934
        rh = self.revision_history()
 
935
        revno = len(rh)
 
936
        if revno:
 
937
            return (revno, rh[-1])
 
938
        else:
 
939
            return (0, _mod_revision.NULL_REVISION)
 
940
 
 
941
    @deprecated_method(deprecated_in((1, 6, 0)))
 
942
    def missing_revisions(self, other, stop_revision=None):
 
943
        """Return a list of new revisions that would perfectly fit.
 
944
 
 
945
        If self and other have not diverged, return a list of the revisions
 
946
        present in other, but missing from self.
 
947
        """
 
948
        self_history = self.revision_history()
 
949
        self_len = len(self_history)
 
950
        other_history = other.revision_history()
 
951
        other_len = len(other_history)
 
952
        common_index = min(self_len, other_len) -1
 
953
        if common_index >= 0 and \
 
954
            self_history[common_index] != other_history[common_index]:
 
955
            raise errors.DivergedBranches(self, other)
 
956
 
 
957
        if stop_revision is None:
 
958
            stop_revision = other_len
 
959
        else:
 
960
            if stop_revision > other_len:
 
961
                raise errors.NoSuchRevision(self, stop_revision)
 
962
        return other_history[self_len:stop_revision]
 
963
 
 
964
    @needs_write_lock
 
965
    def update_revisions(self, other, stop_revision=None, overwrite=False,
 
966
                         graph=None):
 
967
        """Pull in new perfect-fit revisions.
 
968
 
 
969
        :param other: Another Branch to pull from
 
970
        :param stop_revision: Updated until the given revision
 
971
        :param overwrite: Always set the branch pointer, rather than checking
 
972
            to see if it is a proper descendant.
 
973
        :param graph: A Graph object that can be used to query history
 
974
            information. This can be None.
 
975
        :return: None
 
976
        """
 
977
        return InterBranch.get(other, self).update_revisions(stop_revision,
 
978
            overwrite, graph)
 
979
 
1041
980
    def import_last_revision_info(self, source_repo, revno, revid):
1042
981
        """Set the last revision info, importing from another repo if necessary.
1043
982
 
 
983
        This is used by the bound branch code to upload a revision to
 
984
        the master branch first before updating the tip of the local branch.
 
985
 
1044
986
        :param source_repo: Source repository to optionally fetch from
1045
987
        :param revno: Revision number of the new tip
1046
988
        :param revid: Revision id of the new tip
1049
991
            self.repository.fetch(source_repo, revision_id=revid)
1050
992
        self.set_last_revision_info(revno, revid)
1051
993
 
1052
 
    def import_last_revision_info_and_tags(self, source, revno, revid,
1053
 
                                           lossy=False):
1054
 
        """Set the last revision info, importing from another repo if necessary.
1055
 
 
1056
 
        This is used by the bound branch code to upload a revision to
1057
 
        the master branch first before updating the tip of the local branch.
1058
 
        Revisions referenced by source's tags are also transferred.
1059
 
 
1060
 
        :param source: Source branch to optionally fetch from
1061
 
        :param revno: Revision number of the new tip
1062
 
        :param revid: Revision id of the new tip
1063
 
        :param lossy: Whether to discard metadata that can not be
1064
 
            natively represented
1065
 
        :return: Tuple with the new revision number and revision id
1066
 
            (should only be different from the arguments when lossy=True)
1067
 
        """
1068
 
        if not self.repository.has_same_location(source.repository):
1069
 
            self.fetch(source, revid)
1070
 
        self.set_last_revision_info(revno, revid)
1071
 
        return (revno, revid)
1072
 
 
1073
994
    def revision_id_to_revno(self, revision_id):
1074
995
        """Given a revision id, return its revno"""
1075
996
        if _mod_revision.is_null(revision_id):
1095
1016
            self._extend_partial_history(distance_from_last)
1096
1017
        return self._partial_revision_history_cache[distance_from_last]
1097
1018
 
 
1019
    @needs_write_lock
1098
1020
    def pull(self, source, overwrite=False, stop_revision=None,
1099
1021
             possible_transports=None, *args, **kwargs):
1100
1022
        """Mirror source into this branch.
1107
1029
            stop_revision=stop_revision,
1108
1030
            possible_transports=possible_transports, *args, **kwargs)
1109
1031
 
1110
 
    def push(self, target, overwrite=False, stop_revision=None, lossy=False,
1111
 
            *args, **kwargs):
 
1032
    def push(self, target, overwrite=False, stop_revision=None, *args,
 
1033
        **kwargs):
1112
1034
        """Mirror this branch into target.
1113
1035
 
1114
1036
        This branch is considered to be 'local', having low latency.
1115
1037
        """
1116
1038
        return InterBranch.get(self, target).push(overwrite, stop_revision,
1117
 
            lossy, *args, **kwargs)
 
1039
            *args, **kwargs)
 
1040
 
 
1041
    def lossy_push(self, target, stop_revision=None):
 
1042
        """Push deltas into another branch.
 
1043
 
 
1044
        :note: This does not, like push, retain the revision ids from 
 
1045
            the source branch and will, rather than adding bzr-specific 
 
1046
            metadata, push only those semantics of the revision that can be 
 
1047
            natively represented by this branch' VCS.
 
1048
 
 
1049
        :param target: Target branch
 
1050
        :param stop_revision: Revision to push, defaults to last revision.
 
1051
        :return: BranchPushResult with an extra member revidmap: 
 
1052
            A dictionary mapping revision ids from the target branch 
 
1053
            to new revision ids in the target branch, for each 
 
1054
            revision that was pushed.
 
1055
        """
 
1056
        inter = InterBranch.get(self, target)
 
1057
        lossy_push = getattr(inter, "lossy_push", None)
 
1058
        if lossy_push is None:
 
1059
            raise errors.LossyPushToSameVCS(self, target)
 
1060
        return lossy_push(stop_revision)
1118
1061
 
1119
1062
    def basis_tree(self):
1120
1063
        """Return `Tree` object for last revision."""
1275
1218
        return result
1276
1219
 
1277
1220
    @needs_read_lock
1278
 
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None,
1279
 
            repository=None):
 
1221
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None):
1280
1222
        """Create a new line of development from the branch, into to_bzrdir.
1281
1223
 
1282
1224
        to_bzrdir controls the branch format.
1287
1229
        if (repository_policy is not None and
1288
1230
            repository_policy.requires_stacking()):
1289
1231
            to_bzrdir._format.require_stacking(_skip_repo=True)
1290
 
        result = to_bzrdir.create_branch(repository=repository)
 
1232
        result = to_bzrdir.create_branch()
1291
1233
        result.lock_write()
1292
1234
        try:
1293
1235
            if repository_policy is not None:
1294
1236
                repository_policy.configure_branch(result)
1295
1237
            self.copy_content_into(result, revision_id=revision_id)
1296
 
            master_branch = self.get_master_branch()
1297
 
            if master_branch is None:
1298
 
                result.set_parent(self.bzrdir.root_transport.base)
1299
 
            else:
1300
 
                result.set_parent(master_branch.bzrdir.root_transport.base)
 
1238
            result.set_parent(self.bzrdir.root_transport.base)
1301
1239
        finally:
1302
1240
            result.unlock()
1303
1241
        return result
1327
1265
                revno = 1
1328
1266
        destination.set_last_revision_info(revno, revision_id)
1329
1267
 
 
1268
    @needs_read_lock
1330
1269
    def copy_content_into(self, destination, revision_id=None):
1331
1270
        """Copy the content of self into destination.
1332
1271
 
1333
1272
        revision_id: if not None, the revision history in the new branch will
1334
1273
                     be truncated to end with revision_id.
1335
1274
        """
1336
 
        return InterBranch.get(self, destination).copy_content_into(
1337
 
            revision_id=revision_id)
 
1275
        self.update_references(destination)
 
1276
        self._synchronize_history(destination, revision_id)
 
1277
        try:
 
1278
            parent = self.get_parent()
 
1279
        except errors.InaccessibleParent, e:
 
1280
            mutter('parent was not accessible to copy: %s', e)
 
1281
        else:
 
1282
            if parent:
 
1283
                destination.set_parent(parent)
 
1284
        if self._push_should_merge_tags():
 
1285
            self.tags.merge_to(destination.tags)
1338
1286
 
1339
1287
    def update_references(self, target):
1340
1288
        if not getattr(self._format, 'supports_reference_locations', False):
1385
1333
        """Return the most suitable metadir for a checkout of this branch.
1386
1334
        Weaves are used if this branch's repository uses weaves.
1387
1335
        """
1388
 
        format = self.repository.bzrdir.checkout_metadir()
1389
 
        format.set_branch_format(self._format)
 
1336
        if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
 
1337
            from bzrlib.repofmt import weaverepo
 
1338
            format = bzrdir.BzrDirMetaFormat1()
 
1339
            format.repository_format = weaverepo.RepositoryFormat7()
 
1340
        else:
 
1341
            format = self.repository.bzrdir.checkout_metadir()
 
1342
            format.set_branch_format(self._format)
1390
1343
        return format
1391
1344
 
1392
1345
    def create_clone_on_transport(self, to_transport, revision_id=None,
1393
 
        stacked_on=None, create_prefix=False, use_existing_dir=False,
1394
 
        no_tree=None):
 
1346
        stacked_on=None, create_prefix=False, use_existing_dir=False):
1395
1347
        """Create a clone of this branch and its bzrdir.
1396
1348
 
1397
1349
        :param to_transport: The transport to clone onto.
1404
1356
        """
1405
1357
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1406
1358
        # clone call. Or something. 20090224 RBC/spiv.
1407
 
        # XXX: Should this perhaps clone colocated branches as well, 
1408
 
        # rather than just the default branch? 20100319 JRV
1409
1359
        if revision_id is None:
1410
1360
            revision_id = self.last_revision()
1411
1361
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1412
1362
            revision_id=revision_id, stacked_on=stacked_on,
1413
 
            create_prefix=create_prefix, use_existing_dir=use_existing_dir,
1414
 
            no_tree=no_tree)
 
1363
            create_prefix=create_prefix, use_existing_dir=use_existing_dir)
1415
1364
        return dir_to.open_branch()
1416
1365
 
1417
1366
    def create_checkout(self, to_location, revision_id=None,
1422
1371
        :param to_location: The url to produce the checkout at
1423
1372
        :param revision_id: The revision to check out
1424
1373
        :param lightweight: If True, produce a lightweight checkout, otherwise,
1425
 
            produce a bound branch (heavyweight checkout)
 
1374
        produce a bound branch (heavyweight checkout)
1426
1375
        :param accelerator_tree: A tree which can be used for retrieving file
1427
1376
            contents more quickly than the revision tree, i.e. a workingtree.
1428
1377
            The revision tree will be used for cases where accelerator_tree's
1474
1423
 
1475
1424
    def reference_parent(self, file_id, path, possible_transports=None):
1476
1425
        """Return the parent branch for a tree-reference file_id
1477
 
 
1478
1426
        :param file_id: The file_id of the tree reference
1479
1427
        :param path: The path of the file_id in the tree
1480
1428
        :return: A branch associated with the file_id
1533
1481
        else:
1534
1482
            raise AssertionError("invalid heads: %r" % (heads,))
1535
1483
 
1536
 
    def heads_to_fetch(self):
1537
 
        """Return the heads that must and that should be fetched to copy this
1538
 
        branch into another repo.
1539
 
 
1540
 
        :returns: a 2-tuple of (must_fetch, if_present_fetch).  must_fetch is a
1541
 
            set of heads that must be fetched.  if_present_fetch is a set of
1542
 
            heads that must be fetched if present, but no error is necessary if
1543
 
            they are not present.
1544
 
        """
1545
 
        # For bzr native formats must_fetch is just the tip, and if_present_fetch
1546
 
        # are the tags.
1547
 
        must_fetch = set([self.last_revision()])
1548
 
        try:
1549
 
            if_present_fetch = set(self.tags.get_reverse_tag_dict())
1550
 
        except errors.TagsNotSupported:
1551
 
            if_present_fetch = set()
1552
 
        must_fetch.discard(_mod_revision.NULL_REVISION)
1553
 
        if_present_fetch.discard(_mod_revision.NULL_REVISION)
1554
 
        return must_fetch, if_present_fetch
1555
 
 
1556
 
 
1557
 
class BranchFormat(controldir.ControlComponentFormat):
 
1484
 
 
1485
class BranchFormat(object):
1558
1486
    """An encapsulation of the initialization and open routines for a format.
1559
1487
 
1560
1488
    Formats provide three things:
1563
1491
     * an open routine.
1564
1492
 
1565
1493
    Formats are placed in an dict by their format string for reference
1566
 
    during branch opening. It's not required that these be instances, they
 
1494
    during branch opening. Its not required that these be instances, they
1567
1495
    can be classes themselves with class methods - it simply depends on
1568
1496
    whether state is needed for a given format or not.
1569
1497
 
1572
1500
    object will be created every time regardless.
1573
1501
    """
1574
1502
 
 
1503
    _default_format = None
 
1504
    """The default format used for new branches."""
 
1505
 
 
1506
    _formats = {}
 
1507
    """The known formats."""
 
1508
 
1575
1509
    can_set_append_revisions_only = True
1576
1510
 
1577
1511
    def __eq__(self, other):
1586
1520
        try:
1587
1521
            transport = a_bzrdir.get_branch_transport(None, name=name)
1588
1522
            format_string = transport.get_bytes("format")
1589
 
            return format_registry.get(format_string)
 
1523
            return klass._formats[format_string]
1590
1524
        except errors.NoSuchFile:
1591
1525
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1592
1526
        except KeyError:
1593
1527
            raise errors.UnknownFormatError(format=format_string, kind='branch')
1594
1528
 
1595
1529
    @classmethod
1596
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1597
1530
    def get_default_format(klass):
1598
1531
        """Return the current default format."""
1599
 
        return format_registry.get_default()
1600
 
 
1601
 
    @classmethod
1602
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1603
 
    def get_formats(klass):
1604
 
        """Get all the known formats.
1605
 
 
1606
 
        Warning: This triggers a load of all lazy registered formats: do not
1607
 
        use except when that is desireed.
1608
 
        """
1609
 
        return format_registry._get_all()
1610
 
 
1611
 
    def get_reference(self, a_bzrdir, name=None):
 
1532
        return klass._default_format
 
1533
 
 
1534
    def get_reference(self, a_bzrdir):
1612
1535
        """Get the target reference of the branch in a_bzrdir.
1613
1536
 
1614
1537
        format probing must have been completed before calling
1616
1539
        in a_bzrdir is correct.
1617
1540
 
1618
1541
        :param a_bzrdir: The bzrdir to get the branch data from.
1619
 
        :param name: Name of the colocated branch to fetch
1620
1542
        :return: None if the branch is not a reference branch.
1621
1543
        """
1622
1544
        return None
1623
1545
 
1624
1546
    @classmethod
1625
 
    def set_reference(self, a_bzrdir, name, to_branch):
 
1547
    def set_reference(self, a_bzrdir, to_branch):
1626
1548
        """Set the target reference of the branch in a_bzrdir.
1627
1549
 
1628
1550
        format probing must have been completed before calling
1630
1552
        in a_bzrdir is correct.
1631
1553
 
1632
1554
        :param a_bzrdir: The bzrdir to set the branch reference for.
1633
 
        :param name: Name of colocated branch to set, None for default
1634
1555
        :param to_branch: branch that the checkout is to reference
1635
1556
        """
1636
1557
        raise NotImplementedError(self.set_reference)
1651
1572
        for hook in hooks:
1652
1573
            hook(params)
1653
1574
 
1654
 
    def initialize(self, a_bzrdir, name=None, repository=None):
 
1575
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
 
1576
                           lock_type='metadir', set_format=True):
 
1577
        """Initialize a branch in a bzrdir, with specified files
 
1578
 
 
1579
        :param a_bzrdir: The bzrdir to initialize the branch in
 
1580
        :param utf8_files: The files to create as a list of
 
1581
            (filename, content) tuples
 
1582
        :param name: Name of colocated branch to create, if any
 
1583
        :param set_format: If True, set the format with
 
1584
            self.get_format_string.  (BzrBranch4 has its format set
 
1585
            elsewhere)
 
1586
        :return: a branch in this format
 
1587
        """
 
1588
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
 
1589
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
1590
        lock_map = {
 
1591
            'metadir': ('lock', lockdir.LockDir),
 
1592
            'branch4': ('branch-lock', lockable_files.TransportLock),
 
1593
        }
 
1594
        lock_name, lock_class = lock_map[lock_type]
 
1595
        control_files = lockable_files.LockableFiles(branch_transport,
 
1596
            lock_name, lock_class)
 
1597
        control_files.create_lock()
 
1598
        try:
 
1599
            control_files.lock_write()
 
1600
        except errors.LockContention:
 
1601
            if lock_type != 'branch4':
 
1602
                raise
 
1603
            lock_taken = False
 
1604
        else:
 
1605
            lock_taken = True
 
1606
        if set_format:
 
1607
            utf8_files += [('format', self.get_format_string())]
 
1608
        try:
 
1609
            for (filename, content) in utf8_files:
 
1610
                branch_transport.put_bytes(
 
1611
                    filename, content,
 
1612
                    mode=a_bzrdir._get_file_mode())
 
1613
        finally:
 
1614
            if lock_taken:
 
1615
                control_files.unlock()
 
1616
        branch = self.open(a_bzrdir, name, _found=True)
 
1617
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
 
1618
        return branch
 
1619
 
 
1620
    def initialize(self, a_bzrdir, name=None):
1655
1621
        """Create a branch of this format in a_bzrdir.
1656
1622
        
1657
1623
        :param name: Name of the colocated branch to create.
1691
1657
        """
1692
1658
        raise NotImplementedError(self.network_name)
1693
1659
 
1694
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
1695
 
            found_repository=None):
 
1660
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
1696
1661
        """Return the branch object for a_bzrdir
1697
1662
 
1698
1663
        :param a_bzrdir: A BzrDir that contains a branch.
1705
1670
        raise NotImplementedError(self.open)
1706
1671
 
1707
1672
    @classmethod
1708
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1709
1673
    def register_format(klass, format):
1710
 
        """Register a metadir format.
1711
 
 
1712
 
        See MetaDirBranchFormatFactory for the ability to register a format
1713
 
        without loading the code the format needs until it is actually used.
1714
 
        """
1715
 
        format_registry.register(format)
 
1674
        """Register a metadir format."""
 
1675
        klass._formats[format.get_format_string()] = format
 
1676
        # Metadir formats have a network name of their format string, and get
 
1677
        # registered as class factories.
 
1678
        network_format_registry.register(format.get_format_string(), format.__class__)
1716
1679
 
1717
1680
    @classmethod
1718
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1719
1681
    def set_default_format(klass, format):
1720
 
        format_registry.set_default(format)
 
1682
        klass._default_format = format
1721
1683
 
1722
1684
    def supports_set_append_revisions_only(self):
1723
1685
        """True if this format supports set_append_revisions_only."""
1727
1689
        """True if this format records a stacked-on branch."""
1728
1690
        return False
1729
1691
 
1730
 
    def supports_leaving_lock(self):
1731
 
        """True if this format supports leaving locks in place."""
1732
 
        return False # by default
1733
 
 
1734
1692
    @classmethod
1735
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1736
1693
    def unregister_format(klass, format):
1737
 
        format_registry.remove(format)
 
1694
        del klass._formats[format.get_format_string()]
1738
1695
 
1739
1696
    def __str__(self):
1740
1697
        return self.get_format_description().rstrip()
1744
1701
        return False  # by default
1745
1702
 
1746
1703
 
1747
 
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
1748
 
    """A factory for a BranchFormat object, permitting simple lazy registration.
1749
 
    
1750
 
    While none of the built in BranchFormats are lazy registered yet,
1751
 
    bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
1752
 
    use it, and the bzr-loom plugin uses it as well (see
1753
 
    bzrlib.plugins.loom.formats).
1754
 
    """
1755
 
 
1756
 
    def __init__(self, format_string, module_name, member_name):
1757
 
        """Create a MetaDirBranchFormatFactory.
1758
 
 
1759
 
        :param format_string: The format string the format has.
1760
 
        :param module_name: Module to load the format class from.
1761
 
        :param member_name: Attribute name within the module for the format class.
1762
 
        """
1763
 
        registry._LazyObjectGetter.__init__(self, module_name, member_name)
1764
 
        self._format_string = format_string
1765
 
        
1766
 
    def get_format_string(self):
1767
 
        """See BranchFormat.get_format_string."""
1768
 
        return self._format_string
1769
 
 
1770
 
    def __call__(self):
1771
 
        """Used for network_format_registry support."""
1772
 
        return self.get_obj()()
1773
 
 
1774
 
 
1775
1704
class BranchHooks(Hooks):
1776
1705
    """A dictionary mapping hook name to a list of callables for branch hooks.
1777
1706
 
1785
1714
        These are all empty initially, because by default nothing should get
1786
1715
        notified.
1787
1716
        """
1788
 
        Hooks.__init__(self, "bzrlib.branch", "Branch.hooks")
1789
 
        self.add_hook('set_rh',
 
1717
        Hooks.__init__(self)
 
1718
        self.create_hook(HookPoint('set_rh',
1790
1719
            "Invoked whenever the revision history has been set via "
1791
1720
            "set_revision_history. The api signature is (branch, "
1792
1721
            "revision_history), and the branch will be write-locked. "
1793
1722
            "The set_rh hook can be expensive for bzr to trigger, a better "
1794
 
            "hook to use is Branch.post_change_branch_tip.", (0, 15))
1795
 
        self.add_hook('open',
 
1723
            "hook to use is Branch.post_change_branch_tip.", (0, 15), None))
 
1724
        self.create_hook(HookPoint('open',
1796
1725
            "Called with the Branch object that has been opened after a "
1797
 
            "branch is opened.", (1, 8))
1798
 
        self.add_hook('post_push',
 
1726
            "branch is opened.", (1, 8), None))
 
1727
        self.create_hook(HookPoint('post_push',
1799
1728
            "Called after a push operation completes. post_push is called "
1800
1729
            "with a bzrlib.branch.BranchPushResult object and only runs in the "
1801
 
            "bzr client.", (0, 15))
1802
 
        self.add_hook('post_pull',
 
1730
            "bzr client.", (0, 15), None))
 
1731
        self.create_hook(HookPoint('post_pull',
1803
1732
            "Called after a pull operation completes. post_pull is called "
1804
1733
            "with a bzrlib.branch.PullResult object and only runs in the "
1805
 
            "bzr client.", (0, 15))
1806
 
        self.add_hook('pre_commit',
1807
 
            "Called after a commit is calculated but before it is "
 
1734
            "bzr client.", (0, 15), None))
 
1735
        self.create_hook(HookPoint('pre_commit',
 
1736
            "Called after a commit is calculated but before it is is "
1808
1737
            "completed. pre_commit is called with (local, master, old_revno, "
1809
1738
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
1810
1739
            "). old_revid is NULL_REVISION for the first commit to a branch, "
1812
1741
            "basis revision. hooks MUST NOT modify this delta. "
1813
1742
            " future_tree is an in-memory tree obtained from "
1814
1743
            "CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1815
 
            "tree.", (0,91))
1816
 
        self.add_hook('post_commit',
 
1744
            "tree.", (0,91), None))
 
1745
        self.create_hook(HookPoint('post_commit',
1817
1746
            "Called in the bzr client after a commit has completed. "
1818
1747
            "post_commit is called with (local, master, old_revno, old_revid, "
1819
1748
            "new_revno, new_revid). old_revid is NULL_REVISION for the first "
1820
 
            "commit to a branch.", (0, 15))
1821
 
        self.add_hook('post_uncommit',
 
1749
            "commit to a branch.", (0, 15), None))
 
1750
        self.create_hook(HookPoint('post_uncommit',
1822
1751
            "Called in the bzr client after an uncommit completes. "
1823
1752
            "post_uncommit is called with (local, master, old_revno, "
1824
1753
            "old_revid, new_revno, new_revid) where local is the local branch "
1825
1754
            "or None, master is the target branch, and an empty branch "
1826
 
            "receives new_revno of 0, new_revid of None.", (0, 15))
1827
 
        self.add_hook('pre_change_branch_tip',
 
1755
            "receives new_revno of 0, new_revid of None.", (0, 15), None))
 
1756
        self.create_hook(HookPoint('pre_change_branch_tip',
1828
1757
            "Called in bzr client and server before a change to the tip of a "
1829
1758
            "branch is made. pre_change_branch_tip is called with a "
1830
1759
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1831
 
            "commit, uncommit will all trigger this hook.", (1, 6))
1832
 
        self.add_hook('post_change_branch_tip',
 
1760
            "commit, uncommit will all trigger this hook.", (1, 6), None))
 
1761
        self.create_hook(HookPoint('post_change_branch_tip',
1833
1762
            "Called in bzr client and server after a change to the tip of a "
1834
1763
            "branch is made. post_change_branch_tip is called with a "
1835
1764
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1836
 
            "commit, uncommit will all trigger this hook.", (1, 4))
1837
 
        self.add_hook('transform_fallback_location',
 
1765
            "commit, uncommit will all trigger this hook.", (1, 4), None))
 
1766
        self.create_hook(HookPoint('transform_fallback_location',
1838
1767
            "Called when a stacked branch is activating its fallback "
1839
1768
            "locations. transform_fallback_location is called with (branch, "
1840
1769
            "url), and should return a new url. Returning the same url "
1845
1774
            "fallback locations have not been activated. When there are "
1846
1775
            "multiple hooks installed for transform_fallback_location, "
1847
1776
            "all are called with the url returned from the previous hook."
1848
 
            "The order is however undefined.", (1, 9))
1849
 
        self.add_hook('automatic_tag_name',
1850
 
            "Called to determine an automatic tag name for a revision. "
 
1777
            "The order is however undefined.", (1, 9), None))
 
1778
        self.create_hook(HookPoint('automatic_tag_name',
 
1779
            "Called to determine an automatic tag name for a revision."
1851
1780
            "automatic_tag_name is called with (branch, revision_id) and "
1852
1781
            "should return a tag name or None if no tag name could be "
1853
1782
            "determined. The first non-None tag name returned will be used.",
1854
 
            (2, 2))
1855
 
        self.add_hook('post_branch_init',
 
1783
            (2, 2), None))
 
1784
        self.create_hook(HookPoint('post_branch_init',
1856
1785
            "Called after new branch initialization completes. "
1857
1786
            "post_branch_init is called with a "
1858
1787
            "bzrlib.branch.BranchInitHookParams. "
1859
1788
            "Note that init, branch and checkout (both heavyweight and "
1860
 
            "lightweight) will all trigger this hook.", (2, 2))
1861
 
        self.add_hook('post_switch',
 
1789
            "lightweight) will all trigger this hook.", (2, 2), None))
 
1790
        self.create_hook(HookPoint('post_switch',
1862
1791
            "Called after a checkout switches branch. "
1863
1792
            "post_switch is called with a "
1864
 
            "bzrlib.branch.SwitchHookParams.", (2, 2))
 
1793
            "bzrlib.branch.SwitchHookParams.", (2, 2), None))
1865
1794
 
1866
1795
 
1867
1796
 
1870
1799
 
1871
1800
 
1872
1801
class ChangeBranchTipParams(object):
1873
 
    """Object holding parameters passed to `*_change_branch_tip` hooks.
 
1802
    """Object holding parameters passed to *_change_branch_tip hooks.
1874
1803
 
1875
1804
    There are 5 fields that hooks may wish to access:
1876
1805
 
1908
1837
 
1909
1838
 
1910
1839
class BranchInitHookParams(object):
1911
 
    """Object holding parameters passed to `*_branch_init` hooks.
 
1840
    """Object holding parameters passed to *_branch_init hooks.
1912
1841
 
1913
1842
    There are 4 fields that hooks may wish to access:
1914
1843
 
1944
1873
        return self.__dict__ == other.__dict__
1945
1874
 
1946
1875
    def __repr__(self):
1947
 
        return "<%s of %s>" % (self.__class__.__name__, self.branch)
 
1876
        if self.branch:
 
1877
            return "<%s of %s>" % (self.__class__.__name__, self.branch)
 
1878
        else:
 
1879
            return "<%s of format:%s bzrdir:%s>" % (
 
1880
                self.__class__.__name__, self.branch,
 
1881
                self.format, self.bzrdir)
1948
1882
 
1949
1883
 
1950
1884
class SwitchHookParams(object):
1951
 
    """Object holding parameters passed to `*_switch` hooks.
 
1885
    """Object holding parameters passed to *_switch hooks.
1952
1886
 
1953
1887
    There are 4 fields that hooks may wish to access:
1954
1888
 
1980
1914
            self.revision_id)
1981
1915
 
1982
1916
 
 
1917
class BzrBranchFormat4(BranchFormat):
 
1918
    """Bzr branch format 4.
 
1919
 
 
1920
    This format has:
 
1921
     - a revision-history file.
 
1922
     - a branch-lock lock file [ to be shared with the bzrdir ]
 
1923
    """
 
1924
 
 
1925
    def get_format_description(self):
 
1926
        """See BranchFormat.get_format_description()."""
 
1927
        return "Branch format 4"
 
1928
 
 
1929
    def initialize(self, a_bzrdir, name=None):
 
1930
        """Create a branch of this format in a_bzrdir."""
 
1931
        utf8_files = [('revision-history', ''),
 
1932
                      ('branch-name', ''),
 
1933
                      ]
 
1934
        return self._initialize_helper(a_bzrdir, utf8_files, name=name,
 
1935
                                       lock_type='branch4', set_format=False)
 
1936
 
 
1937
    def __init__(self):
 
1938
        super(BzrBranchFormat4, self).__init__()
 
1939
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
 
1940
 
 
1941
    def network_name(self):
 
1942
        """The network name for this format is the control dirs disk label."""
 
1943
        return self._matchingbzrdir.get_format_string()
 
1944
 
 
1945
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1946
        """See BranchFormat.open()."""
 
1947
        if not _found:
 
1948
            # we are being called directly and must probe.
 
1949
            raise NotImplementedError
 
1950
        return BzrBranch(_format=self,
 
1951
                         _control_files=a_bzrdir._control_files,
 
1952
                         a_bzrdir=a_bzrdir,
 
1953
                         name=name,
 
1954
                         _repository=a_bzrdir.open_repository())
 
1955
 
 
1956
    def __str__(self):
 
1957
        return "Bazaar-NG branch format 4"
 
1958
 
 
1959
 
1983
1960
class BranchFormatMetadir(BranchFormat):
1984
1961
    """Common logic for meta-dir based branch formats."""
1985
1962
 
1987
1964
        """What class to instantiate on open calls."""
1988
1965
        raise NotImplementedError(self._branch_class)
1989
1966
 
1990
 
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
1991
 
                           repository=None):
1992
 
        """Initialize a branch in a bzrdir, with specified files
1993
 
 
1994
 
        :param a_bzrdir: The bzrdir to initialize the branch in
1995
 
        :param utf8_files: The files to create as a list of
1996
 
            (filename, content) tuples
1997
 
        :param name: Name of colocated branch to create, if any
1998
 
        :return: a branch in this format
1999
 
        """
2000
 
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
2001
 
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
2002
 
        control_files = lockable_files.LockableFiles(branch_transport,
2003
 
            'lock', lockdir.LockDir)
2004
 
        control_files.create_lock()
2005
 
        control_files.lock_write()
2006
 
        try:
2007
 
            utf8_files += [('format', self.get_format_string())]
2008
 
            for (filename, content) in utf8_files:
2009
 
                branch_transport.put_bytes(
2010
 
                    filename, content,
2011
 
                    mode=a_bzrdir._get_file_mode())
2012
 
        finally:
2013
 
            control_files.unlock()
2014
 
        branch = self.open(a_bzrdir, name, _found=True,
2015
 
                found_repository=repository)
2016
 
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2017
 
        return branch
2018
 
 
2019
1967
    def network_name(self):
2020
1968
        """A simple byte string uniquely identifying this format for RPC calls.
2021
1969
 
2023
1971
        """
2024
1972
        return self.get_format_string()
2025
1973
 
2026
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
2027
 
            found_repository=None):
 
1974
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
2028
1975
        """See BranchFormat.open()."""
2029
1976
        if not _found:
2030
1977
            format = BranchFormat.find_format(a_bzrdir, name=name)
2035
1982
        try:
2036
1983
            control_files = lockable_files.LockableFiles(transport, 'lock',
2037
1984
                                                         lockdir.LockDir)
2038
 
            if found_repository is None:
2039
 
                found_repository = a_bzrdir.find_repository()
2040
1985
            return self._branch_class()(_format=self,
2041
1986
                              _control_files=control_files,
2042
1987
                              name=name,
2043
1988
                              a_bzrdir=a_bzrdir,
2044
 
                              _repository=found_repository,
 
1989
                              _repository=a_bzrdir.find_repository(),
2045
1990
                              ignore_fallbacks=ignore_fallbacks)
2046
1991
        except errors.NoSuchFile:
2047
1992
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
2054
1999
    def supports_tags(self):
2055
2000
        return True
2056
2001
 
2057
 
    def supports_leaving_lock(self):
2058
 
        return True
2059
 
 
2060
2002
 
2061
2003
class BzrBranchFormat5(BranchFormatMetadir):
2062
2004
    """Bzr branch format 5.
2082
2024
        """See BranchFormat.get_format_description()."""
2083
2025
        return "Branch format 5"
2084
2026
 
2085
 
    def initialize(self, a_bzrdir, name=None, repository=None):
 
2027
    def initialize(self, a_bzrdir, name=None):
2086
2028
        """Create a branch of this format in a_bzrdir."""
2087
2029
        utf8_files = [('revision-history', ''),
2088
2030
                      ('branch-name', ''),
2089
2031
                      ]
2090
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
2032
        return self._initialize_helper(a_bzrdir, utf8_files, name)
2091
2033
 
2092
2034
    def supports_tags(self):
2093
2035
        return False
2115
2057
        """See BranchFormat.get_format_description()."""
2116
2058
        return "Branch format 6"
2117
2059
 
2118
 
    def initialize(self, a_bzrdir, name=None, repository=None):
 
2060
    def initialize(self, a_bzrdir, name=None):
2119
2061
        """Create a branch of this format in a_bzrdir."""
2120
2062
        utf8_files = [('last-revision', '0 null:\n'),
2121
2063
                      ('branch.conf', ''),
2122
2064
                      ('tags', ''),
2123
2065
                      ]
2124
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
2066
        return self._initialize_helper(a_bzrdir, utf8_files, name)
2125
2067
 
2126
2068
    def make_tags(self, branch):
2127
2069
        """See bzrlib.branch.BranchFormat.make_tags()."""
2145
2087
        """See BranchFormat.get_format_description()."""
2146
2088
        return "Branch format 8"
2147
2089
 
2148
 
    def initialize(self, a_bzrdir, name=None, repository=None):
 
2090
    def initialize(self, a_bzrdir, name=None):
2149
2091
        """Create a branch of this format in a_bzrdir."""
2150
2092
        utf8_files = [('last-revision', '0 null:\n'),
2151
2093
                      ('branch.conf', ''),
2152
2094
                      ('tags', ''),
2153
2095
                      ('references', '')
2154
2096
                      ]
2155
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
2097
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2098
 
 
2099
    def __init__(self):
 
2100
        super(BzrBranchFormat8, self).__init__()
 
2101
        self._matchingbzrdir.repository_format = \
 
2102
            RepositoryFormatKnitPack5RichRoot()
2156
2103
 
2157
2104
    def make_tags(self, branch):
2158
2105
        """See bzrlib.branch.BranchFormat.make_tags()."""
2167
2114
    supports_reference_locations = True
2168
2115
 
2169
2116
 
2170
 
class BzrBranchFormat7(BranchFormatMetadir):
 
2117
class BzrBranchFormat7(BzrBranchFormat8):
2171
2118
    """Branch format with last-revision, tags, and a stacked location pointer.
2172
2119
 
2173
2120
    The stacked location pointer is passed down to the repository and requires
2176
2123
    This format was introduced in bzr 1.6.
2177
2124
    """
2178
2125
 
2179
 
    def initialize(self, a_bzrdir, name=None, repository=None):
 
2126
    def initialize(self, a_bzrdir, name=None):
2180
2127
        """Create a branch of this format in a_bzrdir."""
2181
2128
        utf8_files = [('last-revision', '0 null:\n'),
2182
2129
                      ('branch.conf', ''),
2183
2130
                      ('tags', ''),
2184
2131
                      ]
2185
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
2132
        return self._initialize_helper(a_bzrdir, utf8_files, name)
2186
2133
 
2187
2134
    def _branch_class(self):
2188
2135
        return BzrBranch7
2198
2145
    def supports_set_append_revisions_only(self):
2199
2146
        return True
2200
2147
 
2201
 
    def supports_stacking(self):
2202
 
        return True
2203
 
 
2204
 
    def make_tags(self, branch):
2205
 
        """See bzrlib.branch.BranchFormat.make_tags()."""
2206
 
        return BasicTags(branch)
2207
 
 
2208
2148
    supports_reference_locations = False
2209
2149
 
2210
2150
 
2227
2167
        """See BranchFormat.get_format_description()."""
2228
2168
        return "Checkout reference format 1"
2229
2169
 
2230
 
    def get_reference(self, a_bzrdir, name=None):
 
2170
    def get_reference(self, a_bzrdir):
2231
2171
        """See BranchFormat.get_reference()."""
2232
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
2172
        transport = a_bzrdir.get_branch_transport(None)
2233
2173
        return transport.get_bytes('location')
2234
2174
 
2235
 
    def set_reference(self, a_bzrdir, name, to_branch):
 
2175
    def set_reference(self, a_bzrdir, to_branch):
2236
2176
        """See BranchFormat.set_reference()."""
2237
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
2177
        transport = a_bzrdir.get_branch_transport(None)
2238
2178
        location = transport.put_bytes('location', to_branch.base)
2239
2179
 
2240
 
    def initialize(self, a_bzrdir, name=None, target_branch=None,
2241
 
            repository=None):
 
2180
    def initialize(self, a_bzrdir, name=None, target_branch=None):
2242
2181
        """Create a branch of this format in a_bzrdir."""
2243
2182
        if target_branch is None:
2244
2183
            # this format does not implement branch itself, thus the implicit
2272
2211
        return clone
2273
2212
 
2274
2213
    def open(self, a_bzrdir, name=None, _found=False, location=None,
2275
 
             possible_transports=None, ignore_fallbacks=False,
2276
 
             found_repository=None):
 
2214
             possible_transports=None, ignore_fallbacks=False):
2277
2215
        """Return the branch that the branch reference in a_bzrdir points at.
2278
2216
 
2279
2217
        :param a_bzrdir: A BzrDir that contains a branch.
2293
2231
                raise AssertionError("wrong format %r found for %r" %
2294
2232
                    (format, self))
2295
2233
        if location is None:
2296
 
            location = self.get_reference(a_bzrdir, name)
 
2234
            location = self.get_reference(a_bzrdir)
2297
2235
        real_bzrdir = bzrdir.BzrDir.open(
2298
2236
            location, possible_transports=possible_transports)
2299
2237
        result = real_bzrdir.open_branch(name=name, 
2310
2248
        return result
2311
2249
 
2312
2250
 
2313
 
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
2314
 
    """Branch format registry."""
2315
 
 
2316
 
    def __init__(self, other_registry=None):
2317
 
        super(BranchFormatRegistry, self).__init__(other_registry)
2318
 
        self._default_format = None
2319
 
 
2320
 
    def set_default(self, format):
2321
 
        self._default_format = format
2322
 
 
2323
 
    def get_default(self):
2324
 
        return self._default_format
2325
 
 
2326
 
 
2327
2251
network_format_registry = registry.FormatRegistry()
2328
2252
"""Registry of formats indexed by their network name.
2329
2253
 
2332
2256
BranchFormat.network_name() for more detail.
2333
2257
"""
2334
2258
 
2335
 
format_registry = BranchFormatRegistry(network_format_registry)
2336
 
 
2337
2259
 
2338
2260
# formats which have no format string are not discoverable
2339
2261
# and not independently creatable, so are not registered.
2341
2263
__format6 = BzrBranchFormat6()
2342
2264
__format7 = BzrBranchFormat7()
2343
2265
__format8 = BzrBranchFormat8()
2344
 
format_registry.register(__format5)
2345
 
format_registry.register(BranchReferenceFormat())
2346
 
format_registry.register(__format6)
2347
 
format_registry.register(__format7)
2348
 
format_registry.register(__format8)
2349
 
format_registry.set_default(__format7)
 
2266
BranchFormat.register_format(__format5)
 
2267
BranchFormat.register_format(BranchReferenceFormat())
 
2268
BranchFormat.register_format(__format6)
 
2269
BranchFormat.register_format(__format7)
 
2270
BranchFormat.register_format(__format8)
 
2271
BranchFormat.set_default_format(__format7)
 
2272
_legacy_formats = [BzrBranchFormat4(),
 
2273
    ]
 
2274
network_format_registry.register(
 
2275
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
2350
2276
 
2351
2277
 
2352
2278
class BranchWriteLockResult(LogicalLockResult):
2500
2426
        """See Branch.print_file."""
2501
2427
        return self.repository.print_file(file, revision_id)
2502
2428
 
 
2429
    def _write_revision_history(self, history):
 
2430
        """Factored out of set_revision_history.
 
2431
 
 
2432
        This performs the actual writing to disk.
 
2433
        It is intended to be called by BzrBranch5.set_revision_history."""
 
2434
        self._transport.put_bytes(
 
2435
            'revision-history', '\n'.join(history),
 
2436
            mode=self.bzrdir._get_file_mode())
 
2437
 
 
2438
    @needs_write_lock
 
2439
    def set_revision_history(self, rev_history):
 
2440
        """See Branch.set_revision_history."""
 
2441
        if 'evil' in debug.debug_flags:
 
2442
            mutter_callsite(3, "set_revision_history scales with history.")
 
2443
        check_not_reserved_id = _mod_revision.check_not_reserved_id
 
2444
        for rev_id in rev_history:
 
2445
            check_not_reserved_id(rev_id)
 
2446
        if Branch.hooks['post_change_branch_tip']:
 
2447
            # Don't calculate the last_revision_info() if there are no hooks
 
2448
            # that will use it.
 
2449
            old_revno, old_revid = self.last_revision_info()
 
2450
        if len(rev_history) == 0:
 
2451
            revid = _mod_revision.NULL_REVISION
 
2452
        else:
 
2453
            revid = rev_history[-1]
 
2454
        self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
 
2455
        self._write_revision_history(rev_history)
 
2456
        self._clear_cached_state()
 
2457
        self._cache_revision_history(rev_history)
 
2458
        for hook in Branch.hooks['set_rh']:
 
2459
            hook(self, rev_history)
 
2460
        if Branch.hooks['post_change_branch_tip']:
 
2461
            self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2462
 
 
2463
    def _synchronize_history(self, destination, revision_id):
 
2464
        """Synchronize last revision and revision history between branches.
 
2465
 
 
2466
        This version is most efficient when the destination is also a
 
2467
        BzrBranch5, but works for BzrBranch6 as long as the revision
 
2468
        history is the true lefthand parent history, and all of the revisions
 
2469
        are in the destination's repository.  If not, set_revision_history
 
2470
        will fail.
 
2471
 
 
2472
        :param destination: The branch to copy the history into
 
2473
        :param revision_id: The revision-id to truncate history at.  May
 
2474
          be None to copy complete history.
 
2475
        """
 
2476
        if not isinstance(destination._format, BzrBranchFormat5):
 
2477
            super(BzrBranch, self)._synchronize_history(
 
2478
                destination, revision_id)
 
2479
            return
 
2480
        if revision_id == _mod_revision.NULL_REVISION:
 
2481
            new_history = []
 
2482
        else:
 
2483
            new_history = self.revision_history()
 
2484
        if revision_id is not None and new_history != []:
 
2485
            try:
 
2486
                new_history = new_history[:new_history.index(revision_id) + 1]
 
2487
            except ValueError:
 
2488
                rev = self.repository.get_revision(revision_id)
 
2489
                new_history = rev.get_history(self.repository)[1:]
 
2490
        destination.set_revision_history(new_history)
 
2491
 
2503
2492
    @needs_write_lock
2504
2493
    def set_last_revision_info(self, revno, revision_id):
2505
 
        if not revision_id or not isinstance(revision_id, basestring):
2506
 
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
 
2494
        """Set the last revision of this branch.
 
2495
 
 
2496
        The caller is responsible for checking that the revno is correct
 
2497
        for this revision id.
 
2498
 
 
2499
        It may be possible to set the branch last revision to an id not
 
2500
        present in the repository.  However, branches can also be
 
2501
        configured to check constraints on history, in which case this may not
 
2502
        be permitted.
 
2503
        """
2507
2504
        revision_id = _mod_revision.ensure_null(revision_id)
2508
 
        old_revno, old_revid = self.last_revision_info()
2509
 
        if self._get_append_revisions_only():
2510
 
            self._check_history_violation(revision_id)
2511
 
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
2512
 
        self._write_last_revision_info(revno, revision_id)
2513
 
        self._clear_cached_state()
2514
 
        self._last_revision_info_cache = revno, revision_id
2515
 
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2505
        # this old format stores the full history, but this api doesn't
 
2506
        # provide it, so we must generate, and might as well check it's
 
2507
        # correct
 
2508
        history = self._lefthand_history(revision_id)
 
2509
        if len(history) != revno:
 
2510
            raise AssertionError('%d != %d' % (len(history), revno))
 
2511
        self.set_revision_history(history)
 
2512
 
 
2513
    def _gen_revision_history(self):
 
2514
        history = self._transport.get_bytes('revision-history').split('\n')
 
2515
        if history[-1:] == ['']:
 
2516
            # There shouldn't be a trailing newline, but just in case.
 
2517
            history.pop()
 
2518
        return history
 
2519
 
 
2520
    @needs_write_lock
 
2521
    def generate_revision_history(self, revision_id, last_rev=None,
 
2522
        other_branch=None):
 
2523
        """Create a new revision history that will finish with revision_id.
 
2524
 
 
2525
        :param revision_id: the new tip to use.
 
2526
        :param last_rev: The previous last_revision. If not None, then this
 
2527
            must be a ancestory of revision_id, or DivergedBranches is raised.
 
2528
        :param other_branch: The other branch that DivergedBranches should
 
2529
            raise with respect to.
 
2530
        """
 
2531
        self.set_revision_history(self._lefthand_history(revision_id,
 
2532
            last_rev, other_branch))
2516
2533
 
2517
2534
    def basis_tree(self):
2518
2535
        """See Branch.basis_tree."""
2527
2544
                pass
2528
2545
        return None
2529
2546
 
 
2547
    def _basic_push(self, target, overwrite, stop_revision):
 
2548
        """Basic implementation of push without bound branches or hooks.
 
2549
 
 
2550
        Must be called with source read locked and target write locked.
 
2551
        """
 
2552
        result = BranchPushResult()
 
2553
        result.source_branch = self
 
2554
        result.target_branch = target
 
2555
        result.old_revno, result.old_revid = target.last_revision_info()
 
2556
        self.update_references(target)
 
2557
        if result.old_revid != self.last_revision():
 
2558
            # We assume that during 'push' this repository is closer than
 
2559
            # the target.
 
2560
            graph = self.repository.get_graph(target.repository)
 
2561
            target.update_revisions(self, stop_revision,
 
2562
                overwrite=overwrite, graph=graph)
 
2563
        if self._push_should_merge_tags():
 
2564
            result.tag_conflicts = self.tags.merge_to(target.tags,
 
2565
                overwrite)
 
2566
        result.new_revno, result.new_revid = target.last_revision_info()
 
2567
        return result
 
2568
 
2530
2569
    def get_stacked_on_url(self):
2531
2570
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
2532
2571
 
2543
2582
            self._transport.put_bytes('parent', url + '\n',
2544
2583
                mode=self.bzrdir._get_file_mode())
2545
2584
 
 
2585
 
 
2586
class BzrBranch5(BzrBranch):
 
2587
    """A format 5 branch. This supports new features over plain branches.
 
2588
 
 
2589
    It has support for a master_branch which is the data for bound branches.
 
2590
    """
 
2591
 
 
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
        This could memoise the branch, but if thats done
 
2605
        it must be revalidated on each new lock.
 
2606
        So for now we just don't memoise it.
 
2607
        # RBC 20060304 review this decision.
 
2608
        """
 
2609
        bound_loc = self.get_bound_location()
 
2610
        if not bound_loc:
 
2611
            return None
 
2612
        try:
 
2613
            return Branch.open(bound_loc,
 
2614
                               possible_transports=possible_transports)
 
2615
        except (errors.NotBranchError, errors.ConnectionError), e:
 
2616
            raise errors.BoundBranchConnectionFailure(
 
2617
                    self, bound_loc, e)
 
2618
 
2546
2619
    @needs_write_lock
2547
 
    def unbind(self):
2548
 
        """If bound, unbind"""
2549
 
        return self.set_bound_location(None)
 
2620
    def set_bound_location(self, location):
 
2621
        """Set the target where this branch is bound to.
 
2622
 
 
2623
        :param location: URL to the target branch
 
2624
        """
 
2625
        if location:
 
2626
            self._transport.put_bytes('bound', location+'\n',
 
2627
                mode=self.bzrdir._get_file_mode())
 
2628
        else:
 
2629
            try:
 
2630
                self._transport.delete('bound')
 
2631
            except errors.NoSuchFile:
 
2632
                return False
 
2633
            return True
2550
2634
 
2551
2635
    @needs_write_lock
2552
2636
    def bind(self, other):
2574
2658
        # history around
2575
2659
        self.set_bound_location(other.base)
2576
2660
 
2577
 
    def get_bound_location(self):
2578
 
        try:
2579
 
            return self._transport.get_bytes('bound')[:-1]
2580
 
        except errors.NoSuchFile:
2581
 
            return None
2582
 
 
2583
 
    @needs_read_lock
2584
 
    def get_master_branch(self, possible_transports=None):
2585
 
        """Return the branch we are bound to.
2586
 
 
2587
 
        :return: Either a Branch, or None
2588
 
        """
2589
 
        if self._master_branch_cache is None:
2590
 
            self._master_branch_cache = self._get_master_branch(
2591
 
                possible_transports)
2592
 
        return self._master_branch_cache
2593
 
 
2594
 
    def _get_master_branch(self, possible_transports):
2595
 
        bound_loc = self.get_bound_location()
2596
 
        if not bound_loc:
2597
 
            return None
2598
 
        try:
2599
 
            return Branch.open(bound_loc,
2600
 
                               possible_transports=possible_transports)
2601
 
        except (errors.NotBranchError, errors.ConnectionError), e:
2602
 
            raise errors.BoundBranchConnectionFailure(
2603
 
                    self, bound_loc, e)
2604
 
 
2605
2661
    @needs_write_lock
2606
 
    def set_bound_location(self, location):
2607
 
        """Set the target where this branch is bound to.
2608
 
 
2609
 
        :param location: URL to the target branch
2610
 
        """
2611
 
        self._master_branch_cache = None
2612
 
        if location:
2613
 
            self._transport.put_bytes('bound', location+'\n',
2614
 
                mode=self.bzrdir._get_file_mode())
2615
 
        else:
2616
 
            try:
2617
 
                self._transport.delete('bound')
2618
 
            except errors.NoSuchFile:
2619
 
                return False
2620
 
            return True
 
2662
    def unbind(self):
 
2663
        """If bound, unbind"""
 
2664
        return self.set_bound_location(None)
2621
2665
 
2622
2666
    @needs_write_lock
2623
2667
    def update(self, possible_transports=None):
2636
2680
            return old_tip
2637
2681
        return None
2638
2682
 
2639
 
    def _read_last_revision_info(self):
2640
 
        revision_string = self._transport.get_bytes('last-revision')
2641
 
        revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
2642
 
        revision_id = cache_utf8.get_cached_utf8(revision_id)
2643
 
        revno = int(revno)
2644
 
        return revno, revision_id
2645
 
 
2646
 
    def _write_last_revision_info(self, revno, revision_id):
2647
 
        """Simply write out the revision id, with no checks.
2648
 
 
2649
 
        Use set_last_revision_info to perform this safely.
2650
 
 
2651
 
        Does not update the revision_history cache.
2652
 
        """
2653
 
        revision_id = _mod_revision.ensure_null(revision_id)
2654
 
        out_string = '%d %s\n' % (revno, revision_id)
2655
 
        self._transport.put_bytes('last-revision', out_string,
2656
 
            mode=self.bzrdir._get_file_mode())
2657
 
 
2658
 
 
2659
 
class FullHistoryBzrBranch(BzrBranch):
2660
 
    """Bzr branch which contains the full revision history."""
2661
 
 
2662
 
    @needs_write_lock
2663
 
    def set_last_revision_info(self, revno, revision_id):
2664
 
        if not revision_id or not isinstance(revision_id, basestring):
2665
 
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2666
 
        revision_id = _mod_revision.ensure_null(revision_id)
2667
 
        # this old format stores the full history, but this api doesn't
2668
 
        # provide it, so we must generate, and might as well check it's
2669
 
        # correct
2670
 
        history = self._lefthand_history(revision_id)
2671
 
        if len(history) != revno:
2672
 
            raise AssertionError('%d != %d' % (len(history), revno))
2673
 
        self._set_revision_history(history)
2674
 
 
2675
 
    def _read_last_revision_info(self):
2676
 
        rh = self.revision_history()
2677
 
        revno = len(rh)
2678
 
        if revno:
2679
 
            return (revno, rh[-1])
2680
 
        else:
2681
 
            return (0, _mod_revision.NULL_REVISION)
2682
 
 
2683
 
    @deprecated_method(deprecated_in((2, 4, 0)))
2684
 
    @needs_write_lock
2685
 
    def set_revision_history(self, rev_history):
2686
 
        """See Branch.set_revision_history."""
2687
 
        self._set_revision_history(rev_history)
2688
 
 
2689
 
    def _set_revision_history(self, rev_history):
2690
 
        if 'evil' in debug.debug_flags:
2691
 
            mutter_callsite(3, "set_revision_history scales with history.")
2692
 
        check_not_reserved_id = _mod_revision.check_not_reserved_id
2693
 
        for rev_id in rev_history:
2694
 
            check_not_reserved_id(rev_id)
2695
 
        if Branch.hooks['post_change_branch_tip']:
2696
 
            # Don't calculate the last_revision_info() if there are no hooks
2697
 
            # that will use it.
2698
 
            old_revno, old_revid = self.last_revision_info()
2699
 
        if len(rev_history) == 0:
2700
 
            revid = _mod_revision.NULL_REVISION
2701
 
        else:
2702
 
            revid = rev_history[-1]
2703
 
        self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
2704
 
        self._write_revision_history(rev_history)
2705
 
        self._clear_cached_state()
2706
 
        self._cache_revision_history(rev_history)
2707
 
        for hook in Branch.hooks['set_rh']:
2708
 
            hook(self, rev_history)
2709
 
        if Branch.hooks['post_change_branch_tip']:
2710
 
            self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2711
 
 
2712
 
    def _write_revision_history(self, history):
2713
 
        """Factored out of set_revision_history.
2714
 
 
2715
 
        This performs the actual writing to disk.
2716
 
        It is intended to be called by set_revision_history."""
2717
 
        self._transport.put_bytes(
2718
 
            'revision-history', '\n'.join(history),
2719
 
            mode=self.bzrdir._get_file_mode())
2720
 
 
2721
 
    def _gen_revision_history(self):
2722
 
        history = self._transport.get_bytes('revision-history').split('\n')
2723
 
        if history[-1:] == ['']:
2724
 
            # There shouldn't be a trailing newline, but just in case.
2725
 
            history.pop()
2726
 
        return history
2727
 
 
2728
 
    def _synchronize_history(self, destination, revision_id):
2729
 
        if not isinstance(destination, FullHistoryBzrBranch):
2730
 
            super(BzrBranch, self)._synchronize_history(
2731
 
                destination, revision_id)
2732
 
            return
2733
 
        if revision_id == _mod_revision.NULL_REVISION:
2734
 
            new_history = []
2735
 
        else:
2736
 
            new_history = self.revision_history()
2737
 
        if revision_id is not None and new_history != []:
2738
 
            try:
2739
 
                new_history = new_history[:new_history.index(revision_id) + 1]
2740
 
            except ValueError:
2741
 
                rev = self.repository.get_revision(revision_id)
2742
 
                new_history = rev.get_history(self.repository)[1:]
2743
 
        destination._set_revision_history(new_history)
2744
 
 
2745
 
    @needs_write_lock
2746
 
    def generate_revision_history(self, revision_id, last_rev=None,
2747
 
        other_branch=None):
2748
 
        """Create a new revision history that will finish with revision_id.
2749
 
 
2750
 
        :param revision_id: the new tip to use.
2751
 
        :param last_rev: The previous last_revision. If not None, then this
2752
 
            must be a ancestory of revision_id, or DivergedBranches is raised.
2753
 
        :param other_branch: The other branch that DivergedBranches should
2754
 
            raise with respect to.
2755
 
        """
2756
 
        self._set_revision_history(self._lefthand_history(revision_id,
2757
 
            last_rev, other_branch))
2758
 
 
2759
 
 
2760
 
class BzrBranch5(FullHistoryBzrBranch):
2761
 
    """A format 5 branch. This supports new features over plain branches.
2762
 
 
2763
 
    It has support for a master_branch which is the data for bound branches.
2764
 
    """
2765
 
 
2766
 
 
2767
 
class BzrBranch8(BzrBranch):
 
2683
 
 
2684
class BzrBranch8(BzrBranch5):
2768
2685
    """A branch that stores tree-reference locations."""
2769
2686
 
2770
2687
    def _open_hook(self):
2796
2713
        self._last_revision_info_cache = None
2797
2714
        self._reference_info = None
2798
2715
 
 
2716
    def _last_revision_info(self):
 
2717
        revision_string = self._transport.get_bytes('last-revision')
 
2718
        revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
 
2719
        revision_id = cache_utf8.get_cached_utf8(revision_id)
 
2720
        revno = int(revno)
 
2721
        return revno, revision_id
 
2722
 
 
2723
    def _write_last_revision_info(self, revno, revision_id):
 
2724
        """Simply write out the revision id, with no checks.
 
2725
 
 
2726
        Use set_last_revision_info to perform this safely.
 
2727
 
 
2728
        Does not update the revision_history cache.
 
2729
        Intended to be called by set_last_revision_info and
 
2730
        _write_revision_history.
 
2731
        """
 
2732
        revision_id = _mod_revision.ensure_null(revision_id)
 
2733
        out_string = '%d %s\n' % (revno, revision_id)
 
2734
        self._transport.put_bytes('last-revision', out_string,
 
2735
            mode=self.bzrdir._get_file_mode())
 
2736
 
 
2737
    @needs_write_lock
 
2738
    def set_last_revision_info(self, revno, revision_id):
 
2739
        revision_id = _mod_revision.ensure_null(revision_id)
 
2740
        old_revno, old_revid = self.last_revision_info()
 
2741
        if self._get_append_revisions_only():
 
2742
            self._check_history_violation(revision_id)
 
2743
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
 
2744
        self._write_last_revision_info(revno, revision_id)
 
2745
        self._clear_cached_state()
 
2746
        self._last_revision_info_cache = revno, revision_id
 
2747
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2748
 
 
2749
    def _synchronize_history(self, destination, revision_id):
 
2750
        """Synchronize last revision and revision history between branches.
 
2751
 
 
2752
        :see: Branch._synchronize_history
 
2753
        """
 
2754
        # XXX: The base Branch has a fast implementation of this method based
 
2755
        # on set_last_revision_info, but BzrBranch/BzrBranch5 have a slower one
 
2756
        # that uses set_revision_history.  This class inherits from BzrBranch5,
 
2757
        # but wants the fast implementation, so it calls
 
2758
        # Branch._synchronize_history directly.
 
2759
        Branch._synchronize_history(self, destination, revision_id)
 
2760
 
2799
2761
    def _check_history_violation(self, revision_id):
2800
 
        current_revid = self.last_revision()
2801
 
        last_revision = _mod_revision.ensure_null(current_revid)
 
2762
        last_revision = _mod_revision.ensure_null(self.last_revision())
2802
2763
        if _mod_revision.is_null(last_revision):
2803
2764
            return
2804
 
        graph = self.repository.get_graph()
2805
 
        for lh_ancestor in graph.iter_lefthand_ancestry(revision_id):
2806
 
            if lh_ancestor == current_revid:
2807
 
                return
2808
 
        raise errors.AppendRevisionsOnlyViolation(self.user_url)
 
2765
        if last_revision not in self._lefthand_history(revision_id):
 
2766
            raise errors.AppendRevisionsOnlyViolation(self.user_url)
2809
2767
 
2810
2768
    def _gen_revision_history(self):
2811
2769
        """Generate the revision history from last revision
2814
2772
        self._extend_partial_history(stop_index=last_revno-1)
2815
2773
        return list(reversed(self._partial_revision_history_cache))
2816
2774
 
 
2775
    def _write_revision_history(self, history):
 
2776
        """Factored out of set_revision_history.
 
2777
 
 
2778
        This performs the actual writing to disk, with format-specific checks.
 
2779
        It is intended to be called by BzrBranch5.set_revision_history.
 
2780
        """
 
2781
        if len(history) == 0:
 
2782
            last_revision = 'null:'
 
2783
        else:
 
2784
            if history != self._lefthand_history(history[-1]):
 
2785
                raise errors.NotLefthandHistory(history)
 
2786
            last_revision = history[-1]
 
2787
        if self._get_append_revisions_only():
 
2788
            self._check_history_violation(last_revision)
 
2789
        self._write_last_revision_info(len(history), last_revision)
 
2790
 
2817
2791
    @needs_write_lock
2818
2792
    def _set_parent_location(self, url):
2819
2793
        """Set the parent branch"""
2905
2879
 
2906
2880
    def set_bound_location(self, location):
2907
2881
        """See Branch.set_push_location."""
2908
 
        self._master_branch_cache = None
2909
2882
        result = None
2910
2883
        config = self.get_config()
2911
2884
        if location is None:
2942
2915
        # you can always ask for the URL; but you might not be able to use it
2943
2916
        # if the repo can't support stacking.
2944
2917
        ## self._check_stackable_repo()
2945
 
        # stacked_on_location is only ever defined in branch.conf, so don't
2946
 
        # waste effort reading the whole stack of config files.
2947
 
        config = self.get_config()._get_branch_data_config()
2948
 
        stacked_url = self._get_config_location('stacked_on_location',
2949
 
            config=config)
 
2918
        stacked_url = self._get_config_location('stacked_on_location')
2950
2919
        if stacked_url is None:
2951
2920
            raise errors.NotStacked(self)
2952
2921
        return stacked_url
2955
2924
        return self.get_config(
2956
2925
            ).get_user_option_as_bool('append_revisions_only')
2957
2926
 
 
2927
    @needs_write_lock
 
2928
    def generate_revision_history(self, revision_id, last_rev=None,
 
2929
                                  other_branch=None):
 
2930
        """See BzrBranch5.generate_revision_history"""
 
2931
        history = self._lefthand_history(revision_id, last_rev, other_branch)
 
2932
        revno = len(history)
 
2933
        self.set_last_revision_info(revno, revision_id)
 
2934
 
2958
2935
    @needs_read_lock
2959
2936
    def get_rev_id(self, revno, history=None):
2960
2937
        """Find the revision id of the specified revno."""
2984
2961
        try:
2985
2962
            index = self._partial_revision_history_cache.index(revision_id)
2986
2963
        except ValueError:
2987
 
            try:
2988
 
                self._extend_partial_history(stop_revision=revision_id)
2989
 
            except errors.RevisionNotPresent, e:
2990
 
                raise errors.GhostRevisionsHaveNoRevno(revision_id, e.revision_id)
 
2964
            self._extend_partial_history(stop_revision=revision_id)
2991
2965
            index = len(self._partial_revision_history_cache) - 1
2992
2966
            if self._partial_revision_history_cache[index] != revision_id:
2993
2967
                raise errors.NoSuchRevision(self, revision_id)
3048
3022
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
3049
3023
    """
3050
3024
 
3051
 
    @deprecated_method(deprecated_in((2, 3, 0)))
3052
3025
    def __int__(self):
3053
 
        """Return the relative change in revno.
3054
 
 
3055
 
        :deprecated: Use `new_revno` and `old_revno` instead.
3056
 
        """
 
3026
        # DEPRECATED: pull used to return the change in revno
3057
3027
        return self.new_revno - self.old_revno
3058
3028
 
3059
3029
    def report(self, to_file):
3084
3054
        target, otherwise it will be None.
3085
3055
    """
3086
3056
 
3087
 
    @deprecated_method(deprecated_in((2, 3, 0)))
3088
3057
    def __int__(self):
3089
 
        """Return the relative change in revno.
3090
 
 
3091
 
        :deprecated: Use `new_revno` and `old_revno` instead.
3092
 
        """
 
3058
        # DEPRECATED: push used to return the change in revno
3093
3059
        return self.new_revno - self.old_revno
3094
3060
 
3095
3061
    def report(self, to_file):
3174
3140
        branch._transport.put_bytes('format', format.get_format_string())
3175
3141
 
3176
3142
 
 
3143
def _run_with_write_locked_target(target, callable, *args, **kwargs):
 
3144
    """Run ``callable(*args, **kwargs)``, write-locking target for the
 
3145
    duration.
 
3146
 
 
3147
    _run_with_write_locked_target will attempt to release the lock it acquires.
 
3148
 
 
3149
    If an exception is raised by callable, then that exception *will* be
 
3150
    propagated, even if the unlock attempt raises its own error.  Thus
 
3151
    _run_with_write_locked_target should be preferred to simply doing::
 
3152
 
 
3153
        target.lock_write()
 
3154
        try:
 
3155
            return callable(*args, **kwargs)
 
3156
        finally:
 
3157
            target.unlock()
 
3158
 
 
3159
    """
 
3160
    # This is very similar to bzrlib.decorators.needs_write_lock.  Perhaps they
 
3161
    # should share code?
 
3162
    target.lock_write()
 
3163
    try:
 
3164
        result = callable(*args, **kwargs)
 
3165
    except:
 
3166
        exc_info = sys.exc_info()
 
3167
        try:
 
3168
            target.unlock()
 
3169
        finally:
 
3170
            raise exc_info[0], exc_info[1], exc_info[2]
 
3171
    else:
 
3172
        target.unlock()
 
3173
        return result
 
3174
 
 
3175
 
3177
3176
class InterBranch(InterObject):
3178
3177
    """This class represents operations taking place between two branches.
3179
3178
 
3185
3184
    _optimisers = []
3186
3185
    """The available optimised InterBranch types."""
3187
3186
 
3188
 
    @classmethod
3189
 
    def _get_branch_formats_to_test(klass):
3190
 
        """Return an iterable of format tuples for testing.
3191
 
        
3192
 
        :return: An iterable of (from_format, to_format) to use when testing
3193
 
            this InterBranch class. Each InterBranch class should define this
3194
 
            method itself.
3195
 
        """
3196
 
        raise NotImplementedError(klass._get_branch_formats_to_test)
 
3187
    @staticmethod
 
3188
    def _get_branch_formats_to_test():
 
3189
        """Return a tuple with the Branch formats to use when testing."""
 
3190
        raise NotImplementedError(InterBranch._get_branch_formats_to_test)
3197
3191
 
3198
 
    @needs_write_lock
3199
3192
    def pull(self, overwrite=False, stop_revision=None,
3200
3193
             possible_transports=None, local=False):
3201
3194
        """Mirror source into target branch.
3206
3199
        """
3207
3200
        raise NotImplementedError(self.pull)
3208
3201
 
3209
 
    @needs_write_lock
3210
 
    def push(self, overwrite=False, stop_revision=None, lossy=False,
 
3202
    def update_revisions(self, stop_revision=None, overwrite=False,
 
3203
                         graph=None):
 
3204
        """Pull in new perfect-fit revisions.
 
3205
 
 
3206
        :param stop_revision: Updated until the given revision
 
3207
        :param overwrite: Always set the branch pointer, rather than checking
 
3208
            to see if it is a proper descendant.
 
3209
        :param graph: A Graph object that can be used to query history
 
3210
            information. This can be None.
 
3211
        :return: None
 
3212
        """
 
3213
        raise NotImplementedError(self.update_revisions)
 
3214
 
 
3215
    def push(self, overwrite=False, stop_revision=None,
3211
3216
             _override_hook_source_branch=None):
3212
3217
        """Mirror the source branch into the target branch.
3213
3218
 
3215
3220
        """
3216
3221
        raise NotImplementedError(self.push)
3217
3222
 
3218
 
    @needs_write_lock
3219
 
    def copy_content_into(self, revision_id=None):
3220
 
        """Copy the content of source into target
3221
 
 
3222
 
        revision_id: if not None, the revision history in the new branch will
3223
 
                     be truncated to end with revision_id.
3224
 
        """
3225
 
        raise NotImplementedError(self.copy_content_into)
3226
 
 
3227
 
    @needs_write_lock
3228
 
    def fetch(self, stop_revision=None, limit=None):
3229
 
        """Fetch revisions.
3230
 
 
3231
 
        :param stop_revision: Last revision to fetch
3232
 
        :param limit: Optional rough limit of revisions to fetch
3233
 
        """
3234
 
        raise NotImplementedError(self.fetch)
3235
 
 
3236
3223
 
3237
3224
class GenericInterBranch(InterBranch):
3238
 
    """InterBranch implementation that uses public Branch functions."""
3239
 
 
3240
 
    @classmethod
3241
 
    def is_compatible(klass, source, target):
3242
 
        # GenericBranch uses the public API, so always compatible
3243
 
        return True
3244
 
 
3245
 
    @classmethod
3246
 
    def _get_branch_formats_to_test(klass):
3247
 
        return [(format_registry.get_default(), format_registry.get_default())]
3248
 
 
3249
 
    @classmethod
3250
 
    def unwrap_format(klass, format):
3251
 
        if isinstance(format, remote.RemoteBranchFormat):
3252
 
            format._ensure_real()
3253
 
            return format._custom_format
3254
 
        return format
3255
 
 
3256
 
    @needs_write_lock
3257
 
    def copy_content_into(self, revision_id=None):
3258
 
        """Copy the content of source into target
3259
 
 
3260
 
        revision_id: if not None, the revision history in the new branch will
3261
 
                     be truncated to end with revision_id.
3262
 
        """
3263
 
        self.source.update_references(self.target)
3264
 
        self.source._synchronize_history(self.target, revision_id)
3265
 
        try:
3266
 
            parent = self.source.get_parent()
3267
 
        except errors.InaccessibleParent, e:
3268
 
            mutter('parent was not accessible to copy: %s', e)
3269
 
        else:
3270
 
            if parent:
3271
 
                self.target.set_parent(parent)
3272
 
        if self.source._push_should_merge_tags():
3273
 
            self.source.tags.merge_to(self.target.tags)
3274
 
 
3275
 
    @needs_write_lock
3276
 
    def fetch(self, stop_revision=None, limit=None):
3277
 
        if self.target.base == self.source.base:
3278
 
            return (0, [])
 
3225
    """InterBranch implementation that uses public Branch functions.
 
3226
    """
 
3227
 
 
3228
    @staticmethod
 
3229
    def _get_branch_formats_to_test():
 
3230
        return BranchFormat._default_format, BranchFormat._default_format
 
3231
 
 
3232
    def update_revisions(self, stop_revision=None, overwrite=False,
 
3233
        graph=None):
 
3234
        """See InterBranch.update_revisions()."""
3279
3235
        self.source.lock_read()
3280
3236
        try:
3281
 
            fetch_spec_factory = fetch.FetchSpecFactory()
3282
 
            fetch_spec_factory.source_branch = self.source
3283
 
            fetch_spec_factory.source_branch_stop_revision_id = stop_revision
3284
 
            fetch_spec_factory.source_repo = self.source.repository
3285
 
            fetch_spec_factory.target_repo = self.target.repository
3286
 
            fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
3287
 
            fetch_spec_factory.limit = limit
3288
 
            fetch_spec = fetch_spec_factory.make_fetch_spec()
3289
 
            return self.target.repository.fetch(self.source.repository,
3290
 
                fetch_spec=fetch_spec)
 
3237
            other_revno, other_last_revision = self.source.last_revision_info()
 
3238
            stop_revno = None # unknown
 
3239
            if stop_revision is None:
 
3240
                stop_revision = other_last_revision
 
3241
                if _mod_revision.is_null(stop_revision):
 
3242
                    # if there are no commits, we're done.
 
3243
                    return
 
3244
                stop_revno = other_revno
 
3245
 
 
3246
            # what's the current last revision, before we fetch [and change it
 
3247
            # possibly]
 
3248
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
3249
            # we fetch here so that we don't process data twice in the common
 
3250
            # case of having something to pull, and so that the check for
 
3251
            # already merged can operate on the just fetched graph, which will
 
3252
            # be cached in memory.
 
3253
            self.target.fetch(self.source, stop_revision)
 
3254
            # Check to see if one is an ancestor of the other
 
3255
            if not overwrite:
 
3256
                if graph is None:
 
3257
                    graph = self.target.repository.get_graph()
 
3258
                if self.target._check_if_descendant_or_diverged(
 
3259
                        stop_revision, last_rev, graph, self.source):
 
3260
                    # stop_revision is a descendant of last_rev, but we aren't
 
3261
                    # overwriting, so we're done.
 
3262
                    return
 
3263
            if stop_revno is None:
 
3264
                if graph is None:
 
3265
                    graph = self.target.repository.get_graph()
 
3266
                this_revno, this_last_revision = \
 
3267
                        self.target.last_revision_info()
 
3268
                stop_revno = graph.find_distance_to_null(stop_revision,
 
3269
                                [(other_last_revision, other_revno),
 
3270
                                 (this_last_revision, this_revno)])
 
3271
            self.target.set_last_revision_info(stop_revno, stop_revision)
3291
3272
        finally:
3292
3273
            self.source.unlock()
3293
3274
 
3294
 
    @needs_write_lock
3295
 
    def _update_revisions(self, stop_revision=None, overwrite=False,
3296
 
            graph=None):
3297
 
        other_revno, other_last_revision = self.source.last_revision_info()
3298
 
        stop_revno = None # unknown
3299
 
        if stop_revision is None:
3300
 
            stop_revision = other_last_revision
3301
 
            if _mod_revision.is_null(stop_revision):
3302
 
                # if there are no commits, we're done.
3303
 
                return
3304
 
            stop_revno = other_revno
3305
 
 
3306
 
        # what's the current last revision, before we fetch [and change it
3307
 
        # possibly]
3308
 
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
3309
 
        # we fetch here so that we don't process data twice in the common
3310
 
        # case of having something to pull, and so that the check for
3311
 
        # already merged can operate on the just fetched graph, which will
3312
 
        # be cached in memory.
3313
 
        self.fetch(stop_revision=stop_revision)
3314
 
        # Check to see if one is an ancestor of the other
3315
 
        if not overwrite:
3316
 
            if graph is None:
3317
 
                graph = self.target.repository.get_graph()
3318
 
            if self.target._check_if_descendant_or_diverged(
3319
 
                    stop_revision, last_rev, graph, self.source):
3320
 
                # stop_revision is a descendant of last_rev, but we aren't
3321
 
                # overwriting, so we're done.
3322
 
                return
3323
 
        if stop_revno is None:
3324
 
            if graph is None:
3325
 
                graph = self.target.repository.get_graph()
3326
 
            this_revno, this_last_revision = \
3327
 
                    self.target.last_revision_info()
3328
 
            stop_revno = graph.find_distance_to_null(stop_revision,
3329
 
                            [(other_last_revision, other_revno),
3330
 
                             (this_last_revision, this_revno)])
3331
 
        self.target.set_last_revision_info(stop_revno, stop_revision)
3332
 
 
3333
 
    @needs_write_lock
3334
3275
    def pull(self, overwrite=False, stop_revision=None,
3335
 
             possible_transports=None, run_hooks=True,
3336
 
             _override_hook_target=None, local=False):
3337
 
        """Pull from source into self, updating my master if any.
3338
 
 
3339
 
        :param run_hooks: Private parameter - if false, this branch
3340
 
            is being called because it's the master of the primary branch,
3341
 
            so it should not run its hooks.
3342
 
        """
3343
 
        bound_location = self.target.get_bound_location()
3344
 
        if local and not bound_location:
3345
 
            raise errors.LocalRequiresBoundBranch()
3346
 
        master_branch = None
3347
 
        source_is_master = (self.source.user_url == bound_location)
3348
 
        if not local and bound_location and not source_is_master:
3349
 
            # not pulling from master, so we need to update master.
3350
 
            master_branch = self.target.get_master_branch(possible_transports)
3351
 
            master_branch.lock_write()
3352
 
        try:
3353
 
            if master_branch:
3354
 
                # pull from source into master.
3355
 
                master_branch.pull(self.source, overwrite, stop_revision,
3356
 
                    run_hooks=False)
3357
 
            return self._pull(overwrite,
3358
 
                stop_revision, _hook_master=master_branch,
3359
 
                run_hooks=run_hooks,
3360
 
                _override_hook_target=_override_hook_target,
3361
 
                merge_tags_to_master=not source_is_master)
3362
 
        finally:
3363
 
            if master_branch:
3364
 
                master_branch.unlock()
3365
 
 
3366
 
    def push(self, overwrite=False, stop_revision=None, lossy=False,
3367
 
             _override_hook_source_branch=None):
3368
 
        """See InterBranch.push.
3369
 
 
3370
 
        This is the basic concrete implementation of push()
3371
 
 
3372
 
        :param _override_hook_source_branch: If specified, run the hooks
3373
 
            passing this Branch as the source, rather than self.  This is for
3374
 
            use of RemoteBranch, where push is delegated to the underlying
3375
 
            vfs-based Branch.
3376
 
        """
3377
 
        if lossy:
3378
 
            raise errors.LossyPushToSameVCS(self.source, self.target)
3379
 
        # TODO: Public option to disable running hooks - should be trivial but
3380
 
        # needs tests.
3381
 
 
3382
 
        op = cleanup.OperationWithCleanups(self._push_with_bound_branches)
3383
 
        op.add_cleanup(self.source.lock_read().unlock)
3384
 
        op.add_cleanup(self.target.lock_write().unlock)
3385
 
        return op.run(overwrite, stop_revision,
3386
 
            _override_hook_source_branch=_override_hook_source_branch)
3387
 
 
3388
 
    def _basic_push(self, overwrite, stop_revision):
3389
 
        """Basic implementation of push without bound branches or hooks.
3390
 
 
3391
 
        Must be called with source read locked and target write locked.
3392
 
        """
3393
 
        result = BranchPushResult()
3394
 
        result.source_branch = self.source
3395
 
        result.target_branch = self.target
3396
 
        result.old_revno, result.old_revid = self.target.last_revision_info()
3397
 
        self.source.update_references(self.target)
3398
 
        if result.old_revid != stop_revision:
3399
 
            # We assume that during 'push' this repository is closer than
3400
 
            # the target.
3401
 
            graph = self.source.repository.get_graph(self.target.repository)
3402
 
            self._update_revisions(stop_revision, overwrite=overwrite,
3403
 
                    graph=graph)
3404
 
        if self.source._push_should_merge_tags():
3405
 
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3406
 
                overwrite)
3407
 
        result.new_revno, result.new_revid = self.target.last_revision_info()
3408
 
        return result
3409
 
 
3410
 
    def _push_with_bound_branches(self, operation, overwrite, stop_revision,
3411
 
            _override_hook_source_branch=None):
3412
 
        """Push from source into target, and into target's master if any.
3413
 
        """
3414
 
        def _run_hooks():
3415
 
            if _override_hook_source_branch:
3416
 
                result.source_branch = _override_hook_source_branch
3417
 
            for hook in Branch.hooks['post_push']:
3418
 
                hook(result)
3419
 
 
3420
 
        bound_location = self.target.get_bound_location()
3421
 
        if bound_location and self.target.base != bound_location:
3422
 
            # there is a master branch.
3423
 
            #
3424
 
            # XXX: Why the second check?  Is it even supported for a branch to
3425
 
            # be bound to itself? -- mbp 20070507
3426
 
            master_branch = self.target.get_master_branch()
3427
 
            master_branch.lock_write()
3428
 
            operation.add_cleanup(master_branch.unlock)
3429
 
            # push into the master from the source branch.
3430
 
            master_inter = InterBranch.get(self.source, master_branch)
3431
 
            master_inter._basic_push(overwrite, stop_revision)
3432
 
            # and push into the target branch from the source. Note that
3433
 
            # we push from the source branch again, because it's considered
3434
 
            # the highest bandwidth repository.
3435
 
            result = self._basic_push(overwrite, stop_revision)
3436
 
            result.master_branch = master_branch
3437
 
            result.local_branch = self.target
3438
 
        else:
3439
 
            master_branch = None
3440
 
            # no master branch
3441
 
            result = self._basic_push(overwrite, stop_revision)
3442
 
            # TODO: Why set master_branch and local_branch if there's no
3443
 
            # binding?  Maybe cleaner to just leave them unset? -- mbp
3444
 
            # 20070504
3445
 
            result.master_branch = self.target
3446
 
            result.local_branch = None
3447
 
        _run_hooks()
3448
 
        return result
3449
 
 
3450
 
    def _pull(self, overwrite=False, stop_revision=None,
3451
3276
             possible_transports=None, _hook_master=None, run_hooks=True,
3452
 
             _override_hook_target=None, local=False,
3453
 
             merge_tags_to_master=True):
 
3277
             _override_hook_target=None, local=False):
3454
3278
        """See Branch.pull.
3455
3279
 
3456
 
        This function is the core worker, used by GenericInterBranch.pull to
3457
 
        avoid duplication when pulling source->master and source->local.
3458
 
 
3459
3280
        :param _hook_master: Private parameter - set the branch to
3460
3281
            be supplied as the master to pull hooks.
3461
3282
        :param run_hooks: Private parameter - if false, this branch
3462
3283
            is being called because it's the master of the primary branch,
3463
3284
            so it should not run its hooks.
3464
 
            is being called because it's the master of the primary branch,
3465
 
            so it should not run its hooks.
3466
3285
        :param _override_hook_target: Private parameter - set the branch to be
3467
3286
            supplied as the target_branch to pull hooks.
3468
3287
        :param local: Only update the local branch, and not the bound branch.
3487
3306
            # -- JRV20090506
3488
3307
            result.old_revno, result.old_revid = \
3489
3308
                self.target.last_revision_info()
3490
 
            self._update_revisions(stop_revision, overwrite=overwrite,
3491
 
                graph=graph)
 
3309
            self.target.update_revisions(self.source, stop_revision,
 
3310
                overwrite=overwrite, graph=graph)
3492
3311
            # TODO: The old revid should be specified when merging tags, 
3493
3312
            # so a tags implementation that versions tags can only 
3494
3313
            # pull in the most recent changes. -- JRV20090506
3495
3314
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3496
 
                overwrite, ignore_master=not merge_tags_to_master)
 
3315
                overwrite)
3497
3316
            result.new_revno, result.new_revid = self.target.last_revision_info()
3498
3317
            if _hook_master:
3499
3318
                result.master_branch = _hook_master
3508
3327
            self.source.unlock()
3509
3328
        return result
3510
3329
 
 
3330
    def push(self, overwrite=False, stop_revision=None,
 
3331
             _override_hook_source_branch=None):
 
3332
        """See InterBranch.push.
 
3333
 
 
3334
        This is the basic concrete implementation of push()
 
3335
 
 
3336
        :param _override_hook_source_branch: If specified, run
 
3337
        the hooks passing this Branch as the source, rather than self.
 
3338
        This is for use of RemoteBranch, where push is delegated to the
 
3339
        underlying vfs-based Branch.
 
3340
        """
 
3341
        # TODO: Public option to disable running hooks - should be trivial but
 
3342
        # needs tests.
 
3343
        self.source.lock_read()
 
3344
        try:
 
3345
            return _run_with_write_locked_target(
 
3346
                self.target, self._push_with_bound_branches, overwrite,
 
3347
                stop_revision,
 
3348
                _override_hook_source_branch=_override_hook_source_branch)
 
3349
        finally:
 
3350
            self.source.unlock()
 
3351
 
 
3352
    def _push_with_bound_branches(self, overwrite, stop_revision,
 
3353
            _override_hook_source_branch=None):
 
3354
        """Push from source into target, and into target's master if any.
 
3355
        """
 
3356
        def _run_hooks():
 
3357
            if _override_hook_source_branch:
 
3358
                result.source_branch = _override_hook_source_branch
 
3359
            for hook in Branch.hooks['post_push']:
 
3360
                hook(result)
 
3361
 
 
3362
        bound_location = self.target.get_bound_location()
 
3363
        if bound_location and self.target.base != bound_location:
 
3364
            # there is a master branch.
 
3365
            #
 
3366
            # XXX: Why the second check?  Is it even supported for a branch to
 
3367
            # be bound to itself? -- mbp 20070507
 
3368
            master_branch = self.target.get_master_branch()
 
3369
            master_branch.lock_write()
 
3370
            try:
 
3371
                # push into the master from the source branch.
 
3372
                self.source._basic_push(master_branch, overwrite, stop_revision)
 
3373
                # and push into the target branch from the source. Note that we
 
3374
                # push from the source branch again, because its considered the
 
3375
                # highest bandwidth repository.
 
3376
                result = self.source._basic_push(self.target, overwrite,
 
3377
                    stop_revision)
 
3378
                result.master_branch = master_branch
 
3379
                result.local_branch = self.target
 
3380
                _run_hooks()
 
3381
                return result
 
3382
            finally:
 
3383
                master_branch.unlock()
 
3384
        else:
 
3385
            # no master branch
 
3386
            result = self.source._basic_push(self.target, overwrite,
 
3387
                stop_revision)
 
3388
            # TODO: Why set master_branch and local_branch if there's no
 
3389
            # binding?  Maybe cleaner to just leave them unset? -- mbp
 
3390
            # 20070504
 
3391
            result.master_branch = self.target
 
3392
            result.local_branch = None
 
3393
            _run_hooks()
 
3394
            return result
 
3395
 
 
3396
    @classmethod
 
3397
    def is_compatible(self, source, target):
 
3398
        # GenericBranch uses the public API, so always compatible
 
3399
        return True
 
3400
 
 
3401
 
 
3402
class InterToBranch5(GenericInterBranch):
 
3403
 
 
3404
    @staticmethod
 
3405
    def _get_branch_formats_to_test():
 
3406
        return BranchFormat._default_format, BzrBranchFormat5()
 
3407
 
 
3408
    def pull(self, overwrite=False, stop_revision=None,
 
3409
             possible_transports=None, run_hooks=True,
 
3410
             _override_hook_target=None, local=False):
 
3411
        """Pull from source into self, updating my master if any.
 
3412
 
 
3413
        :param run_hooks: Private parameter - if false, this branch
 
3414
            is being called because it's the master of the primary branch,
 
3415
            so it should not run its hooks.
 
3416
        """
 
3417
        bound_location = self.target.get_bound_location()
 
3418
        if local and not bound_location:
 
3419
            raise errors.LocalRequiresBoundBranch()
 
3420
        master_branch = None
 
3421
        if not local and bound_location and self.source.user_url != bound_location:
 
3422
            # not pulling from master, so we need to update master.
 
3423
            master_branch = self.target.get_master_branch(possible_transports)
 
3424
            master_branch.lock_write()
 
3425
        try:
 
3426
            if master_branch:
 
3427
                # pull from source into master.
 
3428
                master_branch.pull(self.source, overwrite, stop_revision,
 
3429
                    run_hooks=False)
 
3430
            return super(InterToBranch5, self).pull(overwrite,
 
3431
                stop_revision, _hook_master=master_branch,
 
3432
                run_hooks=run_hooks,
 
3433
                _override_hook_target=_override_hook_target)
 
3434
        finally:
 
3435
            if master_branch:
 
3436
                master_branch.unlock()
 
3437
 
3511
3438
 
3512
3439
InterBranch.register_optimiser(GenericInterBranch)
 
3440
InterBranch.register_optimiser(InterToBranch5)