~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Matt Nordhoff
  • Date: 2009-04-04 02:50:01 UTC
  • mfrom: (4253 +trunk)
  • mto: This revision was merged to the branch mainline in revision 4256.
  • Revision ID: mnordhoff@mattnordhoff.com-20090404025001-z1403k0tatmc8l91
Merge bzr.dev, fixing conflicts.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 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
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
 
18
18
import sys
30
30
        lockable_files,
31
31
        repository,
32
32
        revision as _mod_revision,
 
33
        symbol_versioning,
33
34
        transport,
34
35
        tsort,
35
36
        ui,
36
37
        urlutils,
37
38
        )
38
 
from bzrlib.config import BranchConfig
 
39
from bzrlib.config import BranchConfig, TransportConfig
39
40
from bzrlib.repofmt.pack_repo import RepositoryFormatKnitPack5RichRoot
40
41
from bzrlib.tag import (
41
42
    BasicTags,
44
45
""")
45
46
 
46
47
from bzrlib.decorators import needs_read_lock, needs_write_lock
47
 
from bzrlib.hooks import Hooks
 
48
from bzrlib.hooks import HookPoint, Hooks
 
49
from bzrlib.inter import InterObject
 
50
from bzrlib import registry
48
51
from bzrlib.symbol_versioning import (
49
52
    deprecated_in,
50
53
    deprecated_method,
81
84
    # - RBC 20060112
82
85
    base = None
83
86
 
84
 
    # override this to set the strategy for storing tags
85
 
    def _make_tags(self):
86
 
        return DisabledTags(self)
87
 
 
88
87
    def __init__(self, *ignored, **ignored_too):
89
 
        self.tags = self._make_tags()
 
88
        self.tags = self._format.make_tags(self)
90
89
        self._revision_history_cache = None
91
90
        self._revision_id_to_revno_cache = None
92
91
        self._partial_revision_id_to_revno_cache = {}
100
99
    def _open_hook(self):
101
100
        """Called by init to allow simpler extension of the base class."""
102
101
 
 
102
    def _activate_fallback_location(self, url):
 
103
        """Activate the branch/repository from url as a fallback repository."""
 
104
        self.repository.add_fallback_repository(
 
105
            self._get_fallback_repository(url))
 
106
 
103
107
    def break_lock(self):
104
108
        """Break a lock if one is present from another instance.
105
109
 
114
118
        if master is not None:
115
119
            master.break_lock()
116
120
 
 
121
    def _check_stackable_repo(self):
 
122
        if not self.repository._format.supports_external_lookups:
 
123
            raise errors.UnstackableRepositoryFormat(self.repository._format,
 
124
                self.repository.base)
 
125
 
117
126
    @staticmethod
118
127
    def open(base, _unsupported=False, possible_transports=None):
119
128
        """Open the branch rooted at base.
134
143
    @staticmethod
135
144
    def open_containing(url, possible_transports=None):
136
145
        """Open an existing branch which contains url.
137
 
        
 
146
 
138
147
        This probes for a branch at url, and searches upwards from there.
139
148
 
140
149
        Basically we keep looking up until we find the control directory or
141
150
        run into the root.  If there isn't one, raises NotBranchError.
142
 
        If there is one and it is either an unrecognised format or an unsupported 
 
151
        If there is one and it is either an unrecognised format or an unsupported
143
152
        format, UnknownFormatError or UnsupportedFormatError are raised.
144
153
        If there is one, it is returned, along with the unused portion of url.
145
154
        """
147
156
                                                         possible_transports)
148
157
        return control.open_branch(), relpath
149
158
 
 
159
    def _push_should_merge_tags(self):
 
160
        """Should _basic_push merge this branch's tags into the target?
 
161
 
 
162
        The default implementation returns False if this branch has no tags,
 
163
        and True the rest of the time.  Subclasses may override this.
 
164
        """
 
165
        return self.supports_tags() and self.tags.get_tag_dict()
 
166
 
150
167
    def get_config(self):
151
168
        return BranchConfig(self)
152
169
 
 
170
    def _get_config(self):
 
171
        """Get the concrete config for just the config in this branch.
 
172
 
 
173
        This is not intended for client use; see Branch.get_config for the
 
174
        public API.
 
175
 
 
176
        Added in 1.14.
 
177
 
 
178
        :return: An object supporting get_option and set_option.
 
179
        """
 
180
        raise NotImplementedError(self._get_config)
 
181
 
 
182
    def _get_fallback_repository(self, url):
 
183
        """Get the repository we fallback to at url."""
 
184
        url = urlutils.join(self.base, url)
 
185
        a_bzrdir = bzrdir.BzrDir.open(url,
 
186
            possible_transports=[self.bzrdir.root_transport])
 
187
        return a_bzrdir.open_branch().repository
 
188
 
 
189
    def _get_tags_bytes(self):
 
190
        """Get the bytes of a serialised tags dict.
 
191
 
 
192
        Note that not all branches support tags, nor do all use the same tags
 
193
        logic: this method is specific to BasicTags. Other tag implementations
 
194
        may use the same method name and behave differently, safely, because
 
195
        of the double-dispatch via
 
196
        format.make_tags->tags_instance->get_tags_dict.
 
197
 
 
198
        :return: The bytes of the tags file.
 
199
        :seealso: Branch._set_tags_bytes.
 
200
        """
 
201
        return self._transport.get_bytes('tags')
 
202
 
153
203
    def _get_nick(self, local=False, possible_transports=None):
154
204
        config = self.get_config()
155
205
        # explicit overrides master, but don't look for master if local is True
255
305
    @needs_read_lock
256
306
    def revision_id_to_dotted_revno(self, revision_id):
257
307
        """Given a revision id, return its dotted revno.
258
 
        
 
308
 
259
309
        :return: a tuple like (1,) or (400,1,3).
260
310
        """
261
311
        return self._do_revision_id_to_dotted_revno(revision_id)
425
475
    def leave_lock_in_place(self):
426
476
        """Tell this branch object not to release the physical lock when this
427
477
        object is unlocked.
428
 
        
 
478
 
429
479
        If lock_write doesn't return a token, then this method is not supported.
430
480
        """
431
481
        self.control_files.leave_in_place()
454
504
        :param last_revision: What revision to stop at (None for at the end
455
505
                              of the branch.
456
506
        :param pb: An optional progress bar to use.
457
 
 
458
 
        Returns the copied revision count and the failed revisions in a tuple:
459
 
        (copied, failures).
 
507
        :return: None
460
508
        """
461
509
        if self.base == from_branch.base:
462
510
            return (0, [])
463
 
        if pb is None:
464
 
            nested_pb = ui.ui_factory.nested_progress_bar()
465
 
            pb = nested_pb
466
 
        else:
467
 
            nested_pb = None
468
 
 
 
511
        if pb is not None:
 
512
            symbol_versioning.warn(
 
513
                symbol_versioning.deprecated_in((1, 14, 0))
 
514
                % "pb parameter to fetch()")
469
515
        from_branch.lock_read()
470
516
        try:
471
517
            if last_revision is None:
472
 
                pb.update('get source history')
473
518
                last_revision = from_branch.last_revision()
474
519
                last_revision = _mod_revision.ensure_null(last_revision)
475
520
            return self.repository.fetch(from_branch.repository,
476
521
                                         revision_id=last_revision,
477
 
                                         pb=nested_pb)
 
522
                                         pb=pb)
478
523
        finally:
479
 
            if nested_pb is not None:
480
 
                nested_pb.finished()
481
524
            from_branch.unlock()
482
525
 
483
526
    def get_bound_location(self):
487
530
        branch.
488
531
        """
489
532
        return None
490
 
    
 
533
 
491
534
    def get_old_bound_location(self):
492
535
        """Return the URL of the branch we used to be bound to
493
536
        """
494
537
        raise errors.UpgradeRequired(self.base)
495
538
 
496
 
    def get_commit_builder(self, parents, config=None, timestamp=None, 
497
 
                           timezone=None, committer=None, revprops=None, 
 
539
    def get_commit_builder(self, parents, config=None, timestamp=None,
 
540
                           timezone=None, committer=None, revprops=None,
498
541
                           revision_id=None):
499
542
        """Obtain a CommitBuilder for this branch.
500
 
        
 
543
 
501
544
        :param parents: Revision ids of the parents of the new revision.
502
545
        :param config: Optional configuration to use.
503
546
        :param timestamp: Optional timestamp recorded for commit.
509
552
 
510
553
        if config is None:
511
554
            config = self.get_config()
512
 
        
 
555
 
513
556
        return self.repository.get_commit_builder(self, parents, config,
514
557
            timestamp, timezone, committer, revprops, revision_id)
515
558
 
516
559
    def get_master_branch(self, possible_transports=None):
517
560
        """Return the branch we are bound to.
518
 
        
 
561
 
519
562
        :return: Either a Branch, or None
520
563
        """
521
564
        return None
555
598
        :raises UnstackableRepositoryFormat: If the repository does not support
556
599
            stacking.
557
600
        """
558
 
        raise NotImplementedError(self.set_stacked_on_url)
 
601
        if not self._format.supports_stacking():
 
602
            raise errors.UnstackableBranchFormat(self._format, self.base)
 
603
        self._check_stackable_repo()
 
604
        if not url:
 
605
            try:
 
606
                old_url = self.get_stacked_on_url()
 
607
            except (errors.NotStacked, errors.UnstackableBranchFormat,
 
608
                errors.UnstackableRepositoryFormat):
 
609
                return
 
610
            url = ''
 
611
            # repositories don't offer an interface to remove fallback
 
612
            # repositories today; take the conceptually simpler option and just
 
613
            # reopen it.
 
614
            self.repository = self.bzrdir.find_repository()
 
615
            # for every revision reference the branch has, ensure it is pulled
 
616
            # in.
 
617
            source_repository = self._get_fallback_repository(old_url)
 
618
            for revision_id in chain([self.last_revision()],
 
619
                self.tags.get_reverse_tag_dict()):
 
620
                self.repository.fetch(source_repository, revision_id,
 
621
                    find_ghosts=True)
 
622
        else:
 
623
            self._activate_fallback_location(url)
 
624
        # write this out after the repository is stacked to avoid setting a
 
625
        # stacked config that doesn't work.
 
626
        self._set_config_location('stacked_on_location', url)
 
627
 
 
628
 
 
629
    def _set_tags_bytes(self, bytes):
 
630
        """Mirror method for _get_tags_bytes.
 
631
 
 
632
        :seealso: Branch._get_tags_bytes.
 
633
        """
 
634
        return _run_with_write_locked_target(self, self._transport.put_bytes,
 
635
            'tags', bytes)
559
636
 
560
637
    def _cache_revision_history(self, rev_history):
561
638
        """Set the cached revision history to rev_history.
592
669
 
593
670
    def _gen_revision_history(self):
594
671
        """Return sequence of revision hashes on to this branch.
595
 
        
 
672
 
596
673
        Unlike revision_history, this method always regenerates or rereads the
597
674
        revision history, i.e. it does not cache the result, so repeated calls
598
675
        may be expensive.
599
676
 
600
677
        Concrete subclasses should override this instead of revision_history so
601
678
        that subclasses do not need to deal with caching logic.
602
 
        
 
679
 
603
680
        This API is semi-public; it only for use by subclasses, all other code
604
681
        should consider it to be private.
605
682
        """
608
685
    @needs_read_lock
609
686
    def revision_history(self):
610
687
        """Return sequence of revision ids on this branch.
611
 
        
 
688
 
612
689
        This method will cache the revision history for as long as it is safe to
613
690
        do so.
614
691
        """
662
739
    @deprecated_method(deprecated_in((1, 6, 0)))
663
740
    def missing_revisions(self, other, stop_revision=None):
664
741
        """Return a list of new revisions that would perfectly fit.
665
 
        
 
742
 
666
743
        If self and other have not diverged, return a list of the revisions
667
744
        present in other, but missing from self.
668
745
        """
695
772
            information. This can be None.
696
773
        :return: None
697
774
        """
698
 
        other.lock_read()
699
 
        try:
700
 
            other_revno, other_last_revision = other.last_revision_info()
701
 
            stop_revno = None # unknown
702
 
            if stop_revision is None:
703
 
                stop_revision = other_last_revision
704
 
                if _mod_revision.is_null(stop_revision):
705
 
                    # if there are no commits, we're done.
706
 
                    return
707
 
                stop_revno = other_revno
708
 
 
709
 
            # what's the current last revision, before we fetch [and change it
710
 
            # possibly]
711
 
            last_rev = _mod_revision.ensure_null(self.last_revision())
712
 
            # we fetch here so that we don't process data twice in the common
713
 
            # case of having something to pull, and so that the check for 
714
 
            # already merged can operate on the just fetched graph, which will
715
 
            # be cached in memory.
716
 
            self.fetch(other, stop_revision)
717
 
            # Check to see if one is an ancestor of the other
718
 
            if not overwrite:
719
 
                if graph is None:
720
 
                    graph = self.repository.get_graph()
721
 
                if self._check_if_descendant_or_diverged(
722
 
                        stop_revision, last_rev, graph, other):
723
 
                    # stop_revision is a descendant of last_rev, but we aren't
724
 
                    # overwriting, so we're done.
725
 
                    return
726
 
            if stop_revno is None:
727
 
                if graph is None:
728
 
                    graph = self.repository.get_graph()
729
 
                this_revno, this_last_revision = self.last_revision_info()
730
 
                stop_revno = graph.find_distance_to_null(stop_revision,
731
 
                                [(other_last_revision, other_revno),
732
 
                                 (this_last_revision, this_revno)])
733
 
            self.set_last_revision_info(stop_revno, stop_revision)
734
 
        finally:
735
 
            other.unlock()
 
775
        return InterBranch.get(other, self).update_revisions(stop_revision,
 
776
            overwrite, graph)
 
777
 
 
778
    def import_last_revision_info(self, source_repo, revno, revid):
 
779
        """Set the last revision info, importing from another repo if necessary.
 
780
 
 
781
        This is used by the bound branch code to upload a revision to
 
782
        the master branch first before updating the tip of the local branch.
 
783
 
 
784
        :param source_repo: Source repository to optionally fetch from
 
785
        :param revno: Revision number of the new tip
 
786
        :param revid: Revision id of the new tip
 
787
        """
 
788
        if not self.repository.has_same_location(source_repo):
 
789
            self.repository.fetch(source_repo, revision_id=revid)
 
790
        self.set_last_revision_info(revno, revid)
736
791
 
737
792
    def revision_id_to_revno(self, revision_id):
738
793
        """Given a revision id, return its revno"""
778
833
    def get_parent(self):
779
834
        """Return the parent location of the branch.
780
835
 
781
 
        This is the default location for push/pull/missing.  The usual
 
836
        This is the default location for pull/missing.  The usual
782
837
        pattern is that the user can override it by specifying a
783
838
        location.
784
839
        """
785
 
        raise NotImplementedError(self.get_parent)
 
840
        parent = self._get_parent_location()
 
841
        if parent is None:
 
842
            return parent
 
843
        # This is an old-format absolute path to a local branch
 
844
        # turn it into a url
 
845
        if parent.startswith('/'):
 
846
            parent = urlutils.local_path_to_url(parent.decode('utf8'))
 
847
        try:
 
848
            return urlutils.join(self.base[:-1], parent)
 
849
        except errors.InvalidURLJoin, e:
 
850
            raise errors.InaccessibleParent(parent, self.base)
 
851
 
 
852
    def _get_parent_location(self):
 
853
        raise NotImplementedError(self._get_parent_location)
786
854
 
787
855
    def _set_config_location(self, name, url, config=None,
788
856
                             make_relative=False):
881
949
 
882
950
    @needs_write_lock
883
951
    def update(self):
884
 
        """Synchronise this branch with the master branch if any. 
 
952
        """Synchronise this branch with the master branch if any.
885
953
 
886
954
        :return: None or the last_revision pivoted out during the update.
887
955
        """
894
962
        """
895
963
        if revno != 0:
896
964
            self.check_real_revno(revno)
897
 
            
 
965
 
898
966
    def check_real_revno(self, revno):
899
967
        """\
900
968
        Check whether a revno corresponds to a real revision.
904
972
            raise errors.InvalidRevisionNumber(revno)
905
973
 
906
974
    @needs_read_lock
907
 
    def clone(self, to_bzrdir, revision_id=None):
 
975
    def clone(self, to_bzrdir, revision_id=None, repository_policy=None):
908
976
        """Clone this branch into to_bzrdir preserving all semantic values.
909
 
        
 
977
 
 
978
        Most API users will want 'create_clone_on_transport', which creates a
 
979
        new bzrdir and branch on the fly.
 
980
 
910
981
        revision_id: if not None, the revision history in the new branch will
911
982
                     be truncated to end with revision_id.
912
983
        """
913
984
        result = to_bzrdir.create_branch()
 
985
        if repository_policy is not None:
 
986
            repository_policy.configure_branch(result)
914
987
        self.copy_content_into(result, revision_id=revision_id)
915
988
        return  result
916
989
 
917
990
    @needs_read_lock
918
 
    def sprout(self, to_bzrdir, revision_id=None):
 
991
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None):
919
992
        """Create a new line of development from the branch, into to_bzrdir.
920
993
 
921
994
        to_bzrdir controls the branch format.
924
997
                     be truncated to end with revision_id.
925
998
        """
926
999
        result = to_bzrdir.create_branch()
 
1000
        if repository_policy is not None:
 
1001
            repository_policy.configure_branch(result)
927
1002
        self.copy_content_into(result, revision_id=revision_id)
928
1003
        result.set_parent(self.bzrdir.root_transport.base)
929
1004
        return result
956
1031
            revno = len(list(self.repository.iter_reverse_revision_history(
957
1032
                                                                revision_id)))
958
1033
        destination.set_last_revision_info(revno, revision_id)
959
 
    
 
1034
 
960
1035
    @needs_read_lock
961
1036
    def copy_content_into(self, destination, revision_id=None):
962
1037
        """Copy the content of self into destination.
972
1047
        else:
973
1048
            if parent:
974
1049
                destination.set_parent(parent)
975
 
        self.tags.merge_to(destination.tags)
 
1050
        if self._push_should_merge_tags():
 
1051
            self.tags.merge_to(destination.tags)
976
1052
 
977
1053
    @needs_read_lock
978
1054
    def check(self):
979
1055
        """Check consistency of the branch.
980
1056
 
981
1057
        In particular this checks that revisions given in the revision-history
982
 
        do actually match up in the revision graph, and that they're all 
 
1058
        do actually match up in the revision graph, and that they're all
983
1059
        present in the repository.
984
 
        
 
1060
 
985
1061
        Callers will typically also want to check the repository.
986
1062
 
987
1063
        :return: A BranchCheckResult.
1026
1102
            format.set_branch_format(self._format)
1027
1103
        return format
1028
1104
 
 
1105
    def create_clone_on_transport(self, to_transport, revision_id=None,
 
1106
        stacked_on=None):
 
1107
        """Create a clone of this branch and its bzrdir.
 
1108
 
 
1109
        :param to_transport: The transport to clone onto.
 
1110
        :param revision_id: The revision id to use as tip in the new branch.
 
1111
            If None the tip is obtained from this branch.
 
1112
        :param stacked_on: An optional URL to stack the clone on.
 
1113
        """
 
1114
        # XXX: Fix the bzrdir API to allow getting the branch back from the
 
1115
        # clone call. Or something. 20090224 RBC/spiv.
 
1116
        dir_to = self.bzrdir.clone_on_transport(to_transport,
 
1117
            revision_id=revision_id, stacked_on=stacked_on)
 
1118
        return dir_to.open_branch()
 
1119
 
1029
1120
    def create_checkout(self, to_location, revision_id=None,
1030
1121
                        lightweight=False, accelerator_tree=None,
1031
1122
                        hardlink=False):
1032
1123
        """Create a checkout of a branch.
1033
 
        
 
1124
 
1034
1125
        :param to_location: The url to produce the checkout at
1035
1126
        :param revision_id: The revision to check out
1036
1127
        :param lightweight: If True, produce a lightweight checkout, otherwise,
1055
1146
                to_location, force_new_tree=False, format=format)
1056
1147
            checkout = checkout_branch.bzrdir
1057
1148
            checkout_branch.bind(self)
1058
 
            # pull up to the specified revision_id to set the initial 
 
1149
            # pull up to the specified revision_id to set the initial
1059
1150
            # branch tip correctly, and seed it with history.
1060
1151
            checkout_branch.pull(self, stop_revision=revision_id)
1061
1152
            from_branch=None
1100
1191
        """Ensure that revision_b is a descendant of revision_a.
1101
1192
 
1102
1193
        This is a helper function for update_revisions.
1103
 
        
 
1194
 
1104
1195
        :raises: DivergedBranches if revision_b has diverged from revision_a.
1105
1196
        :returns: True if revision_b is a descendant of revision_a.
1106
1197
        """
1116
1207
 
1117
1208
    def _revision_relations(self, revision_a, revision_b, graph):
1118
1209
        """Determine the relationship between two revisions.
1119
 
        
 
1210
 
1120
1211
        :returns: One of: 'a_descends_from_b', 'b_descends_from_a', 'diverged'
1121
1212
        """
1122
1213
        heads = graph.heads([revision_a, revision_b])
1139
1230
     * a format string,
1140
1231
     * an open routine.
1141
1232
 
1142
 
    Formats are placed in an dict by their format string for reference 
 
1233
    Formats are placed in an dict by their format string for reference
1143
1234
    during branch opening. Its not required that these be instances, they
1144
 
    can be classes themselves with class methods - it simply depends on 
 
1235
    can be classes themselves with class methods - it simply depends on
1145
1236
    whether state is needed for a given format or not.
1146
1237
 
1147
1238
    Once a format is deprecated, just deprecate the initialize and open
1148
 
    methods on the format class. Do not deprecate the object, as the 
 
1239
    methods on the format class. Do not deprecate the object, as the
1149
1240
    object will be created every time regardless.
1150
1241
    """
1151
1242
 
1253
1344
        """Is this format supported?
1254
1345
 
1255
1346
        Supported formats can be initialized and opened.
1256
 
        Unsupported formats may not support initialization or committing or 
 
1347
        Unsupported formats may not support initialization or committing or
1257
1348
        some other features depending on the reason for not being supported.
1258
1349
        """
1259
1350
        return True
1260
1351
 
1261
 
    def open(self, a_bzrdir, _found=False):
 
1352
    def make_tags(self, branch):
 
1353
        """Create a tags object for branch.
 
1354
 
 
1355
        This method is on BranchFormat, because BranchFormats are reflected
 
1356
        over the wire via network_name(), whereas full Branch instances require
 
1357
        multiple VFS method calls to operate at all.
 
1358
 
 
1359
        The default implementation returns a disabled-tags instance.
 
1360
 
 
1361
        Note that it is normal for branch to be a RemoteBranch when using tags
 
1362
        on a RemoteBranch.
 
1363
        """
 
1364
        return DisabledTags(branch)
 
1365
 
 
1366
    def network_name(self):
 
1367
        """A simple byte string uniquely identifying this format for RPC calls.
 
1368
 
 
1369
        MetaDir branch formats use their disk format string to identify the
 
1370
        repository over the wire. All in one formats such as bzr < 0.8, and
 
1371
        foreign formats like svn/git and hg should use some marker which is
 
1372
        unique and immutable.
 
1373
        """
 
1374
        raise NotImplementedError(self.network_name)
 
1375
 
 
1376
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
1262
1377
        """Return the branch object for a_bzrdir
1263
1378
 
1264
 
        _found is a private parameter, do not use it. It is used to indicate
1265
 
               if format probing has already be done.
 
1379
        :param a_bzrdir: A BzrDir that contains a branch.
 
1380
        :param _found: a private parameter, do not use it. It is used to
 
1381
            indicate if format probing has already be done.
 
1382
        :param ignore_fallbacks: when set, no fallback branches will be opened
 
1383
            (if there are any).  Default is to open fallbacks.
1266
1384
        """
1267
1385
        raise NotImplementedError(self.open)
1268
1386
 
1269
1387
    @classmethod
1270
1388
    def register_format(klass, format):
 
1389
        """Register a metadir format."""
1271
1390
        klass._formats[format.get_format_string()] = format
 
1391
        # Metadir formats have a network name of their format string, and get
 
1392
        # registered as class factories.
 
1393
        network_format_registry.register(format.get_format_string(), format.__class__)
1272
1394
 
1273
1395
    @classmethod
1274
1396
    def set_default_format(klass, format):
1283
1405
        del klass._formats[format.get_format_string()]
1284
1406
 
1285
1407
    def __str__(self):
1286
 
        return self.get_format_string().rstrip()
 
1408
        return self.get_format_description().rstrip()
1287
1409
 
1288
1410
    def supports_tags(self):
1289
1411
        """True if this format supports tags stored in the branch"""
1292
1414
 
1293
1415
class BranchHooks(Hooks):
1294
1416
    """A dictionary mapping hook name to a list of callables for branch hooks.
1295
 
    
 
1417
 
1296
1418
    e.g. ['set_rh'] Is the list of items to be called when the
1297
1419
    set_revision_history function is invoked.
1298
1420
    """
1304
1426
        notified.
1305
1427
        """
1306
1428
        Hooks.__init__(self)
1307
 
        # Introduced in 0.15:
1308
 
        # invoked whenever the revision history has been set
1309
 
        # with set_revision_history. The api signature is
1310
 
        # (branch, revision_history), and the branch will
1311
 
        # be write-locked.
1312
 
        self['set_rh'] = []
1313
 
        # Invoked after a branch is opened. The api signature is (branch).
1314
 
        self['open'] = []
1315
 
        # invoked after a push operation completes.
1316
 
        # the api signature is
1317
 
        # (push_result)
1318
 
        # containing the members
1319
 
        # (source, local, master, old_revno, old_revid, new_revno, new_revid)
1320
 
        # where local is the local target branch or None, master is the target 
1321
 
        # master branch, and the rest should be self explanatory. The source
1322
 
        # is read locked and the target branches write locked. Source will
1323
 
        # be the local low-latency branch.
1324
 
        self['post_push'] = []
1325
 
        # invoked after a pull operation completes.
1326
 
        # the api signature is
1327
 
        # (pull_result)
1328
 
        # containing the members
1329
 
        # (source, local, master, old_revno, old_revid, new_revno, new_revid)
1330
 
        # where local is the local branch or None, master is the target 
1331
 
        # master branch, and the rest should be self explanatory. The source
1332
 
        # is read locked and the target branches write locked. The local
1333
 
        # branch is the low-latency branch.
1334
 
        self['post_pull'] = []
1335
 
        # invoked before a commit operation takes place.
1336
 
        # the api signature is
1337
 
        # (local, master, old_revno, old_revid, future_revno, future_revid,
1338
 
        #  tree_delta, future_tree).
1339
 
        # old_revid is NULL_REVISION for the first commit to a branch
1340
 
        # tree_delta is a TreeDelta object describing changes from the basis
1341
 
        # revision, hooks MUST NOT modify this delta
1342
 
        # future_tree is an in-memory tree obtained from
1343
 
        # CommitBuilder.revision_tree() and hooks MUST NOT modify this tree
1344
 
        self['pre_commit'] = []
1345
 
        # invoked after a commit operation completes.
1346
 
        # the api signature is 
1347
 
        # (local, master, old_revno, old_revid, new_revno, new_revid)
1348
 
        # old_revid is NULL_REVISION for the first commit to a branch.
1349
 
        self['post_commit'] = []
1350
 
        # invoked after a uncommit operation completes.
1351
 
        # the api signature is
1352
 
        # (local, master, old_revno, old_revid, new_revno, new_revid) where
1353
 
        # local is the local branch or None, master is the target branch,
1354
 
        # and an empty branch receives new_revno of 0, new_revid of None.
1355
 
        self['post_uncommit'] = []
1356
 
        # Introduced in 1.6
1357
 
        # Invoked before the tip of a branch changes.
1358
 
        # the api signature is
1359
 
        # (params) where params is a ChangeBranchTipParams with the members
1360
 
        # (branch, old_revno, new_revno, old_revid, new_revid)
1361
 
        self['pre_change_branch_tip'] = []
1362
 
        # Introduced in 1.4
1363
 
        # Invoked after the tip of a branch changes.
1364
 
        # the api signature is
1365
 
        # (params) where params is a ChangeBranchTipParams with the members
1366
 
        # (branch, old_revno, new_revno, old_revid, new_revid)
1367
 
        self['post_change_branch_tip'] = []
1368
 
        # Introduced in 1.9
1369
 
        # Invoked when a stacked branch activates its fallback locations and
1370
 
        # allows the transformation of the url of said location.
1371
 
        # the api signature is
1372
 
        # (branch, url) where branch is the branch having its fallback
1373
 
        # location activated and url is the url for the fallback location.
1374
 
        # The hook should return a url.
1375
 
        self['transform_fallback_location'] = []
 
1429
        self.create_hook(HookPoint('set_rh',
 
1430
            "Invoked whenever the revision history has been set via "
 
1431
            "set_revision_history. The api signature is (branch, "
 
1432
            "revision_history), and the branch will be write-locked. "
 
1433
            "The set_rh hook can be expensive for bzr to trigger, a better "
 
1434
            "hook to use is Branch.post_change_branch_tip.", (0, 15), None))
 
1435
        self.create_hook(HookPoint('open',
 
1436
            "Called with the Branch object that has been opened after a "
 
1437
            "branch is opened.", (1, 8), None))
 
1438
        self.create_hook(HookPoint('post_push',
 
1439
            "Called after a push operation completes. post_push is called "
 
1440
            "with a bzrlib.branch.BranchPushResult object and only runs in the "
 
1441
            "bzr client.", (0, 15), None))
 
1442
        self.create_hook(HookPoint('post_pull',
 
1443
            "Called after a pull operation completes. post_pull is called "
 
1444
            "with a bzrlib.branch.PullResult object and only runs in the "
 
1445
            "bzr client.", (0, 15), None))
 
1446
        self.create_hook(HookPoint('pre_commit',
 
1447
            "Called after a commit is calculated but before it is is "
 
1448
            "completed. pre_commit is called with (local, master, old_revno, "
 
1449
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
 
1450
            "). old_revid is NULL_REVISION for the first commit to a branch, "
 
1451
            "tree_delta is a TreeDelta object describing changes from the "
 
1452
            "basis revision. hooks MUST NOT modify this delta. "
 
1453
            " future_tree is an in-memory tree obtained from "
 
1454
            "CommitBuilder.revision_tree() and hooks MUST NOT modify this "
 
1455
            "tree.", (0,91), None))
 
1456
        self.create_hook(HookPoint('post_commit',
 
1457
            "Called in the bzr client after a commit has completed. "
 
1458
            "post_commit is called with (local, master, old_revno, old_revid, "
 
1459
            "new_revno, new_revid). old_revid is NULL_REVISION for the first "
 
1460
            "commit to a branch.", (0, 15), None))
 
1461
        self.create_hook(HookPoint('post_uncommit',
 
1462
            "Called in the bzr client after an uncommit completes. "
 
1463
            "post_uncommit is called with (local, master, old_revno, "
 
1464
            "old_revid, new_revno, new_revid) where local is the local branch "
 
1465
            "or None, master is the target branch, and an empty branch "
 
1466
            "receives new_revno of 0, new_revid of None.", (0, 15), None))
 
1467
        self.create_hook(HookPoint('pre_change_branch_tip',
 
1468
            "Called in bzr client and server before a change to the tip of a "
 
1469
            "branch is made. pre_change_branch_tip is called with a "
 
1470
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
 
1471
            "commit, uncommit will all trigger this hook.", (1, 6), None))
 
1472
        self.create_hook(HookPoint('post_change_branch_tip',
 
1473
            "Called in bzr client and server after a change to the tip of a "
 
1474
            "branch is made. post_change_branch_tip is called with a "
 
1475
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
 
1476
            "commit, uncommit will all trigger this hook.", (1, 4), None))
 
1477
        self.create_hook(HookPoint('transform_fallback_location',
 
1478
            "Called when a stacked branch is activating its fallback "
 
1479
            "locations. transform_fallback_location is called with (branch, "
 
1480
            "url), and should return a new url. Returning the same url "
 
1481
            "allows it to be used as-is, returning a different one can be "
 
1482
            "used to cause the branch to stack on a closer copy of that "
 
1483
            "fallback_location. Note that the branch cannot have history "
 
1484
            "accessing methods called on it during this hook because the "
 
1485
            "fallback locations have not been activated. When there are "
 
1486
            "multiple hooks installed for transform_fallback_location, "
 
1487
            "all are called with the url returned from the previous hook."
 
1488
            "The order is however undefined.", (1, 9), None))
1376
1489
 
1377
1490
 
1378
1491
# install the default hooks into the Branch class.
1410
1523
 
1411
1524
    def __eq__(self, other):
1412
1525
        return self.__dict__ == other.__dict__
1413
 
    
 
1526
 
1414
1527
    def __repr__(self):
1415
1528
        return "<%s of %s from (%s, %s) to (%s, %s)>" % (
1416
 
            self.__class__.__name__, self.branch, 
 
1529
            self.__class__.__name__, self.branch,
1417
1530
            self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1418
1531
 
1419
1532
 
1441
1554
        super(BzrBranchFormat4, self).__init__()
1442
1555
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
1443
1556
 
1444
 
    def open(self, a_bzrdir, _found=False):
1445
 
        """Return the branch object for a_bzrdir
 
1557
    def network_name(self):
 
1558
        """The network name for this format is the control dirs disk label."""
 
1559
        return self._matchingbzrdir.get_format_string()
1446
1560
 
1447
 
        _found is a private parameter, do not use it. It is used to indicate
1448
 
               if format probing has already be done.
1449
 
        """
 
1561
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
 
1562
        """See BranchFormat.open()."""
1450
1563
        if not _found:
1451
1564
            # we are being called directly and must probe.
1452
1565
            raise NotImplementedError
1466
1579
        """What class to instantiate on open calls."""
1467
1580
        raise NotImplementedError(self._branch_class)
1468
1581
 
1469
 
    def open(self, a_bzrdir, _found=False):
1470
 
        """Return the branch object for a_bzrdir.
 
1582
    def network_name(self):
 
1583
        """A simple byte string uniquely identifying this format for RPC calls.
1471
1584
 
1472
 
        _found is a private parameter, do not use it. It is used to indicate
1473
 
               if format probing has already be done.
 
1585
        Metadir branch formats use their format string.
1474
1586
        """
 
1587
        return self.get_format_string()
 
1588
 
 
1589
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
 
1590
        """See BranchFormat.open()."""
1475
1591
        if not _found:
1476
1592
            format = BranchFormat.find_format(a_bzrdir)
1477
1593
            if format.__class__ != self.__class__:
1484
1600
            return self._branch_class()(_format=self,
1485
1601
                              _control_files=control_files,
1486
1602
                              a_bzrdir=a_bzrdir,
1487
 
                              _repository=a_bzrdir.find_repository())
 
1603
                              _repository=a_bzrdir.find_repository(),
 
1604
                              ignore_fallbacks=ignore_fallbacks)
1488
1605
        except errors.NoSuchFile:
1489
1606
            raise errors.NotBranchError(path=transport.base)
1490
1607
 
1520
1637
    def get_format_description(self):
1521
1638
        """See BranchFormat.get_format_description()."""
1522
1639
        return "Branch format 5"
1523
 
        
 
1640
 
1524
1641
    def initialize(self, a_bzrdir):
1525
1642
        """Create a branch of this format in a_bzrdir."""
1526
1643
        utf8_files = [('revision-history', ''),
1562
1679
                      ]
1563
1680
        return self._initialize_helper(a_bzrdir, utf8_files)
1564
1681
 
 
1682
    def make_tags(self, branch):
 
1683
        """See bzrlib.branch.BranchFormat.make_tags()."""
 
1684
        return BasicTags(branch)
 
1685
 
 
1686
 
1565
1687
 
1566
1688
class BzrBranchFormat7(BranchFormatMetadir):
1567
1689
    """Branch format with last-revision, tags, and a stacked location pointer.
1596
1718
        self._matchingbzrdir.repository_format = \
1597
1719
            RepositoryFormatKnitPack5RichRoot()
1598
1720
 
 
1721
    def make_tags(self, branch):
 
1722
        """See bzrlib.branch.BranchFormat.make_tags()."""
 
1723
        return BasicTags(branch)
 
1724
 
1599
1725
    def supports_stacking(self):
1600
1726
        return True
1601
1727
 
1651
1777
 
1652
1778
    def _make_reference_clone_function(format, a_branch):
1653
1779
        """Create a clone() routine for a branch dynamically."""
1654
 
        def clone(to_bzrdir, revision_id=None):
 
1780
        def clone(to_bzrdir, revision_id=None,
 
1781
            repository_policy=None):
1655
1782
            """See Branch.clone()."""
1656
1783
            return format.initialize(to_bzrdir, a_branch)
1657
1784
            # cannot obey revision_id limits when cloning a reference ...
1660
1787
        return clone
1661
1788
 
1662
1789
    def open(self, a_bzrdir, _found=False, location=None,
1663
 
             possible_transports=None):
 
1790
             possible_transports=None, ignore_fallbacks=False):
1664
1791
        """Return the branch that the branch reference in a_bzrdir points at.
1665
1792
 
1666
 
        _found is a private parameter, do not use it. It is used to indicate
1667
 
               if format probing has already be done.
 
1793
        :param a_bzrdir: A BzrDir that contains a branch.
 
1794
        :param _found: a private parameter, do not use it. It is used to
 
1795
            indicate if format probing has already be done.
 
1796
        :param ignore_fallbacks: when set, no fallback branches will be opened
 
1797
            (if there are any).  Default is to open fallbacks.
 
1798
        :param location: The location of the referenced branch.  If
 
1799
            unspecified, this will be determined from the branch reference in
 
1800
            a_bzrdir.
 
1801
        :param possible_transports: An optional reusable transports list.
1668
1802
        """
1669
1803
        if not _found:
1670
1804
            format = BranchFormat.find_format(a_bzrdir)
1675
1809
            location = self.get_reference(a_bzrdir)
1676
1810
        real_bzrdir = bzrdir.BzrDir.open(
1677
1811
            location, possible_transports=possible_transports)
1678
 
        result = real_bzrdir.open_branch()
 
1812
        result = real_bzrdir.open_branch(ignore_fallbacks=ignore_fallbacks)
1679
1813
        # this changes the behaviour of result.clone to create a new reference
1680
1814
        # rather than a copy of the content of the branch.
1681
1815
        # I did not use a proxy object because that needs much more extensive
1688
1822
        return result
1689
1823
 
1690
1824
 
 
1825
network_format_registry = registry.FormatRegistry()
 
1826
"""Registry of formats indexed by their network name.
 
1827
 
 
1828
The network name for a branch format is an identifier that can be used when
 
1829
referring to formats with smart server operations. See
 
1830
BranchFormat.network_name() for more detail.
 
1831
"""
 
1832
 
 
1833
 
1691
1834
# formats which have no format string are not discoverable
1692
1835
# and not independently creatable, so are not registered.
1693
1836
__format5 = BzrBranchFormat5()
1699
1842
BranchFormat.register_format(__format7)
1700
1843
BranchFormat.set_default_format(__format6)
1701
1844
_legacy_formats = [BzrBranchFormat4(),
1702
 
                   ]
 
1845
    ]
 
1846
network_format_registry.register(
 
1847
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
 
1848
 
1703
1849
 
1704
1850
class BzrBranch(Branch):
1705
1851
    """A branch stored in the actual filesystem.
1708
1854
    really matter if it's on an nfs/smb/afs/coda/... share, as long as
1709
1855
    it's writable, and can be accessed via the normal filesystem API.
1710
1856
 
1711
 
    :ivar _transport: Transport for file operations on this branch's 
 
1857
    :ivar _transport: Transport for file operations on this branch's
1712
1858
        control files, typically pointing to the .bzr/branch directory.
1713
1859
    :ivar repository: Repository for this branch.
1714
 
    :ivar base: The url of the base directory for this branch; the one 
 
1860
    :ivar base: The url of the base directory for this branch; the one
1715
1861
        containing the .bzr directory.
1716
1862
    """
1717
 
    
 
1863
 
1718
1864
    def __init__(self, _format=None,
1719
 
                 _control_files=None, a_bzrdir=None, _repository=None):
 
1865
                 _control_files=None, a_bzrdir=None, _repository=None,
 
1866
                 ignore_fallbacks=False):
1720
1867
        """Create new branch object at a particular location."""
1721
1868
        if a_bzrdir is None:
1722
1869
            raise ValueError('a_bzrdir must be supplied')
1745
1892
 
1746
1893
    base = property(_get_base, doc="The URL for the root of this branch.")
1747
1894
 
 
1895
    def _get_config(self):
 
1896
        return TransportConfig(self._transport, 'branch.conf')
 
1897
 
1748
1898
    def is_locked(self):
1749
1899
        return self.control_files.is_locked()
1750
1900
 
1774
1924
        if not self.control_files.is_locked():
1775
1925
            # we just released the lock
1776
1926
            self._clear_cached_state()
1777
 
        
 
1927
 
1778
1928
    def peek_lock_mode(self):
1779
1929
        if self.control_files._lock_count == 0:
1780
1930
            return None
1860
2010
        for this revision id.
1861
2011
 
1862
2012
        It may be possible to set the branch last revision to an id not
1863
 
        present in the repository.  However, branches can also be 
 
2013
        present in the repository.  However, branches can also be
1864
2014
        configured to check constraints on history, in which case this may not
1865
2015
        be permitted.
1866
2016
        """
1904
2054
             _override_hook_target=None):
1905
2055
        """See Branch.pull.
1906
2056
 
1907
 
        :param _hook_master: Private parameter - set the branch to 
 
2057
        :param _hook_master: Private parameter - set the branch to
1908
2058
            be supplied as the master to pull hooks.
1909
2059
        :param run_hooks: Private parameter - if false, this branch
1910
2060
            is being called because it's the master of the primary branch,
1958
2108
        This is the basic concrete implementation of push()
1959
2109
 
1960
2110
        :param _override_hook_source_branch: If specified, run
1961
 
        the hooks passing this Branch as the source, rather than self.  
 
2111
        the hooks passing this Branch as the source, rather than self.
1962
2112
        This is for use of RemoteBranch, where push is delegated to the
1963
 
        underlying vfs-based Branch. 
 
2113
        underlying vfs-based Branch.
1964
2114
        """
1965
2115
        # TODO: Public option to disable running hooks - should be trivial but
1966
2116
        # needs tests.
1973
2123
            stop_revision,
1974
2124
            _override_hook_source_branch=None):
1975
2125
        """Push from self into target, and into target's master if any.
1976
 
        
1977
 
        This is on the base BzrBranch class even though it doesn't support 
 
2126
 
 
2127
        This is on the base BzrBranch class even though it doesn't support
1978
2128
        bound branches because the *target* might be bound.
1979
2129
        """
1980
2130
        def _run_hooks():
2020
2170
 
2021
2171
        Must be called with self read locked and target write locked.
2022
2172
        """
2023
 
        result = PushResult()
 
2173
        result = BranchPushResult()
2024
2174
        result.source_branch = self
2025
2175
        result.target_branch = target
2026
2176
        result.old_revno, result.old_revid = target.last_revision_info()
2035
2185
        result.new_revno, result.new_revid = target.last_revision_info()
2036
2186
        return result
2037
2187
 
2038
 
    def _push_should_merge_tags(self):
2039
 
        """Should _basic_push merge this branch's tags into the target?
2040
 
        
2041
 
        The default implementation returns False if this branch has no tags,
2042
 
        and True the rest of the time.  Subclasses may override this.
2043
 
        """
2044
 
        return self.tags.supports_tags() and self.tags.get_tag_dict()
2045
 
 
2046
 
    def get_parent(self):
2047
 
        """See Branch.get_parent."""
2048
 
        parent = self._get_parent_location()
2049
 
        if parent is None:
2050
 
            return parent
2051
 
        # This is an old-format absolute path to a local branch
2052
 
        # turn it into a url
2053
 
        if parent.startswith('/'):
2054
 
            parent = urlutils.local_path_to_url(parent.decode('utf8'))
2055
 
        try:
2056
 
            return urlutils.join(self.base[:-1], parent)
2057
 
        except errors.InvalidURLJoin, e:
2058
 
            raise errors.InaccessibleParent(parent, self.base)
2059
 
 
2060
2188
    def get_stacked_on_url(self):
2061
2189
        raise errors.UnstackableBranchFormat(self._format, self.base)
2062
2190
 
2091
2219
            self._transport.put_bytes('parent', url + '\n',
2092
2220
                mode=self.bzrdir._get_file_mode())
2093
2221
 
2094
 
    def set_stacked_on_url(self, url):
2095
 
        raise errors.UnstackableBranchFormat(self._format, self.base)
2096
 
 
2097
2222
 
2098
2223
class BzrBranch5(BzrBranch):
2099
2224
    """A format 5 branch. This supports new features over plain branches.
2106
2231
             run_hooks=True, possible_transports=None,
2107
2232
             _override_hook_target=None):
2108
2233
        """Pull from source into self, updating my master if any.
2109
 
        
 
2234
 
2110
2235
        :param run_hooks: Private parameter - if false, this branch
2111
2236
            is being called because it's the master of the primary branch,
2112
2237
            so it should not run its hooks.
2139
2264
    @needs_read_lock
2140
2265
    def get_master_branch(self, possible_transports=None):
2141
2266
        """Return the branch we are bound to.
2142
 
        
 
2267
 
2143
2268
        :return: Either a Branch, or None
2144
2269
 
2145
2270
        This could memoise the branch, but if thats done
2181
2306
        check for divergence to raise an error when the branches are not
2182
2307
        either the same, or one a prefix of the other. That behaviour may not
2183
2308
        be useful, so that check may be removed in future.
2184
 
        
 
2309
 
2185
2310
        :param other: The branch to bind to
2186
2311
        :type other: Branch
2187
2312
        """
2206
2331
 
2207
2332
    @needs_write_lock
2208
2333
    def update(self, possible_transports=None):
2209
 
        """Synchronise this branch with the master branch if any. 
 
2334
        """Synchronise this branch with the master branch if any.
2210
2335
 
2211
2336
        :return: None or the last_revision that was pivoted out during the
2212
2337
                 update.
2225
2350
class BzrBranch7(BzrBranch5):
2226
2351
    """A branch with support for a fallback repository."""
2227
2352
 
2228
 
    def _get_fallback_repository(self, url):
2229
 
        """Get the repository we fallback to at url."""
2230
 
        url = urlutils.join(self.base, url)
2231
 
        a_bzrdir = bzrdir.BzrDir.open(url,
2232
 
                                      possible_transports=[self._transport])
2233
 
        return a_bzrdir.open_branch().repository
2234
 
 
2235
 
    def _activate_fallback_location(self, url):
2236
 
        """Activate the branch/repository from url as a fallback repository."""
2237
 
        self.repository.add_fallback_repository(
2238
 
            self._get_fallback_repository(url))
2239
 
 
2240
2353
    def _open_hook(self):
 
2354
        if self._ignore_fallbacks:
 
2355
            return
2241
2356
        try:
2242
2357
            url = self.get_stacked_on_url()
2243
2358
        except (errors.UnstackableRepositoryFormat, errors.NotStacked,
2253
2368
                        "None, not a URL." % hook_name)
2254
2369
            self._activate_fallback_location(url)
2255
2370
 
2256
 
    def _check_stackable_repo(self):
2257
 
        if not self.repository._format.supports_external_lookups:
2258
 
            raise errors.UnstackableRepositoryFormat(self.repository._format,
2259
 
                self.repository.base)
2260
 
 
2261
2371
    def __init__(self, *args, **kwargs):
 
2372
        self._ignore_fallbacks = kwargs.get('ignore_fallbacks', False)
2262
2373
        super(BzrBranch7, self).__init__(*args, **kwargs)
2263
2374
        self._last_revision_info_cache = None
2264
2375
        self._partial_revision_history_cache = []
2303
2414
 
2304
2415
    def _synchronize_history(self, destination, revision_id):
2305
2416
        """Synchronize last revision and revision history between branches.
2306
 
        
 
2417
 
2307
2418
        :see: Branch._synchronize_history
2308
2419
        """
2309
2420
        # XXX: The base Branch has a fast implementation of this method based
2437
2548
        self.get_config().set_user_option('append_revisions_only', value,
2438
2549
            warn_masked=True)
2439
2550
 
2440
 
    def set_stacked_on_url(self, url):
2441
 
        self._check_stackable_repo()
2442
 
        if not url:
2443
 
            try:
2444
 
                old_url = self.get_stacked_on_url()
2445
 
            except (errors.NotStacked, errors.UnstackableBranchFormat,
2446
 
                errors.UnstackableRepositoryFormat):
2447
 
                return
2448
 
            url = ''
2449
 
            # repositories don't offer an interface to remove fallback
2450
 
            # repositories today; take the conceptually simpler option and just
2451
 
            # reopen it.
2452
 
            self.repository = self.bzrdir.find_repository()
2453
 
            # for every revision reference the branch has, ensure it is pulled
2454
 
            # in.
2455
 
            source_repository = self._get_fallback_repository(old_url)
2456
 
            for revision_id in chain([self.last_revision()],
2457
 
                self.tags.get_reverse_tag_dict()):
2458
 
                self.repository.fetch(source_repository, revision_id,
2459
 
                    find_ghosts=True)
2460
 
        else:
2461
 
            self._activate_fallback_location(url)
2462
 
        # write this out after the repository is stacked to avoid setting a
2463
 
        # stacked config that doesn't work.
2464
 
        self._set_config_location('stacked_on_location', url)
2465
 
 
2466
2551
    def _get_append_revisions_only(self):
2467
2552
        value = self.get_config().get_user_option('append_revisions_only')
2468
2553
        return value == 'True'
2469
2554
 
2470
 
    def _make_tags(self):
2471
 
        return BasicTags(self)
2472
 
 
2473
2555
    @needs_write_lock
2474
2556
    def generate_revision_history(self, revision_id, last_rev=None,
2475
2557
                                  other_branch=None):
2524
2606
    def get_stacked_on_url(self):
2525
2607
        raise errors.UnstackableBranchFormat(self._format, self.base)
2526
2608
 
2527
 
    def set_stacked_on_url(self, url):
2528
 
        raise errors.UnstackableBranchFormat(self._format, self.base)
2529
 
 
2530
2609
 
2531
2610
######################################################################
2532
2611
# results of operations
2549
2628
    :ivar new_revno: Revision number after pull.
2550
2629
    :ivar old_revid: Tip revision id before pull.
2551
2630
    :ivar new_revid: Tip revision id after pull.
2552
 
    :ivar source_branch: Source (local) branch object.
 
2631
    :ivar source_branch: Source (local) branch object. (read locked)
2553
2632
    :ivar master_branch: Master branch of the target, or the target if no
2554
2633
        Master
2555
2634
    :ivar local_branch: target branch if there is a Master, else None
2556
 
    :ivar target_branch: Target/destination branch object.
 
2635
    :ivar target_branch: Target/destination branch object. (write locked)
2557
2636
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
2558
2637
    """
2559
2638
 
2570
2649
        self._show_tag_conficts(to_file)
2571
2650
 
2572
2651
 
2573
 
class PushResult(_Result):
 
2652
class BranchPushResult(_Result):
2574
2653
    """Result of a Branch.push operation.
2575
2654
 
2576
 
    :ivar old_revno: Revision number before push.
2577
 
    :ivar new_revno: Revision number after push.
2578
 
    :ivar old_revid: Tip revision id before push.
2579
 
    :ivar new_revid: Tip revision id after push.
2580
 
    :ivar source_branch: Source branch object.
2581
 
    :ivar master_branch: Master branch of the target, or None.
2582
 
    :ivar target_branch: Target/destination branch object.
 
2655
    :ivar old_revno: Revision number (eg 10) of the target before push.
 
2656
    :ivar new_revno: Revision number (eg 12) of the target after push.
 
2657
    :ivar old_revid: Tip revision id (eg joe@foo.com-1234234-aoeua34) of target
 
2658
        before the push.
 
2659
    :ivar new_revid: Tip revision id (eg joe@foo.com-5676566-boa234a) of target
 
2660
        after the push.
 
2661
    :ivar source_branch: Source branch object that the push was from. This is
 
2662
        read locked, and generally is a local (and thus low latency) branch.
 
2663
    :ivar master_branch: If target is a bound branch, the master branch of
 
2664
        target, or target itself. Always write locked.
 
2665
    :ivar target_branch: The direct Branch where data is being sent (write
 
2666
        locked).
 
2667
    :ivar local_branch: If the target is a bound branch this will be the
 
2668
        target, otherwise it will be None.
2583
2669
    """
2584
2670
 
2585
2671
    def __int__(self):
2589
2675
    def report(self, to_file):
2590
2676
        """Write a human-readable description of the result."""
2591
2677
        if self.old_revid == self.new_revid:
2592
 
            to_file.write('No new revisions to push.\n')
 
2678
            note('No new revisions to push.')
2593
2679
        else:
2594
 
            to_file.write('Pushed up to revision %d.\n' % self.new_revno)
 
2680
            note('Pushed up to revision %d.' % self.new_revno)
2595
2681
        self._show_tag_conficts(to_file)
2596
2682
 
2597
2683
 
2606
2692
 
2607
2693
    def report_results(self, verbose):
2608
2694
        """Report the check results via trace.note.
2609
 
        
 
2695
 
2610
2696
        :param verbose: Requests more detailed display of what was checked,
2611
2697
            if any.
2612
2698
        """
2672
2758
            return callable(*args, **kwargs)
2673
2759
        finally:
2674
2760
            target.unlock()
2675
 
    
 
2761
 
2676
2762
    """
2677
2763
    # This is very similar to bzrlib.decorators.needs_write_lock.  Perhaps they
2678
2764
    # should share code?
2688
2774
    else:
2689
2775
        target.unlock()
2690
2776
        return result
 
2777
 
 
2778
 
 
2779
class InterBranch(InterObject):
 
2780
    """This class represents operations taking place between two branches.
 
2781
 
 
2782
    Its instances have methods like pull() and push() and contain
 
2783
    references to the source and target repositories these operations
 
2784
    can be carried out on.
 
2785
    """
 
2786
 
 
2787
    _optimisers = []
 
2788
    """The available optimised InterBranch types."""
 
2789
 
 
2790
    @staticmethod
 
2791
    def _get_branch_formats_to_test():
 
2792
        """Return a tuple with the Branch formats to use when testing."""
 
2793
        raise NotImplementedError(self._get_branch_formats_to_test)
 
2794
 
 
2795
    def update_revisions(self, stop_revision=None, overwrite=False,
 
2796
                         graph=None):
 
2797
        """Pull in new perfect-fit revisions.
 
2798
 
 
2799
        :param stop_revision: Updated until the given revision
 
2800
        :param overwrite: Always set the branch pointer, rather than checking
 
2801
            to see if it is a proper descendant.
 
2802
        :param graph: A Graph object that can be used to query history
 
2803
            information. This can be None.
 
2804
        :return: None
 
2805
        """
 
2806
        raise NotImplementedError(self.update_revisions)
 
2807
 
 
2808
 
 
2809
class GenericInterBranch(InterBranch):
 
2810
    """InterBranch implementation that uses public Branch functions.
 
2811
    """
 
2812
 
 
2813
    @staticmethod
 
2814
    def _get_branch_formats_to_test():
 
2815
        return BranchFormat._default_format, BranchFormat._default_format
 
2816
 
 
2817
    def update_revisions(self, stop_revision=None, overwrite=False,
 
2818
        graph=None):
 
2819
        """See InterBranch.update_revisions()."""
 
2820
        self.source.lock_read()
 
2821
        try:
 
2822
            other_revno, other_last_revision = self.source.last_revision_info()
 
2823
            stop_revno = None # unknown
 
2824
            if stop_revision is None:
 
2825
                stop_revision = other_last_revision
 
2826
                if _mod_revision.is_null(stop_revision):
 
2827
                    # if there are no commits, we're done.
 
2828
                    return
 
2829
                stop_revno = other_revno
 
2830
 
 
2831
            # what's the current last revision, before we fetch [and change it
 
2832
            # possibly]
 
2833
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
2834
            # we fetch here so that we don't process data twice in the common
 
2835
            # case of having something to pull, and so that the check for
 
2836
            # already merged can operate on the just fetched graph, which will
 
2837
            # be cached in memory.
 
2838
            self.target.fetch(self.source, stop_revision)
 
2839
            # Check to see if one is an ancestor of the other
 
2840
            if not overwrite:
 
2841
                if graph is None:
 
2842
                    graph = self.target.repository.get_graph()
 
2843
                if self.target._check_if_descendant_or_diverged(
 
2844
                        stop_revision, last_rev, graph, self.source):
 
2845
                    # stop_revision is a descendant of last_rev, but we aren't
 
2846
                    # overwriting, so we're done.
 
2847
                    return
 
2848
            if stop_revno is None:
 
2849
                if graph is None:
 
2850
                    graph = self.target.repository.get_graph()
 
2851
                this_revno, this_last_revision = \
 
2852
                        self.target.last_revision_info()
 
2853
                stop_revno = graph.find_distance_to_null(stop_revision,
 
2854
                                [(other_last_revision, other_revno),
 
2855
                                 (this_last_revision, this_revno)])
 
2856
            self.target.set_last_revision_info(stop_revno, stop_revision)
 
2857
        finally:
 
2858
            self.source.unlock()
 
2859
 
 
2860
    @classmethod
 
2861
    def is_compatible(self, source, target):
 
2862
        # GenericBranch uses the public API, so always compatible
 
2863
        return True
 
2864
 
 
2865
 
 
2866
InterBranch.register_optimiser(GenericInterBranch)