~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Martin Pool
  • Date: 2010-06-02 05:03:31 UTC
  • mto: This revision was merged to the branch mainline in revision 5279.
  • Revision ID: mbp@canonical.com-20100602050331-n2p1qt8hfsahspnv
Correct more sloppy use of the term 'Linux'

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
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
 
from __future__ import absolute_import
18
 
 
19
 
import bzrlib.bzrdir
20
17
 
21
18
from cStringIO import StringIO
 
19
import sys
22
20
 
23
21
from bzrlib.lazy_import import lazy_import
24
22
lazy_import(globals(), """
25
 
import itertools
 
23
from itertools import chain
26
24
from bzrlib import (
27
 
    bzrdir,
28
 
    controldir,
29
 
    cache_utf8,
30
 
    cleanup,
31
 
    config as _mod_config,
32
 
    debug,
33
 
    errors,
34
 
    fetch,
35
 
    graph as _mod_graph,
36
 
    lockdir,
37
 
    lockable_files,
38
 
    remote,
39
 
    repository,
40
 
    revision as _mod_revision,
41
 
    rio,
42
 
    tag as _mod_tag,
43
 
    transport,
44
 
    ui,
45
 
    urlutils,
46
 
    vf_search,
 
25
        bzrdir,
 
26
        cache_utf8,
 
27
        config as _mod_config,
 
28
        debug,
 
29
        errors,
 
30
        lockdir,
 
31
        lockable_files,
 
32
        repository,
 
33
        revision as _mod_revision,
 
34
        rio,
 
35
        symbol_versioning,
 
36
        transport,
 
37
        tsort,
 
38
        ui,
 
39
        urlutils,
 
40
        )
 
41
from bzrlib.config import BranchConfig, TransportConfig
 
42
from bzrlib.repofmt.pack_repo import RepositoryFormatKnitPack5RichRoot
 
43
from bzrlib.tag import (
 
44
    BasicTags,
 
45
    DisabledTags,
47
46
    )
48
 
from bzrlib.i18n import gettext, ngettext
49
47
""")
50
48
 
51
 
# Explicitly import bzrlib.bzrdir so that the BzrProber
52
 
# is guaranteed to be registered.
53
 
import bzrlib.bzrdir
54
 
 
55
 
from bzrlib import (
56
 
    controldir,
57
 
    )
58
 
from bzrlib.decorators import (
59
 
    needs_read_lock,
60
 
    needs_write_lock,
61
 
    only_raises,
62
 
    )
63
 
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
64
51
from bzrlib.inter import InterObject
65
52
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
66
53
from bzrlib import registry
71
58
from bzrlib.trace import mutter, mutter_callsite, note, is_quiet
72
59
 
73
60
 
74
 
class Branch(controldir.ControlComponent):
 
61
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
 
62
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
 
63
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
 
64
 
 
65
 
 
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
93
84
    def user_transport(self):
94
85
        return self.bzrdir.user_transport
95
86
 
96
 
    def __init__(self, possible_transports=None):
 
87
    def __init__(self, *ignored, **ignored_too):
97
88
        self.tags = self._format.make_tags(self)
98
89
        self._revision_history_cache = None
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
 
        self._open_hook(possible_transports)
 
95
        self._open_hook()
107
96
        hooks = Branch.hooks['open']
108
97
        for hook in hooks:
109
98
            hook(self)
110
99
 
111
 
    def _open_hook(self, possible_transports):
 
100
    def _open_hook(self):
112
101
        """Called by init to allow simpler extension of the base class."""
113
102
 
114
 
    def _activate_fallback_location(self, url, possible_transports):
 
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 ControlDir.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
 
        repo = self._get_fallback_repository(url, possible_transports)
 
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)
126
108
        self.repository.add_fallback_repository(repo)
180
162
        For instance, if the branch is at URL/.bzr/branch,
181
163
        Branch.open(URL) -> a Branch instance.
182
164
        """
183
 
        control = controldir.ControlDir.open(base, _unsupported,
 
165
        control = bzrdir.BzrDir.open(base, _unsupported,
184
166
                                     possible_transports=possible_transports)
185
 
        return control.open_branch(unsupported=_unsupported,
186
 
            possible_transports=possible_transports)
 
167
        return control.open_branch(unsupported=_unsupported)
187
168
 
188
169
    @staticmethod
189
 
    def open_from_transport(transport, name=None, _unsupported=False,
190
 
            possible_transports=None):
 
170
    def open_from_transport(transport, name=None, _unsupported=False):
191
171
        """Open the branch rooted at transport"""
192
 
        control = controldir.ControlDir.open_from_transport(transport, _unsupported)
193
 
        return control.open_branch(name=name, unsupported=_unsupported,
194
 
            possible_transports=possible_transports)
 
172
        control = bzrdir.BzrDir.open_from_transport(transport, _unsupported)
 
173
        return control.open_branch(name=name, unsupported=_unsupported)
195
174
 
196
175
    @staticmethod
197
176
    def open_containing(url, possible_transports=None):
205
184
        format, UnknownFormatError or UnsupportedFormatError are raised.
206
185
        If there is one, it is returned, along with the unused portion of url.
207
186
        """
208
 
        control, relpath = controldir.ControlDir.open_containing(url,
 
187
        control, relpath = bzrdir.BzrDir.open_containing(url,
209
188
                                                         possible_transports)
210
 
        branch = control.open_branch(possible_transports=possible_transports)
211
 
        return (branch, relpath)
 
189
        return control.open_branch(), relpath
212
190
 
213
191
    def _push_should_merge_tags(self):
214
192
        """Should _basic_push merge this branch's tags into the target?
219
197
        return self.supports_tags() and self.tags.get_tag_dict()
220
198
 
221
199
    def get_config(self):
222
 
        """Get a bzrlib.config.BranchConfig for this Branch.
223
 
 
224
 
        This can then be used to get and set configuration options for the
225
 
        branch.
226
 
 
227
 
        :return: A bzrlib.config.BranchConfig.
228
 
        """
229
 
        return _mod_config.BranchConfig(self)
230
 
 
231
 
    def get_config_stack(self):
232
 
        """Get a bzrlib.config.BranchStack for this Branch.
233
 
 
234
 
        This can then be used to get and set configuration options for the
235
 
        branch.
236
 
 
237
 
        :return: A bzrlib.config.BranchStack.
238
 
        """
239
 
        return _mod_config.BranchStack(self)
 
200
        return BranchConfig(self)
240
201
 
241
202
    def _get_config(self):
242
203
        """Get the concrete config for just the config in this branch.
250
211
        """
251
212
        raise NotImplementedError(self._get_config)
252
213
 
253
 
    def _get_fallback_repository(self, url, possible_transports):
 
214
    def _get_fallback_repository(self, url):
254
215
        """Get the repository we fallback to at url."""
255
216
        url = urlutils.join(self.base, url)
256
 
        a_branch = Branch.open(url, possible_transports=possible_transports)
 
217
        a_branch = Branch.open(url,
 
218
            possible_transports=[self.bzrdir.root_transport])
257
219
        return a_branch.repository
258
220
 
259
 
    @needs_read_lock
260
221
    def _get_tags_bytes(self):
261
222
        """Get the bytes of a serialised tags dict.
262
223
 
269
230
        :return: The bytes of the tags file.
270
231
        :seealso: Branch._set_tags_bytes.
271
232
        """
272
 
        if self._tags_bytes is None:
273
 
            self._tags_bytes = self._transport.get_bytes('tags')
274
 
        return self._tags_bytes
 
233
        return self._transport.get_bytes('tags')
275
234
 
276
235
    def _get_nick(self, local=False, possible_transports=None):
277
236
        config = self.get_config()
279
238
        if not local and not config.has_explicit_nickname():
280
239
            try:
281
240
                master = self.get_master_branch(possible_transports)
282
 
                if master and self.user_url == master.user_url:
283
 
                    raise errors.RecursiveBind(self.user_url)
284
241
                if master is not None:
285
242
                    # return the master branch value
286
243
                    return master.nick
287
 
            except errors.RecursiveBind, e:
288
 
                raise e
289
244
            except errors.BzrError, e:
290
245
                # Silently fall back to local implicit nick if the master is
291
246
                # unavailable
468
423
            after. If None, the rest of history is included.
469
424
        :param stop_rule: if stop_revision_id is not None, the precise rule
470
425
            to use for termination:
471
 
 
472
426
            * 'exclude' - leave the stop revision out of the result (default)
473
427
            * 'include' - the stop revision is the last item in the result
474
428
            * 'with-merges' - include the stop revision and all of its
476
430
            * 'with-merges-without-common-ancestry' - filter out revisions 
477
431
              that are in both ancestries
478
432
        :param direction: either 'reverse' or 'forward':
479
 
 
480
433
            * reverse means return the start_revision_id first, i.e.
481
434
              start at the most recent revision and go backwards in history
482
435
            * forward returns tuples in the opposite order to reverse.
526
479
        rev_iter = iter(merge_sorted_revisions)
527
480
        if start_revision_id is not None:
528
481
            for node in rev_iter:
529
 
                rev_id = node.key
 
482
                rev_id = node.key[-1]
530
483
                if rev_id != start_revision_id:
531
484
                    continue
532
485
                else:
533
486
                    # The decision to include the start or not
534
487
                    # depends on the stop_rule if a stop is provided
535
488
                    # so pop this node back into the iterator
536
 
                    rev_iter = itertools.chain(iter([node]), rev_iter)
 
489
                    rev_iter = chain(iter([node]), rev_iter)
537
490
                    break
538
491
        if stop_revision_id is None:
539
492
            # Yield everything
540
493
            for node in rev_iter:
541
 
                rev_id = node.key
 
494
                rev_id = node.key[-1]
542
495
                yield (rev_id, node.merge_depth, node.revno,
543
496
                       node.end_of_merge)
544
497
        elif stop_rule == 'exclude':
545
498
            for node in rev_iter:
546
 
                rev_id = node.key
 
499
                rev_id = node.key[-1]
547
500
                if rev_id == stop_revision_id:
548
501
                    return
549
502
                yield (rev_id, node.merge_depth, node.revno,
550
503
                       node.end_of_merge)
551
504
        elif stop_rule == 'include':
552
505
            for node in rev_iter:
553
 
                rev_id = node.key
 
506
                rev_id = node.key[-1]
554
507
                yield (rev_id, node.merge_depth, node.revno,
555
508
                       node.end_of_merge)
556
509
                if rev_id == stop_revision_id:
562
515
            ancestors = graph.find_unique_ancestors(start_revision_id,
563
516
                                                    [stop_revision_id])
564
517
            for node in rev_iter:
565
 
                rev_id = node.key
 
518
                rev_id = node.key[-1]
566
519
                if rev_id not in ancestors:
567
520
                    continue
568
521
                yield (rev_id, node.merge_depth, node.revno,
578
531
            reached_stop_revision_id = False
579
532
            revision_id_whitelist = []
580
533
            for node in rev_iter:
581
 
                rev_id = node.key
 
534
                rev_id = node.key[-1]
582
535
                if rev_id == left_parent:
583
536
                    # reached the left parent after the stop_revision
584
537
                    return
664
617
        """
665
618
        raise errors.UpgradeRequired(self.user_url)
666
619
 
667
 
    def get_append_revisions_only(self):
668
 
        """Whether it is only possible to append revisions to the history.
669
 
        """
670
 
        if not self._format.supports_set_append_revisions_only():
671
 
            return False
672
 
        return self.get_config_stack().get('append_revisions_only')
673
 
 
674
620
    def set_append_revisions_only(self, enabled):
675
621
        if not self._format.supports_set_append_revisions_only():
676
622
            raise errors.UpgradeRequired(self.user_url)
677
 
        self.get_config_stack().set('append_revisions_only', enabled)
 
623
        if enabled:
 
624
            value = 'True'
 
625
        else:
 
626
            value = 'False'
 
627
        self.get_config().set_user_option('append_revisions_only', value,
 
628
            warn_masked=True)
678
629
 
679
630
    def set_reference_info(self, file_id, tree_path, branch_location):
680
631
        """Set the branch location to use for a tree reference."""
685
636
        raise errors.UnsupportedOperation(self.get_reference_info, self)
686
637
 
687
638
    @needs_write_lock
688
 
    def fetch(self, from_branch, last_revision=None, limit=None):
 
639
    def fetch(self, from_branch, last_revision=None, pb=None):
689
640
        """Copy revisions from from_branch into this branch.
690
641
 
691
642
        :param from_branch: Where to copy from.
692
643
        :param last_revision: What revision to stop at (None for at the end
693
644
                              of the branch.
694
 
        :param limit: Optional rough limit of revisions to fetch
 
645
        :param pb: An optional progress bar to use.
695
646
        :return: None
696
647
        """
697
 
        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()
698
664
 
699
665
    def get_bound_location(self):
700
666
        """Return the URL of the branch we are bound to.
709
675
        """
710
676
        raise errors.UpgradeRequired(self.user_url)
711
677
 
712
 
    def get_commit_builder(self, parents, config_stack=None, timestamp=None,
 
678
    def get_commit_builder(self, parents, config=None, timestamp=None,
713
679
                           timezone=None, committer=None, revprops=None,
714
 
                           revision_id=None, lossy=False):
 
680
                           revision_id=None):
715
681
        """Obtain a CommitBuilder for this branch.
716
682
 
717
683
        :param parents: Revision ids of the parents of the new revision.
721
687
        :param committer: Optional committer to set for commit.
722
688
        :param revprops: Optional dictionary of revision properties.
723
689
        :param revision_id: Optional revision id.
724
 
        :param lossy: Whether to discard data that can not be natively
725
 
            represented, when pushing to a foreign VCS 
726
690
        """
727
691
 
728
 
        if config_stack is None:
729
 
            config_stack = self.get_config_stack()
 
692
        if config is None:
 
693
            config = self.get_config()
730
694
 
731
 
        return self.repository.get_commit_builder(self, parents, config_stack,
732
 
            timestamp, timezone, committer, revprops, revision_id,
733
 
            lossy)
 
695
        return self.repository.get_commit_builder(self, parents, config,
 
696
            timestamp, timezone, committer, revprops, revision_id)
734
697
 
735
698
    def get_master_branch(self, possible_transports=None):
736
699
        """Return the branch we are bound to.
739
702
        """
740
703
        return None
741
704
 
742
 
    @deprecated_method(deprecated_in((2, 5, 0)))
743
705
    def get_revision_delta(self, revno):
744
706
        """Return the delta for one revision.
745
707
 
746
708
        The delta is relative to its mainline predecessor, or the
747
709
        empty tree for revision 1.
748
710
        """
749
 
        try:
750
 
            revid = self.get_rev_id(revno)
751
 
        except errors.NoSuchRevision:
 
711
        rh = self.revision_history()
 
712
        if not (1 <= revno <= len(rh)):
752
713
            raise errors.InvalidRevisionNumber(revno)
753
 
        return self.repository.get_revision_delta(revid)
 
714
        return self.repository.get_revision_delta(rh[revno-1])
754
715
 
755
716
    def get_stacked_on_url(self):
756
717
        """Get the URL this branch is stacked against.
765
726
        """Print `file` to stdout."""
766
727
        raise NotImplementedError(self.print_file)
767
728
 
768
 
    @deprecated_method(deprecated_in((2, 4, 0)))
769
729
    def set_revision_history(self, rev_history):
770
 
        """See Branch.set_revision_history."""
771
 
        self._set_revision_history(rev_history)
772
 
 
773
 
    @needs_write_lock
774
 
    def _set_revision_history(self, rev_history):
775
 
        if len(rev_history) == 0:
776
 
            revid = _mod_revision.NULL_REVISION
777
 
        else:
778
 
            revid = rev_history[-1]
779
 
        if rev_history != self._lefthand_history(revid):
780
 
            raise errors.NotLefthandHistory(rev_history)
781
 
        self.set_last_revision_info(len(rev_history), revid)
782
 
        self._cache_revision_history(rev_history)
783
 
        for hook in Branch.hooks['set_rh']:
784
 
            hook(self, rev_history)
785
 
 
786
 
    @needs_write_lock
787
 
    def set_last_revision_info(self, revno, revision_id):
788
 
        """Set the last revision of this branch.
789
 
 
790
 
        The caller is responsible for checking that the revno is correct
791
 
        for this revision id.
792
 
 
793
 
        It may be possible to set the branch last revision to an id not
794
 
        present in the repository.  However, branches can also be
795
 
        configured to check constraints on history, in which case this may not
796
 
        be permitted.
797
 
        """
798
 
        raise NotImplementedError(self.set_last_revision_info)
799
 
 
800
 
    @needs_write_lock
801
 
    def generate_revision_history(self, revision_id, last_rev=None,
802
 
                                  other_branch=None):
803
 
        """See Branch.generate_revision_history"""
804
 
        graph = self.repository.get_graph()
805
 
        (last_revno, last_revid) = self.last_revision_info()
806
 
        known_revision_ids = [
807
 
            (last_revid, last_revno),
808
 
            (_mod_revision.NULL_REVISION, 0),
809
 
            ]
810
 
        if last_rev is not None:
811
 
            if not graph.is_ancestor(last_rev, revision_id):
812
 
                # our previous tip is not merged into stop_revision
813
 
                raise errors.DivergedBranches(self, other_branch)
814
 
        revno = graph.find_distance_to_null(revision_id, known_revision_ids)
815
 
        self.set_last_revision_info(revno, revision_id)
 
730
        raise NotImplementedError(self.set_revision_history)
816
731
 
817
732
    @needs_write_lock
818
733
    def set_parent(self, url):
855
770
                return
856
771
            self._unstack()
857
772
        else:
858
 
            self._activate_fallback_location(url,
859
 
                possible_transports=[self.bzrdir.root_transport])
 
773
            self._activate_fallback_location(url)
860
774
        # write this out after the repository is stacked to avoid setting a
861
775
        # stacked config that doesn't work.
862
776
        self._set_config_location('stacked_on_location', url)
863
777
 
864
778
    def _unstack(self):
865
779
        """Change a branch to be unstacked, copying data as needed.
866
 
 
 
780
        
867
781
        Don't call this directly, use set_stacked_on_url(None).
868
782
        """
869
783
        pb = ui.ui_factory.nested_progress_bar()
870
784
        try:
871
 
            pb.update(gettext("Unstacking"))
 
785
            pb.update("Unstacking")
872
786
            # The basic approach here is to fetch the tip of the branch,
873
787
            # including all available ghosts, from the existing stacked
874
788
            # repository into a new repository object without the fallbacks. 
878
792
            old_repository = self.repository
879
793
            if len(old_repository._fallback_repositories) != 1:
880
794
                raise AssertionError("can't cope with fallback repositories "
881
 
                    "of %r (fallbacks: %r)" % (old_repository,
882
 
                        old_repository._fallback_repositories))
883
 
            # Open the new repository object.
884
 
            # Repositories don't offer an interface to remove fallback
885
 
            # repositories today; take the conceptually simpler option and just
886
 
            # reopen it.  We reopen it starting from the URL so that we
887
 
            # get a separate connection for RemoteRepositories and can
888
 
            # stream from one of them to the other.  This does mean doing
889
 
            # separate SSH connection setup, but unstacking is not a
890
 
            # common operation so it's tolerable.
891
 
            new_bzrdir = controldir.ControlDir.open(
892
 
                self.bzrdir.root_transport.base)
893
 
            new_repository = new_bzrdir.find_repository()
894
 
            if new_repository._fallback_repositories:
895
 
                raise AssertionError("didn't expect %r to have "
896
 
                    "fallback_repositories"
897
 
                    % (self.repository,))
898
 
            # Replace self.repository with the new repository.
899
 
            # Do our best to transfer the lock state (i.e. lock-tokens and
900
 
            # lock count) of self.repository to the new repository.
901
 
            lock_token = old_repository.lock_write().repository_token
902
 
            self.repository = new_repository
903
 
            if isinstance(self, remote.RemoteBranch):
904
 
                # Remote branches can have a second reference to the old
905
 
                # repository that need to be replaced.
906
 
                if self._real_branch is not None:
907
 
                    self._real_branch.repository = new_repository
908
 
            self.repository.lock_write(token=lock_token)
909
 
            if lock_token is not None:
910
 
                old_repository.leave_lock_in_place()
 
795
                    "of %r" % (self.repository,))
 
796
            # unlock it, including unlocking the fallback
911
797
            old_repository.unlock()
912
 
            if lock_token is not None:
913
 
                # XXX: self.repository.leave_lock_in_place() before this
914
 
                # function will not be preserved.  Fortunately that doesn't
915
 
                # affect the current default format (2a), and would be a
916
 
                # corner-case anyway.
917
 
                #  - Andrew Bennetts, 2010/06/30
918
 
                self.repository.dont_leave_lock_in_place()
919
 
            old_lock_count = 0
920
 
            while True:
921
 
                try:
922
 
                    old_repository.unlock()
923
 
                except errors.LockNotHeld:
924
 
                    break
925
 
                old_lock_count += 1
926
 
            if old_lock_count == 0:
927
 
                raise AssertionError(
928
 
                    'old_repository should have been locked at least once.')
929
 
            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
930
817
                self.repository.lock_write()
931
 
            # Fetch from the old repository into the new.
932
 
            old_repository.lock_read()
933
 
            try:
934
818
                # XXX: If you unstack a branch while it has a working tree
935
819
                # with a pending merge, the pending-merged revisions will no
936
820
                # longer be present.  You can (probably) revert and remerge.
937
 
                try:
938
 
                    tags_to_fetch = set(self.tags.get_reverse_tag_dict())
939
 
                except errors.TagsNotSupported:
940
 
                    tags_to_fetch = set()
941
 
                fetch_spec = vf_search.NotInOtherForRevs(self.repository,
942
 
                    old_repository, required_ids=[self.last_revision()],
943
 
                    if_present_ids=tags_to_fetch, find_ghosts=True).execute()
944
 
                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)
945
828
            finally:
946
829
                old_repository.unlock()
947
830
        finally:
952
835
 
953
836
        :seealso: Branch._get_tags_bytes.
954
837
        """
955
 
        op = cleanup.OperationWithCleanups(self._set_tags_bytes_locked)
956
 
        op.add_cleanup(self.lock_write().unlock)
957
 
        return op.run_simple(bytes)
958
 
 
959
 
    def _set_tags_bytes_locked(self, bytes):
960
 
        self._tags_bytes = bytes
961
 
        return self._transport.put_bytes('tags', bytes)
 
838
        return _run_with_write_locked_target(self, self._transport.put_bytes,
 
839
            'tags', bytes)
962
840
 
963
841
    def _cache_revision_history(self, rev_history):
964
842
        """Set the cached revision history to rev_history.
991
869
        self._revision_history_cache = None
992
870
        self._revision_id_to_revno_cache = None
993
871
        self._last_revision_info_cache = None
994
 
        self._master_branch_cache = None
995
872
        self._merge_sorted_revisions_cache = None
996
873
        self._partial_revision_history_cache = []
997
874
        self._partial_revision_id_to_revno_cache = {}
998
 
        self._tags_bytes = None
999
875
 
1000
876
    def _gen_revision_history(self):
1001
877
        """Return sequence of revision hashes on to this branch.
1012
888
        """
1013
889
        raise NotImplementedError(self._gen_revision_history)
1014
890
 
1015
 
    @deprecated_method(deprecated_in((2, 5, 0)))
1016
891
    @needs_read_lock
1017
892
    def revision_history(self):
1018
893
        """Return sequence of revision ids on this branch.
1020
895
        This method will cache the revision history for as long as it is safe to
1021
896
        do so.
1022
897
        """
1023
 
        return self._revision_history()
1024
 
 
1025
 
    def _revision_history(self):
1026
898
        if 'evil' in debug.debug_flags:
1027
899
            mutter_callsite(3, "revision_history scales with history.")
1028
900
        if self._revision_history_cache is not None:
1055
927
        :return: A tuple (revno, revision_id).
1056
928
        """
1057
929
        if self._last_revision_info_cache is None:
1058
 
            self._last_revision_info_cache = self._read_last_revision_info()
 
930
            self._last_revision_info_cache = self._last_revision_info()
1059
931
        return self._last_revision_info_cache
1060
932
 
1061
 
    def _read_last_revision_info(self):
1062
 
        raise NotImplementedError(self._read_last_revision_info)
1063
 
 
1064
 
    @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
 
1065
980
    def import_last_revision_info(self, source_repo, revno, revid):
1066
981
        """Set the last revision info, importing from another repo if necessary.
1067
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
 
1068
986
        :param source_repo: Source repository to optionally fetch from
1069
987
        :param revno: Revision number of the new tip
1070
988
        :param revid: Revision id of the new tip
1073
991
            self.repository.fetch(source_repo, revision_id=revid)
1074
992
        self.set_last_revision_info(revno, revid)
1075
993
 
1076
 
    def import_last_revision_info_and_tags(self, source, revno, revid,
1077
 
                                           lossy=False):
1078
 
        """Set the last revision info, importing from another repo if necessary.
1079
 
 
1080
 
        This is used by the bound branch code to upload a revision to
1081
 
        the master branch first before updating the tip of the local branch.
1082
 
        Revisions referenced by source's tags are also transferred.
1083
 
 
1084
 
        :param source: Source branch to optionally fetch from
1085
 
        :param revno: Revision number of the new tip
1086
 
        :param revid: Revision id of the new tip
1087
 
        :param lossy: Whether to discard metadata that can not be
1088
 
            natively represented
1089
 
        :return: Tuple with the new revision number and revision id
1090
 
            (should only be different from the arguments when lossy=True)
1091
 
        """
1092
 
        if not self.repository.has_same_location(source.repository):
1093
 
            self.fetch(source, revid)
1094
 
        self.set_last_revision_info(revno, revid)
1095
 
        return (revno, revid)
1096
 
 
1097
994
    def revision_id_to_revno(self, revision_id):
1098
995
        """Given a revision id, return its revno"""
1099
996
        if _mod_revision.is_null(revision_id):
1100
997
            return 0
1101
 
        history = self._revision_history()
 
998
        history = self.revision_history()
1102
999
        try:
1103
1000
            return history.index(revision_id) + 1
1104
1001
        except ValueError:
1119
1016
            self._extend_partial_history(distance_from_last)
1120
1017
        return self._partial_revision_history_cache[distance_from_last]
1121
1018
 
 
1019
    @needs_write_lock
1122
1020
    def pull(self, source, overwrite=False, stop_revision=None,
1123
1021
             possible_transports=None, *args, **kwargs):
1124
1022
        """Mirror source into this branch.
1131
1029
            stop_revision=stop_revision,
1132
1030
            possible_transports=possible_transports, *args, **kwargs)
1133
1031
 
1134
 
    def push(self, target, overwrite=False, stop_revision=None, lossy=False,
1135
 
            *args, **kwargs):
 
1032
    def push(self, target, overwrite=False, stop_revision=None, *args,
 
1033
        **kwargs):
1136
1034
        """Mirror this branch into target.
1137
1035
 
1138
1036
        This branch is considered to be 'local', having low latency.
1139
1037
        """
1140
1038
        return InterBranch.get(self, target).push(overwrite, stop_revision,
1141
 
            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)
1142
1061
 
1143
1062
    def basis_tree(self):
1144
1063
        """Return `Tree` object for last revision."""
1169
1088
    def _set_config_location(self, name, url, config=None,
1170
1089
                             make_relative=False):
1171
1090
        if config is None:
1172
 
            config = self.get_config_stack()
 
1091
            config = self.get_config()
1173
1092
        if url is None:
1174
1093
            url = ''
1175
1094
        elif make_relative:
1176
1095
            url = urlutils.relative_url(self.base, url)
1177
 
        config.set(name, url)
 
1096
        config.set_user_option(name, url, warn_masked=True)
1178
1097
 
1179
1098
    def _get_config_location(self, name, config=None):
1180
1099
        if config is None:
1181
 
            config = self.get_config_stack()
1182
 
        location = config.get(name)
 
1100
            config = self.get_config()
 
1101
        location = config.get_user_option(name)
1183
1102
        if location == '':
1184
1103
            location = None
1185
1104
        return location
1299
1218
        return result
1300
1219
 
1301
1220
    @needs_read_lock
1302
 
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None,
1303
 
            repository=None):
 
1221
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None):
1304
1222
        """Create a new line of development from the branch, into to_bzrdir.
1305
1223
 
1306
1224
        to_bzrdir controls the branch format.
1311
1229
        if (repository_policy is not None and
1312
1230
            repository_policy.requires_stacking()):
1313
1231
            to_bzrdir._format.require_stacking(_skip_repo=True)
1314
 
        result = to_bzrdir.create_branch(repository=repository)
 
1232
        result = to_bzrdir.create_branch()
1315
1233
        result.lock_write()
1316
1234
        try:
1317
1235
            if repository_policy is not None:
1318
1236
                repository_policy.configure_branch(result)
1319
1237
            self.copy_content_into(result, revision_id=revision_id)
1320
 
            master_url = self.get_bound_location()
1321
 
            if master_url is None:
1322
 
                result.set_parent(self.bzrdir.root_transport.base)
1323
 
            else:
1324
 
                result.set_parent(master_url)
 
1238
            result.set_parent(self.bzrdir.root_transport.base)
1325
1239
        finally:
1326
1240
            result.unlock()
1327
1241
        return result
1351
1265
                revno = 1
1352
1266
        destination.set_last_revision_info(revno, revision_id)
1353
1267
 
 
1268
    @needs_read_lock
1354
1269
    def copy_content_into(self, destination, revision_id=None):
1355
1270
        """Copy the content of self into destination.
1356
1271
 
1357
1272
        revision_id: if not None, the revision history in the new branch will
1358
1273
                     be truncated to end with revision_id.
1359
1274
        """
1360
 
        return InterBranch.get(self, destination).copy_content_into(
1361
 
            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)
1362
1286
 
1363
1287
    def update_references(self, target):
1364
1288
        if not getattr(self._format, 'supports_reference_locations', False):
1401
1325
        # TODO: We should probably also check that self.revision_history
1402
1326
        # matches the repository for older branch formats.
1403
1327
        # If looking for the code that cross-checks repository parents against
1404
 
        # the Graph.iter_lefthand_ancestry output, that is now a repository
 
1328
        # the iter_reverse_revision_history output, that is now a repository
1405
1329
        # specific check.
1406
1330
        return result
1407
1331
 
1408
 
    def _get_checkout_format(self, lightweight=False):
 
1332
    def _get_checkout_format(self):
1409
1333
        """Return the most suitable metadir for a checkout of this branch.
1410
1334
        Weaves are used if this branch's repository uses weaves.
1411
1335
        """
1412
 
        format = self.repository.bzrdir.checkout_metadir()
1413
 
        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)
1414
1343
        return format
1415
1344
 
1416
1345
    def create_clone_on_transport(self, to_transport, revision_id=None,
1417
 
        stacked_on=None, create_prefix=False, use_existing_dir=False,
1418
 
        no_tree=None):
 
1346
        stacked_on=None, create_prefix=False, use_existing_dir=False):
1419
1347
        """Create a clone of this branch and its bzrdir.
1420
1348
 
1421
1349
        :param to_transport: The transport to clone onto.
1434
1362
            revision_id = self.last_revision()
1435
1363
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1436
1364
            revision_id=revision_id, stacked_on=stacked_on,
1437
 
            create_prefix=create_prefix, use_existing_dir=use_existing_dir,
1438
 
            no_tree=no_tree)
 
1365
            create_prefix=create_prefix, use_existing_dir=use_existing_dir)
1439
1366
        return dir_to.open_branch()
1440
1367
 
1441
1368
    def create_checkout(self, to_location, revision_id=None,
1446
1373
        :param to_location: The url to produce the checkout at
1447
1374
        :param revision_id: The revision to check out
1448
1375
        :param lightweight: If True, produce a lightweight checkout, otherwise,
1449
 
            produce a bound branch (heavyweight checkout)
 
1376
        produce a bound branch (heavyweight checkout)
1450
1377
        :param accelerator_tree: A tree which can be used for retrieving file
1451
1378
            contents more quickly than the revision tree, i.e. a workingtree.
1452
1379
            The revision tree will be used for cases where accelerator_tree's
1457
1384
        """
1458
1385
        t = transport.get_transport(to_location)
1459
1386
        t.ensure_base()
1460
 
        format = self._get_checkout_format(lightweight=lightweight)
1461
1387
        if lightweight:
 
1388
            format = self._get_checkout_format()
1462
1389
            checkout = format.initialize_on_transport(t)
1463
1390
            from_branch = BranchReferenceFormat().initialize(checkout, 
1464
1391
                target_branch=self)
1465
1392
        else:
1466
 
            checkout_branch = controldir.ControlDir.create_branch_convenience(
 
1393
            format = self._get_checkout_format()
 
1394
            checkout_branch = bzrdir.BzrDir.create_branch_convenience(
1467
1395
                to_location, force_new_tree=False, format=format)
1468
1396
            checkout = checkout_branch.bzrdir
1469
1397
            checkout_branch.bind(self)
1497
1425
 
1498
1426
    def reference_parent(self, file_id, path, possible_transports=None):
1499
1427
        """Return the parent branch for a tree-reference file_id
1500
 
 
1501
1428
        :param file_id: The file_id of the tree reference
1502
1429
        :param path: The path of the file_id in the tree
1503
1430
        :return: A branch associated with the file_id
1556
1483
        else:
1557
1484
            raise AssertionError("invalid heads: %r" % (heads,))
1558
1485
 
1559
 
    def heads_to_fetch(self):
1560
 
        """Return the heads that must and that should be fetched to copy this
1561
 
        branch into another repo.
1562
 
 
1563
 
        :returns: a 2-tuple of (must_fetch, if_present_fetch).  must_fetch is a
1564
 
            set of heads that must be fetched.  if_present_fetch is a set of
1565
 
            heads that must be fetched if present, but no error is necessary if
1566
 
            they are not present.
1567
 
        """
1568
 
        # For bzr native formats must_fetch is just the tip, and if_present_fetch
1569
 
        # are the tags.
1570
 
        must_fetch = set([self.last_revision()])
1571
 
        if_present_fetch = set()
1572
 
        c = self.get_config()
1573
 
        include_tags = c.get_user_option_as_bool('branch.fetch_tags',
1574
 
                                                 default=False)
1575
 
        if include_tags:
1576
 
            try:
1577
 
                if_present_fetch = set(self.tags.get_reverse_tag_dict())
1578
 
            except errors.TagsNotSupported:
1579
 
                pass
1580
 
        must_fetch.discard(_mod_revision.NULL_REVISION)
1581
 
        if_present_fetch.discard(_mod_revision.NULL_REVISION)
1582
 
        return must_fetch, if_present_fetch
1583
 
 
1584
 
 
1585
 
class BranchFormat(controldir.ControlComponentFormat):
 
1486
 
 
1487
class BranchFormat(object):
1586
1488
    """An encapsulation of the initialization and open routines for a format.
1587
1489
 
1588
1490
    Formats provide three things:
1591
1493
     * an open routine.
1592
1494
 
1593
1495
    Formats are placed in an dict by their format string for reference
1594
 
    during branch opening. It's not required that these be instances, they
 
1496
    during branch opening. Its not required that these be instances, they
1595
1497
    can be classes themselves with class methods - it simply depends on
1596
1498
    whether state is needed for a given format or not.
1597
1499
 
1600
1502
    object will be created every time regardless.
1601
1503
    """
1602
1504
 
 
1505
    _default_format = None
 
1506
    """The default format used for new branches."""
 
1507
 
 
1508
    _formats = {}
 
1509
    """The known formats."""
 
1510
 
 
1511
    can_set_append_revisions_only = True
 
1512
 
1603
1513
    def __eq__(self, other):
1604
1514
        return self.__class__ is other.__class__
1605
1515
 
1607
1517
        return not (self == other)
1608
1518
 
1609
1519
    @classmethod
1610
 
    @deprecated_method(deprecated_in((2, 4, 0)))
 
1520
    def find_format(klass, a_bzrdir, name=None):
 
1521
        """Return the format for the branch object in a_bzrdir."""
 
1522
        try:
 
1523
            transport = a_bzrdir.get_branch_transport(None, name=name)
 
1524
            format_string = transport.get_bytes("format")
 
1525
            return klass._formats[format_string]
 
1526
        except errors.NoSuchFile:
 
1527
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
 
1528
        except KeyError:
 
1529
            raise errors.UnknownFormatError(format=format_string, kind='branch')
 
1530
 
 
1531
    @classmethod
1611
1532
    def get_default_format(klass):
1612
1533
        """Return the current default format."""
1613
 
        return format_registry.get_default()
1614
 
 
1615
 
    @classmethod
1616
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1617
 
    def get_formats(klass):
1618
 
        """Get all the known formats.
1619
 
 
1620
 
        Warning: This triggers a load of all lazy registered formats: do not
1621
 
        use except when that is desireed.
1622
 
        """
1623
 
        return format_registry._get_all()
1624
 
 
1625
 
    def get_reference(self, controldir, name=None):
1626
 
        """Get the target reference of the branch in controldir.
 
1534
        return klass._default_format
 
1535
 
 
1536
    def get_reference(self, a_bzrdir, name=None):
 
1537
        """Get the target reference of the branch in a_bzrdir.
1627
1538
 
1628
1539
        format probing must have been completed before calling
1629
1540
        this method - it is assumed that the format of the branch
1630
 
        in controldir is correct.
 
1541
        in a_bzrdir is correct.
1631
1542
 
1632
 
        :param controldir: The controldir to get the branch data from.
 
1543
        :param a_bzrdir: The bzrdir to get the branch data from.
1633
1544
        :param name: Name of the colocated branch to fetch
1634
1545
        :return: None if the branch is not a reference branch.
1635
1546
        """
1636
1547
        return None
1637
1548
 
1638
1549
    @classmethod
1639
 
    def set_reference(self, controldir, name, to_branch):
1640
 
        """Set the target reference of the branch in controldir.
 
1550
    def set_reference(self, a_bzrdir, name, to_branch):
 
1551
        """Set the target reference of the branch in a_bzrdir.
1641
1552
 
1642
1553
        format probing must have been completed before calling
1643
1554
        this method - it is assumed that the format of the branch
1644
 
        in controldir is correct.
 
1555
        in a_bzrdir is correct.
1645
1556
 
1646
 
        :param controldir: The controldir to set the branch reference for.
 
1557
        :param a_bzrdir: The bzrdir to set the branch reference for.
1647
1558
        :param name: Name of colocated branch to set, None for default
1648
1559
        :param to_branch: branch that the checkout is to reference
1649
1560
        """
1650
1561
        raise NotImplementedError(self.set_reference)
1651
1562
 
 
1563
    def get_format_string(self):
 
1564
        """Return the ASCII format string that identifies this format."""
 
1565
        raise NotImplementedError(self.get_format_string)
 
1566
 
1652
1567
    def get_format_description(self):
1653
1568
        """Return the short format description for this format."""
1654
1569
        raise NotImplementedError(self.get_format_description)
1655
1570
 
1656
 
    def _run_post_branch_init_hooks(self, controldir, name, branch):
 
1571
    def _run_post_branch_init_hooks(self, a_bzrdir, name, branch):
1657
1572
        hooks = Branch.hooks['post_branch_init']
1658
1573
        if not hooks:
1659
1574
            return
1660
 
        params = BranchInitHookParams(self, controldir, name, branch)
 
1575
        params = BranchInitHookParams(self, a_bzrdir, name, branch)
1661
1576
        for hook in hooks:
1662
1577
            hook(params)
1663
1578
 
1664
 
    def initialize(self, controldir, name=None, repository=None,
1665
 
                   append_revisions_only=None):
1666
 
        """Create a branch of this format in controldir.
1667
 
 
 
1579
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
 
1580
                           lock_type='metadir', set_format=True):
 
1581
        """Initialize a branch in a bzrdir, with specified files
 
1582
 
 
1583
        :param a_bzrdir: The bzrdir to initialize the branch in
 
1584
        :param utf8_files: The files to create as a list of
 
1585
            (filename, content) tuples
 
1586
        :param name: Name of colocated branch to create, if any
 
1587
        :param set_format: If True, set the format with
 
1588
            self.get_format_string.  (BzrBranch4 has its format set
 
1589
            elsewhere)
 
1590
        :return: a branch in this format
 
1591
        """
 
1592
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
 
1593
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
1594
        lock_map = {
 
1595
            'metadir': ('lock', lockdir.LockDir),
 
1596
            'branch4': ('branch-lock', lockable_files.TransportLock),
 
1597
        }
 
1598
        lock_name, lock_class = lock_map[lock_type]
 
1599
        control_files = lockable_files.LockableFiles(branch_transport,
 
1600
            lock_name, lock_class)
 
1601
        control_files.create_lock()
 
1602
        try:
 
1603
            control_files.lock_write()
 
1604
        except errors.LockContention:
 
1605
            if lock_type != 'branch4':
 
1606
                raise
 
1607
            lock_taken = False
 
1608
        else:
 
1609
            lock_taken = True
 
1610
        if set_format:
 
1611
            utf8_files += [('format', self.get_format_string())]
 
1612
        try:
 
1613
            for (filename, content) in utf8_files:
 
1614
                branch_transport.put_bytes(
 
1615
                    filename, content,
 
1616
                    mode=a_bzrdir._get_file_mode())
 
1617
        finally:
 
1618
            if lock_taken:
 
1619
                control_files.unlock()
 
1620
        branch = self.open(a_bzrdir, name, _found=True)
 
1621
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
 
1622
        return branch
 
1623
 
 
1624
    def initialize(self, a_bzrdir, name=None):
 
1625
        """Create a branch of this format in a_bzrdir.
 
1626
        
1668
1627
        :param name: Name of the colocated branch to create.
1669
1628
        """
1670
1629
        raise NotImplementedError(self.initialize)
1690
1649
        Note that it is normal for branch to be a RemoteBranch when using tags
1691
1650
        on a RemoteBranch.
1692
1651
        """
1693
 
        return _mod_tag.DisabledTags(branch)
 
1652
        return DisabledTags(branch)
1694
1653
 
1695
1654
    def network_name(self):
1696
1655
        """A simple byte string uniquely identifying this format for RPC calls.
1702
1661
        """
1703
1662
        raise NotImplementedError(self.network_name)
1704
1663
 
1705
 
    def open(self, controldir, name=None, _found=False, ignore_fallbacks=False,
1706
 
            found_repository=None, possible_transports=None):
1707
 
        """Return the branch object for controldir.
 
1664
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1665
        """Return the branch object for a_bzrdir
1708
1666
 
1709
 
        :param controldir: A ControlDir that contains a branch.
 
1667
        :param a_bzrdir: A BzrDir that contains a branch.
1710
1668
        :param name: Name of colocated branch to open
1711
1669
        :param _found: a private parameter, do not use it. It is used to
1712
1670
            indicate if format probing has already be done.
1716
1674
        raise NotImplementedError(self.open)
1717
1675
 
1718
1676
    @classmethod
1719
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1720
1677
    def register_format(klass, format):
1721
 
        """Register a metadir format.
1722
 
 
1723
 
        See MetaDirBranchFormatFactory for the ability to register a format
1724
 
        without loading the code the format needs until it is actually used.
1725
 
        """
1726
 
        format_registry.register(format)
 
1678
        """Register a metadir format."""
 
1679
        klass._formats[format.get_format_string()] = format
 
1680
        # Metadir formats have a network name of their format string, and get
 
1681
        # registered as class factories.
 
1682
        network_format_registry.register(format.get_format_string(), format.__class__)
1727
1683
 
1728
1684
    @classmethod
1729
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1730
1685
    def set_default_format(klass, format):
1731
 
        format_registry.set_default(format)
 
1686
        klass._default_format = format
1732
1687
 
1733
1688
    def supports_set_append_revisions_only(self):
1734
1689
        """True if this format supports set_append_revisions_only."""
1738
1693
        """True if this format records a stacked-on branch."""
1739
1694
        return False
1740
1695
 
1741
 
    def supports_leaving_lock(self):
1742
 
        """True if this format supports leaving locks in place."""
1743
 
        return False # by default
1744
 
 
1745
1696
    @classmethod
1746
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1747
1697
    def unregister_format(klass, format):
1748
 
        format_registry.remove(format)
 
1698
        del klass._formats[format.get_format_string()]
1749
1699
 
1750
1700
    def __str__(self):
1751
1701
        return self.get_format_description().rstrip()
1754
1704
        """True if this format supports tags stored in the branch"""
1755
1705
        return False  # by default
1756
1706
 
1757
 
    def tags_are_versioned(self):
1758
 
        """Whether the tag container for this branch versions tags."""
1759
 
        return False
1760
 
 
1761
 
    def supports_tags_referencing_ghosts(self):
1762
 
        """True if tags can reference ghost revisions."""
1763
 
        return True
1764
 
 
1765
 
 
1766
 
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
1767
 
    """A factory for a BranchFormat object, permitting simple lazy registration.
1768
 
    
1769
 
    While none of the built in BranchFormats are lazy registered yet,
1770
 
    bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
1771
 
    use it, and the bzr-loom plugin uses it as well (see
1772
 
    bzrlib.plugins.loom.formats).
1773
 
    """
1774
 
 
1775
 
    def __init__(self, format_string, module_name, member_name):
1776
 
        """Create a MetaDirBranchFormatFactory.
1777
 
 
1778
 
        :param format_string: The format string the format has.
1779
 
        :param module_name: Module to load the format class from.
1780
 
        :param member_name: Attribute name within the module for the format class.
1781
 
        """
1782
 
        registry._LazyObjectGetter.__init__(self, module_name, member_name)
1783
 
        self._format_string = format_string
1784
 
 
1785
 
    def get_format_string(self):
1786
 
        """See BranchFormat.get_format_string."""
1787
 
        return self._format_string
1788
 
 
1789
 
    def __call__(self):
1790
 
        """Used for network_format_registry support."""
1791
 
        return self.get_obj()()
1792
 
 
1793
1707
 
1794
1708
class BranchHooks(Hooks):
1795
1709
    """A dictionary mapping hook name to a list of callables for branch hooks.
1804
1718
        These are all empty initially, because by default nothing should get
1805
1719
        notified.
1806
1720
        """
1807
 
        Hooks.__init__(self, "bzrlib.branch", "Branch.hooks")
1808
 
        self.add_hook('set_rh',
 
1721
        Hooks.__init__(self)
 
1722
        self.create_hook(HookPoint('set_rh',
1809
1723
            "Invoked whenever the revision history has been set via "
1810
1724
            "set_revision_history. The api signature is (branch, "
1811
1725
            "revision_history), and the branch will be write-locked. "
1812
1726
            "The set_rh hook can be expensive for bzr to trigger, a better "
1813
 
            "hook to use is Branch.post_change_branch_tip.", (0, 15))
1814
 
        self.add_hook('open',
 
1727
            "hook to use is Branch.post_change_branch_tip.", (0, 15), None))
 
1728
        self.create_hook(HookPoint('open',
1815
1729
            "Called with the Branch object that has been opened after a "
1816
 
            "branch is opened.", (1, 8))
1817
 
        self.add_hook('post_push',
 
1730
            "branch is opened.", (1, 8), None))
 
1731
        self.create_hook(HookPoint('post_push',
1818
1732
            "Called after a push operation completes. post_push is called "
1819
1733
            "with a bzrlib.branch.BranchPushResult object and only runs in the "
1820
 
            "bzr client.", (0, 15))
1821
 
        self.add_hook('post_pull',
 
1734
            "bzr client.", (0, 15), None))
 
1735
        self.create_hook(HookPoint('post_pull',
1822
1736
            "Called after a pull operation completes. post_pull is called "
1823
1737
            "with a bzrlib.branch.PullResult object and only runs in the "
1824
 
            "bzr client.", (0, 15))
1825
 
        self.add_hook('pre_commit',
1826
 
            "Called after a commit is calculated but before it is "
 
1738
            "bzr client.", (0, 15), None))
 
1739
        self.create_hook(HookPoint('pre_commit',
 
1740
            "Called after a commit is calculated but before it is is "
1827
1741
            "completed. pre_commit is called with (local, master, old_revno, "
1828
1742
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
1829
1743
            "). old_revid is NULL_REVISION for the first commit to a branch, "
1831
1745
            "basis revision. hooks MUST NOT modify this delta. "
1832
1746
            " future_tree is an in-memory tree obtained from "
1833
1747
            "CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1834
 
            "tree.", (0,91))
1835
 
        self.add_hook('post_commit',
 
1748
            "tree.", (0,91), None))
 
1749
        self.create_hook(HookPoint('post_commit',
1836
1750
            "Called in the bzr client after a commit has completed. "
1837
1751
            "post_commit is called with (local, master, old_revno, old_revid, "
1838
1752
            "new_revno, new_revid). old_revid is NULL_REVISION for the first "
1839
 
            "commit to a branch.", (0, 15))
1840
 
        self.add_hook('post_uncommit',
 
1753
            "commit to a branch.", (0, 15), None))
 
1754
        self.create_hook(HookPoint('post_uncommit',
1841
1755
            "Called in the bzr client after an uncommit completes. "
1842
1756
            "post_uncommit is called with (local, master, old_revno, "
1843
1757
            "old_revid, new_revno, new_revid) where local is the local branch "
1844
1758
            "or None, master is the target branch, and an empty branch "
1845
 
            "receives new_revno of 0, new_revid of None.", (0, 15))
1846
 
        self.add_hook('pre_change_branch_tip',
 
1759
            "receives new_revno of 0, new_revid of None.", (0, 15), None))
 
1760
        self.create_hook(HookPoint('pre_change_branch_tip',
1847
1761
            "Called in bzr client and server before a change to the tip of a "
1848
1762
            "branch is made. pre_change_branch_tip is called with a "
1849
1763
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1850
 
            "commit, uncommit will all trigger this hook.", (1, 6))
1851
 
        self.add_hook('post_change_branch_tip',
 
1764
            "commit, uncommit will all trigger this hook.", (1, 6), None))
 
1765
        self.create_hook(HookPoint('post_change_branch_tip',
1852
1766
            "Called in bzr client and server after a change to the tip of a "
1853
1767
            "branch is made. post_change_branch_tip is called with a "
1854
1768
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1855
 
            "commit, uncommit will all trigger this hook.", (1, 4))
1856
 
        self.add_hook('transform_fallback_location',
 
1769
            "commit, uncommit will all trigger this hook.", (1, 4), None))
 
1770
        self.create_hook(HookPoint('transform_fallback_location',
1857
1771
            "Called when a stacked branch is activating its fallback "
1858
1772
            "locations. transform_fallback_location is called with (branch, "
1859
1773
            "url), and should return a new url. Returning the same url "
1864
1778
            "fallback locations have not been activated. When there are "
1865
1779
            "multiple hooks installed for transform_fallback_location, "
1866
1780
            "all are called with the url returned from the previous hook."
1867
 
            "The order is however undefined.", (1, 9))
1868
 
        self.add_hook('automatic_tag_name',
1869
 
            "Called to determine an automatic tag name for a revision. "
 
1781
            "The order is however undefined.", (1, 9), None))
 
1782
        self.create_hook(HookPoint('automatic_tag_name',
 
1783
            "Called to determine an automatic tag name for a revision."
1870
1784
            "automatic_tag_name is called with (branch, revision_id) and "
1871
1785
            "should return a tag name or None if no tag name could be "
1872
1786
            "determined. The first non-None tag name returned will be used.",
1873
 
            (2, 2))
1874
 
        self.add_hook('post_branch_init',
 
1787
            (2, 2), None))
 
1788
        self.create_hook(HookPoint('post_branch_init',
1875
1789
            "Called after new branch initialization completes. "
1876
1790
            "post_branch_init is called with a "
1877
1791
            "bzrlib.branch.BranchInitHookParams. "
1878
1792
            "Note that init, branch and checkout (both heavyweight and "
1879
 
            "lightweight) will all trigger this hook.", (2, 2))
1880
 
        self.add_hook('post_switch',
 
1793
            "lightweight) will all trigger this hook.", (2, 2), None))
 
1794
        self.create_hook(HookPoint('post_switch',
1881
1795
            "Called after a checkout switches branch. "
1882
1796
            "post_switch is called with a "
1883
 
            "bzrlib.branch.SwitchHookParams.", (2, 2))
 
1797
            "bzrlib.branch.SwitchHookParams.", (2, 2), None))
1884
1798
 
1885
1799
 
1886
1800
 
1889
1803
 
1890
1804
 
1891
1805
class ChangeBranchTipParams(object):
1892
 
    """Object holding parameters passed to `*_change_branch_tip` hooks.
 
1806
    """Object holding parameters passed to *_change_branch_tip hooks.
1893
1807
 
1894
1808
    There are 5 fields that hooks may wish to access:
1895
1809
 
1927
1841
 
1928
1842
 
1929
1843
class BranchInitHookParams(object):
1930
 
    """Object holding parameters passed to `*_branch_init` hooks.
 
1844
    """Object holding parameters passed to *_branch_init hooks.
1931
1845
 
1932
1846
    There are 4 fields that hooks may wish to access:
1933
1847
 
1934
1848
    :ivar format: the branch format
1935
 
    :ivar bzrdir: the ControlDir where the branch will be/has been initialized
 
1849
    :ivar bzrdir: the BzrDir where the branch will be/has been initialized
1936
1850
    :ivar name: name of colocated branch, if any (or None)
1937
1851
    :ivar branch: the branch created
1938
1852
 
1941
1855
    branch, which refer to the original branch.
1942
1856
    """
1943
1857
 
1944
 
    def __init__(self, format, controldir, name, branch):
 
1858
    def __init__(self, format, a_bzrdir, name, branch):
1945
1859
        """Create a group of BranchInitHook parameters.
1946
1860
 
1947
1861
        :param format: the branch format
1948
 
        :param controldir: the ControlDir where the branch will be/has been
 
1862
        :param a_bzrdir: the BzrDir where the branch will be/has been
1949
1863
            initialized
1950
1864
        :param name: name of colocated branch, if any (or None)
1951
1865
        :param branch: the branch created
1955
1869
        in branch, which refer to the original branch.
1956
1870
        """
1957
1871
        self.format = format
1958
 
        self.bzrdir = controldir
 
1872
        self.bzrdir = a_bzrdir
1959
1873
        self.name = name
1960
1874
        self.branch = branch
1961
1875
 
1963
1877
        return self.__dict__ == other.__dict__
1964
1878
 
1965
1879
    def __repr__(self):
1966
 
        return "<%s of %s>" % (self.__class__.__name__, self.branch)
 
1880
        if self.branch:
 
1881
            return "<%s of %s>" % (self.__class__.__name__, self.branch)
 
1882
        else:
 
1883
            return "<%s of format:%s bzrdir:%s>" % (
 
1884
                self.__class__.__name__, self.branch,
 
1885
                self.format, self.bzrdir)
1967
1886
 
1968
1887
 
1969
1888
class SwitchHookParams(object):
1970
 
    """Object holding parameters passed to `*_switch` hooks.
 
1889
    """Object holding parameters passed to *_switch hooks.
1971
1890
 
1972
1891
    There are 4 fields that hooks may wish to access:
1973
1892
 
1974
 
    :ivar control_dir: ControlDir of the checkout to change
 
1893
    :ivar control_dir: BzrDir of the checkout to change
1975
1894
    :ivar to_branch: branch that the checkout is to reference
1976
1895
    :ivar force: skip the check for local commits in a heavy checkout
1977
1896
    :ivar revision_id: revision ID to switch to (or None)
1980
1899
    def __init__(self, control_dir, to_branch, force, revision_id):
1981
1900
        """Create a group of SwitchHook parameters.
1982
1901
 
1983
 
        :param control_dir: ControlDir of the checkout to change
 
1902
        :param control_dir: BzrDir of the checkout to change
1984
1903
        :param to_branch: branch that the checkout is to reference
1985
1904
        :param force: skip the check for local commits in a heavy checkout
1986
1905
        :param revision_id: revision ID to switch to (or None)
1999
1918
            self.revision_id)
2000
1919
 
2001
1920
 
2002
 
class BranchFormatMetadir(bzrdir.BzrDirMetaComponentFormat, BranchFormat):
2003
 
    """Base class for branch formats that live in meta directories.
 
1921
class BzrBranchFormat4(BranchFormat):
 
1922
    """Bzr branch format 4.
 
1923
 
 
1924
    This format has:
 
1925
     - a revision-history file.
 
1926
     - a branch-lock lock file [ to be shared with the bzrdir ]
2004
1927
    """
2005
1928
 
 
1929
    def get_format_description(self):
 
1930
        """See BranchFormat.get_format_description()."""
 
1931
        return "Branch format 4"
 
1932
 
 
1933
    def initialize(self, a_bzrdir, name=None):
 
1934
        """Create a branch of this format in a_bzrdir."""
 
1935
        utf8_files = [('revision-history', ''),
 
1936
                      ('branch-name', ''),
 
1937
                      ]
 
1938
        return self._initialize_helper(a_bzrdir, utf8_files, name=name,
 
1939
                                       lock_type='branch4', set_format=False)
 
1940
 
2006
1941
    def __init__(self):
2007
 
        BranchFormat.__init__(self)
2008
 
        bzrdir.BzrDirMetaComponentFormat.__init__(self)
2009
 
 
2010
 
    @classmethod
2011
 
    def find_format(klass, controldir, name=None):
2012
 
        """Return the format for the branch object in controldir."""
2013
 
        try:
2014
 
            transport = controldir.get_branch_transport(None, name=name)
2015
 
        except errors.NoSuchFile:
2016
 
            raise errors.NotBranchError(path=name, bzrdir=controldir)
2017
 
        try:
2018
 
            format_string = transport.get_bytes("format")
2019
 
        except errors.NoSuchFile:
2020
 
            raise errors.NotBranchError(path=transport.base, bzrdir=controldir)
2021
 
        return klass._find_format(format_registry, 'branch', format_string)
 
1942
        super(BzrBranchFormat4, self).__init__()
 
1943
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
 
1944
 
 
1945
    def network_name(self):
 
1946
        """The network name for this format is the control dirs disk label."""
 
1947
        return self._matchingbzrdir.get_format_string()
 
1948
 
 
1949
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1950
        """See BranchFormat.open()."""
 
1951
        if not _found:
 
1952
            # we are being called directly and must probe.
 
1953
            raise NotImplementedError
 
1954
        return BzrBranch(_format=self,
 
1955
                         _control_files=a_bzrdir._control_files,
 
1956
                         a_bzrdir=a_bzrdir,
 
1957
                         name=name,
 
1958
                         _repository=a_bzrdir.open_repository())
 
1959
 
 
1960
    def __str__(self):
 
1961
        return "Bazaar-NG branch format 4"
 
1962
 
 
1963
 
 
1964
class BranchFormatMetadir(BranchFormat):
 
1965
    """Common logic for meta-dir based branch formats."""
2022
1966
 
2023
1967
    def _branch_class(self):
2024
1968
        """What class to instantiate on open calls."""
2025
1969
        raise NotImplementedError(self._branch_class)
2026
1970
 
2027
 
    def _get_initial_config(self, append_revisions_only=None):
2028
 
        if append_revisions_only:
2029
 
            return "append_revisions_only = True\n"
2030
 
        else:
2031
 
            # Avoid writing anything if append_revisions_only is disabled,
2032
 
            # as that is the default.
2033
 
            return ""
2034
 
 
2035
 
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
2036
 
                           repository=None):
2037
 
        """Initialize a branch in a bzrdir, with specified files
2038
 
 
2039
 
        :param a_bzrdir: The bzrdir to initialize the branch in
2040
 
        :param utf8_files: The files to create as a list of
2041
 
            (filename, content) tuples
2042
 
        :param name: Name of colocated branch to create, if any
2043
 
        :return: a branch in this format
 
1971
    def network_name(self):
 
1972
        """A simple byte string uniquely identifying this format for RPC calls.
 
1973
 
 
1974
        Metadir branch formats use their format string.
2044
1975
        """
2045
 
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
2046
 
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
2047
 
        control_files = lockable_files.LockableFiles(branch_transport,
2048
 
            'lock', lockdir.LockDir)
2049
 
        control_files.create_lock()
2050
 
        control_files.lock_write()
2051
 
        try:
2052
 
            utf8_files += [('format', self.get_format_string())]
2053
 
            for (filename, content) in utf8_files:
2054
 
                branch_transport.put_bytes(
2055
 
                    filename, content,
2056
 
                    mode=a_bzrdir._get_file_mode())
2057
 
        finally:
2058
 
            control_files.unlock()
2059
 
        branch = self.open(a_bzrdir, name, _found=True,
2060
 
                found_repository=repository)
2061
 
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2062
 
        return branch
 
1976
        return self.get_format_string()
2063
1977
 
2064
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
2065
 
            found_repository=None, possible_transports=None):
 
1978
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
2066
1979
        """See BranchFormat.open()."""
2067
1980
        if not _found:
2068
 
            format = BranchFormatMetadir.find_format(a_bzrdir, name=name)
 
1981
            format = BranchFormat.find_format(a_bzrdir, name=name)
2069
1982
            if format.__class__ != self.__class__:
2070
1983
                raise AssertionError("wrong format %r found for %r" %
2071
1984
                    (format, self))
2073
1986
        try:
2074
1987
            control_files = lockable_files.LockableFiles(transport, 'lock',
2075
1988
                                                         lockdir.LockDir)
2076
 
            if found_repository is None:
2077
 
                found_repository = a_bzrdir.find_repository()
2078
1989
            return self._branch_class()(_format=self,
2079
1990
                              _control_files=control_files,
2080
1991
                              name=name,
2081
1992
                              a_bzrdir=a_bzrdir,
2082
 
                              _repository=found_repository,
2083
 
                              ignore_fallbacks=ignore_fallbacks,
2084
 
                              possible_transports=possible_transports)
 
1993
                              _repository=a_bzrdir.find_repository(),
 
1994
                              ignore_fallbacks=ignore_fallbacks)
2085
1995
        except errors.NoSuchFile:
2086
1996
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
2087
1997
 
2088
 
    @property
2089
 
    def _matchingbzrdir(self):
2090
 
        ret = bzrdir.BzrDirMetaFormat1()
2091
 
        ret.set_branch_format(self)
2092
 
        return ret
 
1998
    def __init__(self):
 
1999
        super(BranchFormatMetadir, self).__init__()
 
2000
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
2001
        self._matchingbzrdir.set_branch_format(self)
2093
2002
 
2094
2003
    def supports_tags(self):
2095
2004
        return True
2096
2005
 
2097
 
    def supports_leaving_lock(self):
2098
 
        return True
2099
 
 
2100
2006
 
2101
2007
class BzrBranchFormat5(BranchFormatMetadir):
2102
2008
    """Bzr branch format 5.
2114
2020
    def _branch_class(self):
2115
2021
        return BzrBranch5
2116
2022
 
2117
 
    @classmethod
2118
 
    def get_format_string(cls):
 
2023
    def get_format_string(self):
2119
2024
        """See BranchFormat.get_format_string()."""
2120
2025
        return "Bazaar-NG branch format 5\n"
2121
2026
 
2123
2028
        """See BranchFormat.get_format_description()."""
2124
2029
        return "Branch format 5"
2125
2030
 
2126
 
    def initialize(self, a_bzrdir, name=None, repository=None,
2127
 
                   append_revisions_only=None):
 
2031
    def initialize(self, a_bzrdir, name=None):
2128
2032
        """Create a branch of this format in a_bzrdir."""
2129
 
        if append_revisions_only:
2130
 
            raise errors.UpgradeRequired(a_bzrdir.user_url)
2131
2033
        utf8_files = [('revision-history', ''),
2132
2034
                      ('branch-name', ''),
2133
2035
                      ]
2134
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
2036
        return self._initialize_helper(a_bzrdir, utf8_files, name)
2135
2037
 
2136
2038
    def supports_tags(self):
2137
2039
        return False
2151
2053
    def _branch_class(self):
2152
2054
        return BzrBranch6
2153
2055
 
2154
 
    @classmethod
2155
 
    def get_format_string(cls):
 
2056
    def get_format_string(self):
2156
2057
        """See BranchFormat.get_format_string()."""
2157
2058
        return "Bazaar Branch Format 6 (bzr 0.15)\n"
2158
2059
 
2160
2061
        """See BranchFormat.get_format_description()."""
2161
2062
        return "Branch format 6"
2162
2063
 
2163
 
    def initialize(self, a_bzrdir, name=None, repository=None,
2164
 
                   append_revisions_only=None):
 
2064
    def initialize(self, a_bzrdir, name=None):
2165
2065
        """Create a branch of this format in a_bzrdir."""
2166
2066
        utf8_files = [('last-revision', '0 null:\n'),
2167
 
                      ('branch.conf',
2168
 
                          self._get_initial_config(append_revisions_only)),
 
2067
                      ('branch.conf', ''),
2169
2068
                      ('tags', ''),
2170
2069
                      ]
2171
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
2070
        return self._initialize_helper(a_bzrdir, utf8_files, name)
2172
2071
 
2173
2072
    def make_tags(self, branch):
2174
2073
        """See bzrlib.branch.BranchFormat.make_tags()."""
2175
 
        return _mod_tag.BasicTags(branch)
 
2074
        return BasicTags(branch)
2176
2075
 
2177
2076
    def supports_set_append_revisions_only(self):
2178
2077
        return True
2184
2083
    def _branch_class(self):
2185
2084
        return BzrBranch8
2186
2085
 
2187
 
    @classmethod
2188
 
    def get_format_string(cls):
 
2086
    def get_format_string(self):
2189
2087
        """See BranchFormat.get_format_string()."""
2190
2088
        return "Bazaar Branch Format 8 (needs bzr 1.15)\n"
2191
2089
 
2193
2091
        """See BranchFormat.get_format_description()."""
2194
2092
        return "Branch format 8"
2195
2093
 
2196
 
    def initialize(self, a_bzrdir, name=None, repository=None,
2197
 
                   append_revisions_only=None):
 
2094
    def initialize(self, a_bzrdir, name=None):
2198
2095
        """Create a branch of this format in a_bzrdir."""
2199
2096
        utf8_files = [('last-revision', '0 null:\n'),
2200
 
                      ('branch.conf',
2201
 
                          self._get_initial_config(append_revisions_only)),
 
2097
                      ('branch.conf', ''),
2202
2098
                      ('tags', ''),
2203
2099
                      ('references', '')
2204
2100
                      ]
2205
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
2101
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2102
 
 
2103
    def __init__(self):
 
2104
        super(BzrBranchFormat8, self).__init__()
 
2105
        self._matchingbzrdir.repository_format = \
 
2106
            RepositoryFormatKnitPack5RichRoot()
2206
2107
 
2207
2108
    def make_tags(self, branch):
2208
2109
        """See bzrlib.branch.BranchFormat.make_tags()."""
2209
 
        return _mod_tag.BasicTags(branch)
 
2110
        return BasicTags(branch)
2210
2111
 
2211
2112
    def supports_set_append_revisions_only(self):
2212
2113
        return True
2217
2118
    supports_reference_locations = True
2218
2119
 
2219
2120
 
2220
 
class BzrBranchFormat7(BranchFormatMetadir):
 
2121
class BzrBranchFormat7(BzrBranchFormat8):
2221
2122
    """Branch format with last-revision, tags, and a stacked location pointer.
2222
2123
 
2223
2124
    The stacked location pointer is passed down to the repository and requires
2226
2127
    This format was introduced in bzr 1.6.
2227
2128
    """
2228
2129
 
2229
 
    def initialize(self, a_bzrdir, name=None, repository=None,
2230
 
                   append_revisions_only=None):
 
2130
    def initialize(self, a_bzrdir, name=None):
2231
2131
        """Create a branch of this format in a_bzrdir."""
2232
2132
        utf8_files = [('last-revision', '0 null:\n'),
2233
 
                      ('branch.conf',
2234
 
                          self._get_initial_config(append_revisions_only)),
 
2133
                      ('branch.conf', ''),
2235
2134
                      ('tags', ''),
2236
2135
                      ]
2237
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
2136
        return self._initialize_helper(a_bzrdir, utf8_files, name)
2238
2137
 
2239
2138
    def _branch_class(self):
2240
2139
        return BzrBranch7
2241
2140
 
2242
 
    @classmethod
2243
 
    def get_format_string(cls):
 
2141
    def get_format_string(self):
2244
2142
        """See BranchFormat.get_format_string()."""
2245
2143
        return "Bazaar Branch Format 7 (needs bzr 1.6)\n"
2246
2144
 
2251
2149
    def supports_set_append_revisions_only(self):
2252
2150
        return True
2253
2151
 
2254
 
    def supports_stacking(self):
2255
 
        return True
2256
 
 
2257
 
    def make_tags(self, branch):
2258
 
        """See bzrlib.branch.BranchFormat.make_tags()."""
2259
 
        return _mod_tag.BasicTags(branch)
2260
 
 
2261
2152
    supports_reference_locations = False
2262
2153
 
2263
2154
 
2264
 
class BranchReferenceFormat(BranchFormatMetadir):
 
2155
class BranchReferenceFormat(BranchFormat):
2265
2156
    """Bzr branch reference format.
2266
2157
 
2267
2158
    Branch references are used in implementing checkouts, they
2272
2163
     - a format string
2273
2164
    """
2274
2165
 
2275
 
    @classmethod
2276
 
    def get_format_string(cls):
 
2166
    def get_format_string(self):
2277
2167
        """See BranchFormat.get_format_string()."""
2278
2168
        return "Bazaar-NG Branch Reference Format 1\n"
2279
2169
 
2291
2181
        transport = a_bzrdir.get_branch_transport(None, name=name)
2292
2182
        location = transport.put_bytes('location', to_branch.base)
2293
2183
 
2294
 
    def initialize(self, a_bzrdir, name=None, target_branch=None,
2295
 
            repository=None, append_revisions_only=None):
 
2184
    def initialize(self, a_bzrdir, name=None, target_branch=None):
2296
2185
        """Create a branch of this format in a_bzrdir."""
2297
2186
        if target_branch is None:
2298
2187
            # this format does not implement branch itself, thus the implicit
2299
2188
            # creation contract must see it as uninitializable
2300
2189
            raise errors.UninitializableFormat(self)
2301
2190
        mutter('creating branch reference in %s', a_bzrdir.user_url)
2302
 
        if a_bzrdir._format.fixed_components:
2303
 
            raise errors.IncompatibleFormat(self, a_bzrdir._format)
2304
2191
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
2305
2192
        branch_transport.put_bytes('location',
2306
 
            target_branch.user_url)
 
2193
            target_branch.bzrdir.user_url)
2307
2194
        branch_transport.put_bytes('format', self.get_format_string())
2308
2195
        branch = self.open(
2309
2196
            a_bzrdir, name, _found=True,
2311
2198
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2312
2199
        return branch
2313
2200
 
 
2201
    def __init__(self):
 
2202
        super(BranchReferenceFormat, self).__init__()
 
2203
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
2204
        self._matchingbzrdir.set_branch_format(self)
 
2205
 
2314
2206
    def _make_reference_clone_function(format, a_branch):
2315
2207
        """Create a clone() routine for a branch dynamically."""
2316
2208
        def clone(to_bzrdir, revision_id=None,
2323
2215
        return clone
2324
2216
 
2325
2217
    def open(self, a_bzrdir, name=None, _found=False, location=None,
2326
 
             possible_transports=None, ignore_fallbacks=False,
2327
 
             found_repository=None):
 
2218
             possible_transports=None, ignore_fallbacks=False):
2328
2219
        """Return the branch that the branch reference in a_bzrdir points at.
2329
2220
 
2330
2221
        :param a_bzrdir: A BzrDir that contains a branch.
2339
2230
        :param possible_transports: An optional reusable transports list.
2340
2231
        """
2341
2232
        if not _found:
2342
 
            format = BranchFormatMetadir.find_format(a_bzrdir, name=name)
 
2233
            format = BranchFormat.find_format(a_bzrdir, name=name)
2343
2234
            if format.__class__ != self.__class__:
2344
2235
                raise AssertionError("wrong format %r found for %r" %
2345
2236
                    (format, self))
2346
2237
        if location is None:
2347
2238
            location = self.get_reference(a_bzrdir, name)
2348
 
        real_bzrdir = controldir.ControlDir.open(
 
2239
        real_bzrdir = bzrdir.BzrDir.open(
2349
2240
            location, possible_transports=possible_transports)
2350
2241
        result = real_bzrdir.open_branch(name=name, 
2351
 
            ignore_fallbacks=ignore_fallbacks,
2352
 
            possible_transports=possible_transports)
 
2242
            ignore_fallbacks=ignore_fallbacks)
2353
2243
        # this changes the behaviour of result.clone to create a new reference
2354
2244
        # rather than a copy of the content of the branch.
2355
2245
        # I did not use a proxy object because that needs much more extensive
2362
2252
        return result
2363
2253
 
2364
2254
 
2365
 
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
2366
 
    """Branch format registry."""
2367
 
 
2368
 
    def __init__(self, other_registry=None):
2369
 
        super(BranchFormatRegistry, self).__init__(other_registry)
2370
 
        self._default_format = None
2371
 
 
2372
 
    def set_default(self, format):
2373
 
        self._default_format = format
2374
 
 
2375
 
    def get_default(self):
2376
 
        return self._default_format
2377
 
 
2378
 
 
2379
2255
network_format_registry = registry.FormatRegistry()
2380
2256
"""Registry of formats indexed by their network name.
2381
2257
 
2384
2260
BranchFormat.network_name() for more detail.
2385
2261
"""
2386
2262
 
2387
 
format_registry = BranchFormatRegistry(network_format_registry)
2388
 
 
2389
2263
 
2390
2264
# formats which have no format string are not discoverable
2391
2265
# and not independently creatable, so are not registered.
2393
2267
__format6 = BzrBranchFormat6()
2394
2268
__format7 = BzrBranchFormat7()
2395
2269
__format8 = BzrBranchFormat8()
2396
 
format_registry.register(__format5)
2397
 
format_registry.register(BranchReferenceFormat())
2398
 
format_registry.register(__format6)
2399
 
format_registry.register(__format7)
2400
 
format_registry.register(__format8)
2401
 
format_registry.set_default(__format7)
 
2270
BranchFormat.register_format(__format5)
 
2271
BranchFormat.register_format(BranchReferenceFormat())
 
2272
BranchFormat.register_format(__format6)
 
2273
BranchFormat.register_format(__format7)
 
2274
BranchFormat.register_format(__format8)
 
2275
BranchFormat.set_default_format(__format7)
 
2276
_legacy_formats = [BzrBranchFormat4(),
 
2277
    ]
 
2278
network_format_registry.register(
 
2279
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
2402
2280
 
2403
2281
 
2404
2282
class BranchWriteLockResult(LogicalLockResult):
2436
2314
 
2437
2315
    def __init__(self, _format=None,
2438
2316
                 _control_files=None, a_bzrdir=None, name=None,
2439
 
                 _repository=None, ignore_fallbacks=False,
2440
 
                 possible_transports=None):
 
2317
                 _repository=None, ignore_fallbacks=False):
2441
2318
        """Create new branch object at a particular location."""
2442
2319
        if a_bzrdir is None:
2443
2320
            raise ValueError('a_bzrdir must be supplied')
2444
2321
        else:
2445
2322
            self.bzrdir = a_bzrdir
2446
 
        self._user_transport = self.bzrdir.transport.clone('..')
2447
 
        if name is not None:
2448
 
            self._user_transport.set_segment_parameter(
2449
 
                "branch", urlutils.escape(name))
2450
 
        self._base = self._user_transport.base
 
2323
        self._base = self.bzrdir.transport.clone('..').base
2451
2324
        self.name = name
 
2325
        # XXX: We should be able to just do
 
2326
        #   self.base = self.bzrdir.root_transport.base
 
2327
        # but this does not quite work yet -- mbp 20080522
2452
2328
        self._format = _format
2453
2329
        if _control_files is None:
2454
2330
            raise ValueError('BzrBranch _control_files is None')
2455
2331
        self.control_files = _control_files
2456
2332
        self._transport = _control_files._transport
2457
2333
        self.repository = _repository
2458
 
        Branch.__init__(self, possible_transports)
 
2334
        Branch.__init__(self)
2459
2335
 
2460
2336
    def __str__(self):
2461
 
        return '%s(%s)' % (self.__class__.__name__, self.user_url)
 
2337
        if self.name is None:
 
2338
            return '%s(%s)' % (self.__class__.__name__, self.user_url)
 
2339
        else:
 
2340
            return '%s(%s,%s)' % (self.__class__.__name__, self.user_url,
 
2341
                self.name)
2462
2342
 
2463
2343
    __repr__ = __str__
2464
2344
 
2468
2348
 
2469
2349
    base = property(_get_base, doc="The URL for the root of this branch.")
2470
2350
 
2471
 
    @property
2472
 
    def user_transport(self):
2473
 
        return self._user_transport
2474
 
 
2475
2351
    def _get_config(self):
2476
 
        return _mod_config.TransportConfig(self._transport, 'branch.conf')
2477
 
 
2478
 
    def _get_config_store(self):
2479
 
        return _mod_config.BranchStore(self)
 
2352
        return TransportConfig(self._transport, 'branch.conf')
2480
2353
 
2481
2354
    def is_locked(self):
2482
2355
        return self.control_files.is_locked()
2557
2430
        """See Branch.print_file."""
2558
2431
        return self.repository.print_file(file, revision_id)
2559
2432
 
 
2433
    def _write_revision_history(self, history):
 
2434
        """Factored out of set_revision_history.
 
2435
 
 
2436
        This performs the actual writing to disk.
 
2437
        It is intended to be called by BzrBranch5.set_revision_history."""
 
2438
        self._transport.put_bytes(
 
2439
            'revision-history', '\n'.join(history),
 
2440
            mode=self.bzrdir._get_file_mode())
 
2441
 
 
2442
    @needs_write_lock
 
2443
    def set_revision_history(self, rev_history):
 
2444
        """See Branch.set_revision_history."""
 
2445
        if 'evil' in debug.debug_flags:
 
2446
            mutter_callsite(3, "set_revision_history scales with history.")
 
2447
        check_not_reserved_id = _mod_revision.check_not_reserved_id
 
2448
        for rev_id in rev_history:
 
2449
            check_not_reserved_id(rev_id)
 
2450
        if Branch.hooks['post_change_branch_tip']:
 
2451
            # Don't calculate the last_revision_info() if there are no hooks
 
2452
            # that will use it.
 
2453
            old_revno, old_revid = self.last_revision_info()
 
2454
        if len(rev_history) == 0:
 
2455
            revid = _mod_revision.NULL_REVISION
 
2456
        else:
 
2457
            revid = rev_history[-1]
 
2458
        self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
 
2459
        self._write_revision_history(rev_history)
 
2460
        self._clear_cached_state()
 
2461
        self._cache_revision_history(rev_history)
 
2462
        for hook in Branch.hooks['set_rh']:
 
2463
            hook(self, rev_history)
 
2464
        if Branch.hooks['post_change_branch_tip']:
 
2465
            self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2466
 
 
2467
    def _synchronize_history(self, destination, revision_id):
 
2468
        """Synchronize last revision and revision history between branches.
 
2469
 
 
2470
        This version is most efficient when the destination is also a
 
2471
        BzrBranch5, but works for BzrBranch6 as long as the revision
 
2472
        history is the true lefthand parent history, and all of the revisions
 
2473
        are in the destination's repository.  If not, set_revision_history
 
2474
        will fail.
 
2475
 
 
2476
        :param destination: The branch to copy the history into
 
2477
        :param revision_id: The revision-id to truncate history at.  May
 
2478
          be None to copy complete history.
 
2479
        """
 
2480
        if not isinstance(destination._format, BzrBranchFormat5):
 
2481
            super(BzrBranch, self)._synchronize_history(
 
2482
                destination, revision_id)
 
2483
            return
 
2484
        if revision_id == _mod_revision.NULL_REVISION:
 
2485
            new_history = []
 
2486
        else:
 
2487
            new_history = self.revision_history()
 
2488
        if revision_id is not None and new_history != []:
 
2489
            try:
 
2490
                new_history = new_history[:new_history.index(revision_id) + 1]
 
2491
            except ValueError:
 
2492
                rev = self.repository.get_revision(revision_id)
 
2493
                new_history = rev.get_history(self.repository)[1:]
 
2494
        destination.set_revision_history(new_history)
 
2495
 
2560
2496
    @needs_write_lock
2561
2497
    def set_last_revision_info(self, revno, revision_id):
2562
 
        if not revision_id or not isinstance(revision_id, basestring):
2563
 
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
 
2498
        """Set the last revision of this branch.
 
2499
 
 
2500
        The caller is responsible for checking that the revno is correct
 
2501
        for this revision id.
 
2502
 
 
2503
        It may be possible to set the branch last revision to an id not
 
2504
        present in the repository.  However, branches can also be
 
2505
        configured to check constraints on history, in which case this may not
 
2506
        be permitted.
 
2507
        """
2564
2508
        revision_id = _mod_revision.ensure_null(revision_id)
2565
 
        old_revno, old_revid = self.last_revision_info()
2566
 
        if self.get_append_revisions_only():
2567
 
            self._check_history_violation(revision_id)
2568
 
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
2569
 
        self._write_last_revision_info(revno, revision_id)
2570
 
        self._clear_cached_state()
2571
 
        self._last_revision_info_cache = revno, revision_id
2572
 
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2509
        # this old format stores the full history, but this api doesn't
 
2510
        # provide it, so we must generate, and might as well check it's
 
2511
        # correct
 
2512
        history = self._lefthand_history(revision_id)
 
2513
        if len(history) != revno:
 
2514
            raise AssertionError('%d != %d' % (len(history), revno))
 
2515
        self.set_revision_history(history)
 
2516
 
 
2517
    def _gen_revision_history(self):
 
2518
        history = self._transport.get_bytes('revision-history').split('\n')
 
2519
        if history[-1:] == ['']:
 
2520
            # There shouldn't be a trailing newline, but just in case.
 
2521
            history.pop()
 
2522
        return history
 
2523
 
 
2524
    @needs_write_lock
 
2525
    def generate_revision_history(self, revision_id, last_rev=None,
 
2526
        other_branch=None):
 
2527
        """Create a new revision history that will finish with revision_id.
 
2528
 
 
2529
        :param revision_id: the new tip to use.
 
2530
        :param last_rev: The previous last_revision. If not None, then this
 
2531
            must be a ancestory of revision_id, or DivergedBranches is raised.
 
2532
        :param other_branch: The other branch that DivergedBranches should
 
2533
            raise with respect to.
 
2534
        """
 
2535
        self.set_revision_history(self._lefthand_history(revision_id,
 
2536
            last_rev, other_branch))
2573
2537
 
2574
2538
    def basis_tree(self):
2575
2539
        """See Branch.basis_tree."""
2584
2548
                pass
2585
2549
        return None
2586
2550
 
 
2551
    def _basic_push(self, target, overwrite, stop_revision):
 
2552
        """Basic implementation of push without bound branches or hooks.
 
2553
 
 
2554
        Must be called with source read locked and target write locked.
 
2555
        """
 
2556
        result = BranchPushResult()
 
2557
        result.source_branch = self
 
2558
        result.target_branch = target
 
2559
        result.old_revno, result.old_revid = target.last_revision_info()
 
2560
        self.update_references(target)
 
2561
        if result.old_revid != self.last_revision():
 
2562
            # We assume that during 'push' this repository is closer than
 
2563
            # the target.
 
2564
            graph = self.repository.get_graph(target.repository)
 
2565
            target.update_revisions(self, stop_revision,
 
2566
                overwrite=overwrite, graph=graph)
 
2567
        if self._push_should_merge_tags():
 
2568
            result.tag_conflicts = self.tags.merge_to(target.tags,
 
2569
                overwrite)
 
2570
        result.new_revno, result.new_revid = target.last_revision_info()
 
2571
        return result
 
2572
 
2587
2573
    def get_stacked_on_url(self):
2588
2574
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
2589
2575
 
2600
2586
            self._transport.put_bytes('parent', url + '\n',
2601
2587
                mode=self.bzrdir._get_file_mode())
2602
2588
 
 
2589
 
 
2590
class BzrBranch5(BzrBranch):
 
2591
    """A format 5 branch. This supports new features over plain branches.
 
2592
 
 
2593
    It has support for a master_branch which is the data for bound branches.
 
2594
    """
 
2595
 
 
2596
    def get_bound_location(self):
 
2597
        try:
 
2598
            return self._transport.get_bytes('bound')[:-1]
 
2599
        except errors.NoSuchFile:
 
2600
            return None
 
2601
 
 
2602
    @needs_read_lock
 
2603
    def get_master_branch(self, possible_transports=None):
 
2604
        """Return the branch we are bound to.
 
2605
 
 
2606
        :return: Either a Branch, or None
 
2607
 
 
2608
        This could memoise the branch, but if thats done
 
2609
        it must be revalidated on each new lock.
 
2610
        So for now we just don't memoise it.
 
2611
        # RBC 20060304 review this decision.
 
2612
        """
 
2613
        bound_loc = self.get_bound_location()
 
2614
        if not bound_loc:
 
2615
            return None
 
2616
        try:
 
2617
            return Branch.open(bound_loc,
 
2618
                               possible_transports=possible_transports)
 
2619
        except (errors.NotBranchError, errors.ConnectionError), e:
 
2620
            raise errors.BoundBranchConnectionFailure(
 
2621
                    self, bound_loc, e)
 
2622
 
2603
2623
    @needs_write_lock
2604
 
    def unbind(self):
2605
 
        """If bound, unbind"""
2606
 
        return self.set_bound_location(None)
 
2624
    def set_bound_location(self, location):
 
2625
        """Set the target where this branch is bound to.
 
2626
 
 
2627
        :param location: URL to the target branch
 
2628
        """
 
2629
        if location:
 
2630
            self._transport.put_bytes('bound', location+'\n',
 
2631
                mode=self.bzrdir._get_file_mode())
 
2632
        else:
 
2633
            try:
 
2634
                self._transport.delete('bound')
 
2635
            except errors.NoSuchFile:
 
2636
                return False
 
2637
            return True
2607
2638
 
2608
2639
    @needs_write_lock
2609
2640
    def bind(self, other):
2631
2662
        # history around
2632
2663
        self.set_bound_location(other.base)
2633
2664
 
2634
 
    def get_bound_location(self):
2635
 
        try:
2636
 
            return self._transport.get_bytes('bound')[:-1]
2637
 
        except errors.NoSuchFile:
2638
 
            return None
2639
 
 
2640
 
    @needs_read_lock
2641
 
    def get_master_branch(self, possible_transports=None):
2642
 
        """Return the branch we are bound to.
2643
 
 
2644
 
        :return: Either a Branch, or None
2645
 
        """
2646
 
        if self._master_branch_cache is None:
2647
 
            self._master_branch_cache = self._get_master_branch(
2648
 
                possible_transports)
2649
 
        return self._master_branch_cache
2650
 
 
2651
 
    def _get_master_branch(self, possible_transports):
2652
 
        bound_loc = self.get_bound_location()
2653
 
        if not bound_loc:
2654
 
            return None
2655
 
        try:
2656
 
            return Branch.open(bound_loc,
2657
 
                               possible_transports=possible_transports)
2658
 
        except (errors.NotBranchError, errors.ConnectionError), e:
2659
 
            raise errors.BoundBranchConnectionFailure(
2660
 
                    self, bound_loc, e)
2661
 
 
2662
2665
    @needs_write_lock
2663
 
    def set_bound_location(self, location):
2664
 
        """Set the target where this branch is bound to.
2665
 
 
2666
 
        :param location: URL to the target branch
2667
 
        """
2668
 
        self._master_branch_cache = None
2669
 
        if location:
2670
 
            self._transport.put_bytes('bound', location+'\n',
2671
 
                mode=self.bzrdir._get_file_mode())
2672
 
        else:
2673
 
            try:
2674
 
                self._transport.delete('bound')
2675
 
            except errors.NoSuchFile:
2676
 
                return False
2677
 
            return True
 
2666
    def unbind(self):
 
2667
        """If bound, unbind"""
 
2668
        return self.set_bound_location(None)
2678
2669
 
2679
2670
    @needs_write_lock
2680
2671
    def update(self, possible_transports=None):
2693
2684
            return old_tip
2694
2685
        return None
2695
2686
 
2696
 
    def _read_last_revision_info(self):
2697
 
        revision_string = self._transport.get_bytes('last-revision')
2698
 
        revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
2699
 
        revision_id = cache_utf8.get_cached_utf8(revision_id)
2700
 
        revno = int(revno)
2701
 
        return revno, revision_id
2702
 
 
2703
 
    def _write_last_revision_info(self, revno, revision_id):
2704
 
        """Simply write out the revision id, with no checks.
2705
 
 
2706
 
        Use set_last_revision_info to perform this safely.
2707
 
 
2708
 
        Does not update the revision_history cache.
2709
 
        """
2710
 
        revision_id = _mod_revision.ensure_null(revision_id)
2711
 
        out_string = '%d %s\n' % (revno, revision_id)
2712
 
        self._transport.put_bytes('last-revision', out_string,
2713
 
            mode=self.bzrdir._get_file_mode())
2714
 
 
2715
 
 
2716
 
class FullHistoryBzrBranch(BzrBranch):
2717
 
    """Bzr branch which contains the full revision history."""
2718
 
 
2719
 
    @needs_write_lock
2720
 
    def set_last_revision_info(self, revno, revision_id):
2721
 
        if not revision_id or not isinstance(revision_id, basestring):
2722
 
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2723
 
        revision_id = _mod_revision.ensure_null(revision_id)
2724
 
        # this old format stores the full history, but this api doesn't
2725
 
        # provide it, so we must generate, and might as well check it's
2726
 
        # correct
2727
 
        history = self._lefthand_history(revision_id)
2728
 
        if len(history) != revno:
2729
 
            raise AssertionError('%d != %d' % (len(history), revno))
2730
 
        self._set_revision_history(history)
2731
 
 
2732
 
    def _read_last_revision_info(self):
2733
 
        rh = self._revision_history()
2734
 
        revno = len(rh)
2735
 
        if revno:
2736
 
            return (revno, rh[-1])
2737
 
        else:
2738
 
            return (0, _mod_revision.NULL_REVISION)
2739
 
 
2740
 
    @deprecated_method(deprecated_in((2, 4, 0)))
2741
 
    @needs_write_lock
2742
 
    def set_revision_history(self, rev_history):
2743
 
        """See Branch.set_revision_history."""
2744
 
        self._set_revision_history(rev_history)
2745
 
 
2746
 
    def _set_revision_history(self, rev_history):
2747
 
        if 'evil' in debug.debug_flags:
2748
 
            mutter_callsite(3, "set_revision_history scales with history.")
2749
 
        check_not_reserved_id = _mod_revision.check_not_reserved_id
2750
 
        for rev_id in rev_history:
2751
 
            check_not_reserved_id(rev_id)
2752
 
        if Branch.hooks['post_change_branch_tip']:
2753
 
            # Don't calculate the last_revision_info() if there are no hooks
2754
 
            # that will use it.
2755
 
            old_revno, old_revid = self.last_revision_info()
2756
 
        if len(rev_history) == 0:
2757
 
            revid = _mod_revision.NULL_REVISION
2758
 
        else:
2759
 
            revid = rev_history[-1]
2760
 
        self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
2761
 
        self._write_revision_history(rev_history)
2762
 
        self._clear_cached_state()
2763
 
        self._cache_revision_history(rev_history)
2764
 
        for hook in Branch.hooks['set_rh']:
2765
 
            hook(self, rev_history)
2766
 
        if Branch.hooks['post_change_branch_tip']:
2767
 
            self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2768
 
 
2769
 
    def _write_revision_history(self, history):
2770
 
        """Factored out of set_revision_history.
2771
 
 
2772
 
        This performs the actual writing to disk.
2773
 
        It is intended to be called by set_revision_history."""
2774
 
        self._transport.put_bytes(
2775
 
            'revision-history', '\n'.join(history),
2776
 
            mode=self.bzrdir._get_file_mode())
2777
 
 
2778
 
    def _gen_revision_history(self):
2779
 
        history = self._transport.get_bytes('revision-history').split('\n')
2780
 
        if history[-1:] == ['']:
2781
 
            # There shouldn't be a trailing newline, but just in case.
2782
 
            history.pop()
2783
 
        return history
2784
 
 
2785
 
    def _synchronize_history(self, destination, revision_id):
2786
 
        if not isinstance(destination, FullHistoryBzrBranch):
2787
 
            super(BzrBranch, self)._synchronize_history(
2788
 
                destination, revision_id)
2789
 
            return
2790
 
        if revision_id == _mod_revision.NULL_REVISION:
2791
 
            new_history = []
2792
 
        else:
2793
 
            new_history = self._revision_history()
2794
 
        if revision_id is not None and new_history != []:
2795
 
            try:
2796
 
                new_history = new_history[:new_history.index(revision_id) + 1]
2797
 
            except ValueError:
2798
 
                rev = self.repository.get_revision(revision_id)
2799
 
                new_history = rev.get_history(self.repository)[1:]
2800
 
        destination._set_revision_history(new_history)
2801
 
 
2802
 
    @needs_write_lock
2803
 
    def generate_revision_history(self, revision_id, last_rev=None,
2804
 
        other_branch=None):
2805
 
        """Create a new revision history that will finish with revision_id.
2806
 
 
2807
 
        :param revision_id: the new tip to use.
2808
 
        :param last_rev: The previous last_revision. If not None, then this
2809
 
            must be a ancestory of revision_id, or DivergedBranches is raised.
2810
 
        :param other_branch: The other branch that DivergedBranches should
2811
 
            raise with respect to.
2812
 
        """
2813
 
        self._set_revision_history(self._lefthand_history(revision_id,
2814
 
            last_rev, other_branch))
2815
 
 
2816
 
 
2817
 
class BzrBranch5(FullHistoryBzrBranch):
2818
 
    """A format 5 branch. This supports new features over plain branches.
2819
 
 
2820
 
    It has support for a master_branch which is the data for bound branches.
2821
 
    """
2822
 
 
2823
 
 
2824
 
class BzrBranch8(BzrBranch):
 
2687
 
 
2688
class BzrBranch8(BzrBranch5):
2825
2689
    """A branch that stores tree-reference locations."""
2826
2690
 
2827
 
    def _open_hook(self, possible_transports=None):
 
2691
    def _open_hook(self):
2828
2692
        if self._ignore_fallbacks:
2829
2693
            return
2830
 
        if possible_transports is None:
2831
 
            possible_transports = [self.bzrdir.root_transport]
2832
2694
        try:
2833
2695
            url = self.get_stacked_on_url()
2834
2696
        except (errors.UnstackableRepositoryFormat, errors.NotStacked,
2842
2704
                    raise AssertionError(
2843
2705
                        "'transform_fallback_location' hook %s returned "
2844
2706
                        "None, not a URL." % hook_name)
2845
 
            self._activate_fallback_location(url,
2846
 
                possible_transports=possible_transports)
 
2707
            self._activate_fallback_location(url)
2847
2708
 
2848
2709
    def __init__(self, *args, **kwargs):
2849
2710
        self._ignore_fallbacks = kwargs.get('ignore_fallbacks', False)
2856
2717
        self._last_revision_info_cache = None
2857
2718
        self._reference_info = None
2858
2719
 
 
2720
    def _last_revision_info(self):
 
2721
        revision_string = self._transport.get_bytes('last-revision')
 
2722
        revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
 
2723
        revision_id = cache_utf8.get_cached_utf8(revision_id)
 
2724
        revno = int(revno)
 
2725
        return revno, revision_id
 
2726
 
 
2727
    def _write_last_revision_info(self, revno, revision_id):
 
2728
        """Simply write out the revision id, with no checks.
 
2729
 
 
2730
        Use set_last_revision_info to perform this safely.
 
2731
 
 
2732
        Does not update the revision_history cache.
 
2733
        Intended to be called by set_last_revision_info and
 
2734
        _write_revision_history.
 
2735
        """
 
2736
        revision_id = _mod_revision.ensure_null(revision_id)
 
2737
        out_string = '%d %s\n' % (revno, revision_id)
 
2738
        self._transport.put_bytes('last-revision', out_string,
 
2739
            mode=self.bzrdir._get_file_mode())
 
2740
 
 
2741
    @needs_write_lock
 
2742
    def set_last_revision_info(self, revno, revision_id):
 
2743
        revision_id = _mod_revision.ensure_null(revision_id)
 
2744
        old_revno, old_revid = self.last_revision_info()
 
2745
        if self._get_append_revisions_only():
 
2746
            self._check_history_violation(revision_id)
 
2747
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
 
2748
        self._write_last_revision_info(revno, revision_id)
 
2749
        self._clear_cached_state()
 
2750
        self._last_revision_info_cache = revno, revision_id
 
2751
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2752
 
 
2753
    def _synchronize_history(self, destination, revision_id):
 
2754
        """Synchronize last revision and revision history between branches.
 
2755
 
 
2756
        :see: Branch._synchronize_history
 
2757
        """
 
2758
        # XXX: The base Branch has a fast implementation of this method based
 
2759
        # on set_last_revision_info, but BzrBranch/BzrBranch5 have a slower one
 
2760
        # that uses set_revision_history.  This class inherits from BzrBranch5,
 
2761
        # but wants the fast implementation, so it calls
 
2762
        # Branch._synchronize_history directly.
 
2763
        Branch._synchronize_history(self, destination, revision_id)
 
2764
 
2859
2765
    def _check_history_violation(self, revision_id):
2860
 
        current_revid = self.last_revision()
2861
 
        last_revision = _mod_revision.ensure_null(current_revid)
 
2766
        last_revision = _mod_revision.ensure_null(self.last_revision())
2862
2767
        if _mod_revision.is_null(last_revision):
2863
2768
            return
2864
 
        graph = self.repository.get_graph()
2865
 
        for lh_ancestor in graph.iter_lefthand_ancestry(revision_id):
2866
 
            if lh_ancestor == current_revid:
2867
 
                return
2868
 
        raise errors.AppendRevisionsOnlyViolation(self.user_url)
 
2769
        if last_revision not in self._lefthand_history(revision_id):
 
2770
            raise errors.AppendRevisionsOnlyViolation(self.user_url)
2869
2771
 
2870
2772
    def _gen_revision_history(self):
2871
2773
        """Generate the revision history from last revision
2874
2776
        self._extend_partial_history(stop_index=last_revno-1)
2875
2777
        return list(reversed(self._partial_revision_history_cache))
2876
2778
 
 
2779
    def _write_revision_history(self, history):
 
2780
        """Factored out of set_revision_history.
 
2781
 
 
2782
        This performs the actual writing to disk, with format-specific checks.
 
2783
        It is intended to be called by BzrBranch5.set_revision_history.
 
2784
        """
 
2785
        if len(history) == 0:
 
2786
            last_revision = 'null:'
 
2787
        else:
 
2788
            if history != self._lefthand_history(history[-1]):
 
2789
                raise errors.NotLefthandHistory(history)
 
2790
            last_revision = history[-1]
 
2791
        if self._get_append_revisions_only():
 
2792
            self._check_history_violation(last_revision)
 
2793
        self._write_last_revision_info(len(history), last_revision)
 
2794
 
2877
2795
    @needs_write_lock
2878
2796
    def _set_parent_location(self, url):
2879
2797
        """Set the parent branch"""
2965
2883
 
2966
2884
    def set_bound_location(self, location):
2967
2885
        """See Branch.set_push_location."""
2968
 
        self._master_branch_cache = None
2969
2886
        result = None
2970
 
        conf = self.get_config_stack()
 
2887
        config = self.get_config()
2971
2888
        if location is None:
2972
 
            if not conf.get('bound'):
 
2889
            if config.get_user_option('bound') != 'True':
2973
2890
                return False
2974
2891
            else:
2975
 
                conf.set('bound', 'False')
 
2892
                config.set_user_option('bound', 'False', warn_masked=True)
2976
2893
                return True
2977
2894
        else:
2978
2895
            self._set_config_location('bound_location', location,
2979
 
                                      config=conf)
2980
 
            conf.set('bound', 'True')
 
2896
                                      config=config)
 
2897
            config.set_user_option('bound', 'True', warn_masked=True)
2981
2898
        return True
2982
2899
 
2983
2900
    def _get_bound_location(self, bound):
2984
2901
        """Return the bound location in the config file.
2985
2902
 
2986
2903
        Return None if the bound parameter does not match"""
2987
 
        conf = self.get_config_stack()
2988
 
        if conf.get('bound') != bound:
 
2904
        config = self.get_config()
 
2905
        config_bound = (config.get_user_option('bound') == 'True')
 
2906
        if config_bound != bound:
2989
2907
            return None
2990
 
        return self._get_config_location('bound_location', config=conf)
 
2908
        return self._get_config_location('bound_location', config=config)
2991
2909
 
2992
2910
    def get_bound_location(self):
2993
2911
        """See Branch.set_push_location."""
3001
2919
        # you can always ask for the URL; but you might not be able to use it
3002
2920
        # if the repo can't support stacking.
3003
2921
        ## self._check_stackable_repo()
3004
 
        # stacked_on_location is only ever defined in branch.conf, so don't
3005
 
        # waste effort reading the whole stack of config files.
3006
 
        conf = _mod_config.BranchOnlyStack(self)
3007
 
        stacked_url = self._get_config_location('stacked_on_location',
3008
 
                                                config=conf)
 
2922
        stacked_url = self._get_config_location('stacked_on_location')
3009
2923
        if stacked_url is None:
3010
2924
            raise errors.NotStacked(self)
3011
2925
        return stacked_url
3012
2926
 
 
2927
    def _get_append_revisions_only(self):
 
2928
        return self.get_config(
 
2929
            ).get_user_option_as_bool('append_revisions_only')
 
2930
 
 
2931
    @needs_write_lock
 
2932
    def generate_revision_history(self, revision_id, last_rev=None,
 
2933
                                  other_branch=None):
 
2934
        """See BzrBranch5.generate_revision_history"""
 
2935
        history = self._lefthand_history(revision_id, last_rev, other_branch)
 
2936
        revno = len(history)
 
2937
        self.set_last_revision_info(revno, revision_id)
 
2938
 
3013
2939
    @needs_read_lock
3014
2940
    def get_rev_id(self, revno, history=None):
3015
2941
        """Find the revision id of the specified revno."""
3039
2965
        try:
3040
2966
            index = self._partial_revision_history_cache.index(revision_id)
3041
2967
        except ValueError:
3042
 
            try:
3043
 
                self._extend_partial_history(stop_revision=revision_id)
3044
 
            except errors.RevisionNotPresent, e:
3045
 
                raise errors.GhostRevisionsHaveNoRevno(revision_id, e.revision_id)
 
2968
            self._extend_partial_history(stop_revision=revision_id)
3046
2969
            index = len(self._partial_revision_history_cache) - 1
3047
 
            if index < 0:
3048
 
                raise errors.NoSuchRevision(self, revision_id)
3049
2970
            if self._partial_revision_history_cache[index] != revision_id:
3050
2971
                raise errors.NoSuchRevision(self, revision_id)
3051
2972
        return self.revno() - index
3103
3024
    :ivar local_branch: target branch if there is a Master, else None
3104
3025
    :ivar target_branch: Target/destination branch object. (write locked)
3105
3026
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
3106
 
    :ivar tag_updates: A dict with new tags, see BasicTags.merge_to
3107
3027
    """
3108
3028
 
3109
 
    @deprecated_method(deprecated_in((2, 3, 0)))
3110
3029
    def __int__(self):
3111
 
        """Return the relative change in revno.
3112
 
 
3113
 
        :deprecated: Use `new_revno` and `old_revno` instead.
3114
 
        """
 
3030
        # DEPRECATED: pull used to return the change in revno
3115
3031
        return self.new_revno - self.old_revno
3116
3032
 
3117
3033
    def report(self, to_file):
3118
 
        tag_conflicts = getattr(self, "tag_conflicts", None)
3119
 
        tag_updates = getattr(self, "tag_updates", None)
3120
3034
        if not is_quiet():
3121
 
            if self.old_revid != self.new_revid:
 
3035
            if self.old_revid == self.new_revid:
 
3036
                to_file.write('No revisions to pull.\n')
 
3037
            else:
3122
3038
                to_file.write('Now on revision %d.\n' % self.new_revno)
3123
 
            if tag_updates:
3124
 
                to_file.write('%d tag(s) updated.\n' % len(tag_updates))
3125
 
            if self.old_revid == self.new_revid and not tag_updates:
3126
 
                if not tag_conflicts:
3127
 
                    to_file.write('No revisions or tags to pull.\n')
3128
 
                else:
3129
 
                    to_file.write('No revisions to pull.\n')
3130
3039
        self._show_tag_conficts(to_file)
3131
3040
 
3132
3041
 
3149
3058
        target, otherwise it will be None.
3150
3059
    """
3151
3060
 
3152
 
    @deprecated_method(deprecated_in((2, 3, 0)))
3153
3061
    def __int__(self):
3154
 
        """Return the relative change in revno.
3155
 
 
3156
 
        :deprecated: Use `new_revno` and `old_revno` instead.
3157
 
        """
 
3062
        # DEPRECATED: push used to return the change in revno
3158
3063
        return self.new_revno - self.old_revno
3159
3064
 
3160
3065
    def report(self, to_file):
3161
 
        # TODO: This function gets passed a to_file, but then
3162
 
        # ignores it and calls note() instead. This is also
3163
 
        # inconsistent with PullResult(), which writes to stdout.
3164
 
        # -- JRV20110901, bug #838853
3165
 
        tag_conflicts = getattr(self, "tag_conflicts", None)
3166
 
        tag_updates = getattr(self, "tag_updates", None)
3167
 
        if not is_quiet():
3168
 
            if self.old_revid != self.new_revid:
3169
 
                note(gettext('Pushed up to revision %d.') % self.new_revno)
3170
 
            if tag_updates:
3171
 
                note(ngettext('%d tag updated.', '%d tags updated.', len(tag_updates)) % len(tag_updates))
3172
 
            if self.old_revid == self.new_revid and not tag_updates:
3173
 
                if not tag_conflicts:
3174
 
                    note(gettext('No new revisions or tags to push.'))
3175
 
                else:
3176
 
                    note(gettext('No new revisions to push.'))
 
3066
        """Write a human-readable description of the result."""
 
3067
        if self.old_revid == self.new_revid:
 
3068
            note('No new revisions to push.')
 
3069
        else:
 
3070
            note('Pushed up to revision %d.' % self.new_revno)
3177
3071
        self._show_tag_conficts(to_file)
3178
3072
 
3179
3073
 
3193
3087
        :param verbose: Requests more detailed display of what was checked,
3194
3088
            if any.
3195
3089
        """
3196
 
        note(gettext('checked branch {0} format {1}').format(
3197
 
                                self.branch.user_url, self.branch._format))
 
3090
        note('checked branch %s format %s', self.branch.user_url,
 
3091
            self.branch._format)
3198
3092
        for error in self.errors:
3199
 
            note(gettext('found error:%s'), error)
 
3093
            note('found error:%s', error)
3200
3094
 
3201
3095
 
3202
3096
class Converter5to6(object):
3241
3135
 
3242
3136
 
3243
3137
class Converter7to8(object):
3244
 
    """Perform an in-place upgrade of format 7 to format 8"""
 
3138
    """Perform an in-place upgrade of format 6 to format 7"""
3245
3139
 
3246
3140
    def convert(self, branch):
3247
3141
        format = BzrBranchFormat8()
3250
3144
        branch._transport.put_bytes('format', format.get_format_string())
3251
3145
 
3252
3146
 
 
3147
def _run_with_write_locked_target(target, callable, *args, **kwargs):
 
3148
    """Run ``callable(*args, **kwargs)``, write-locking target for the
 
3149
    duration.
 
3150
 
 
3151
    _run_with_write_locked_target will attempt to release the lock it acquires.
 
3152
 
 
3153
    If an exception is raised by callable, then that exception *will* be
 
3154
    propagated, even if the unlock attempt raises its own error.  Thus
 
3155
    _run_with_write_locked_target should be preferred to simply doing::
 
3156
 
 
3157
        target.lock_write()
 
3158
        try:
 
3159
            return callable(*args, **kwargs)
 
3160
        finally:
 
3161
            target.unlock()
 
3162
 
 
3163
    """
 
3164
    # This is very similar to bzrlib.decorators.needs_write_lock.  Perhaps they
 
3165
    # should share code?
 
3166
    target.lock_write()
 
3167
    try:
 
3168
        result = callable(*args, **kwargs)
 
3169
    except:
 
3170
        exc_info = sys.exc_info()
 
3171
        try:
 
3172
            target.unlock()
 
3173
        finally:
 
3174
            raise exc_info[0], exc_info[1], exc_info[2]
 
3175
    else:
 
3176
        target.unlock()
 
3177
        return result
 
3178
 
 
3179
 
3253
3180
class InterBranch(InterObject):
3254
3181
    """This class represents operations taking place between two branches.
3255
3182
 
3261
3188
    _optimisers = []
3262
3189
    """The available optimised InterBranch types."""
3263
3190
 
3264
 
    @classmethod
3265
 
    def _get_branch_formats_to_test(klass):
3266
 
        """Return an iterable of format tuples for testing.
3267
 
        
3268
 
        :return: An iterable of (from_format, to_format) to use when testing
3269
 
            this InterBranch class. Each InterBranch class should define this
3270
 
            method itself.
3271
 
        """
3272
 
        raise NotImplementedError(klass._get_branch_formats_to_test)
 
3191
    @staticmethod
 
3192
    def _get_branch_formats_to_test():
 
3193
        """Return a tuple with the Branch formats to use when testing."""
 
3194
        raise NotImplementedError(InterBranch._get_branch_formats_to_test)
3273
3195
 
3274
 
    @needs_write_lock
3275
3196
    def pull(self, overwrite=False, stop_revision=None,
3276
3197
             possible_transports=None, local=False):
3277
3198
        """Mirror source into target branch.
3282
3203
        """
3283
3204
        raise NotImplementedError(self.pull)
3284
3205
 
3285
 
    @needs_write_lock
3286
 
    def push(self, overwrite=False, stop_revision=None, lossy=False,
 
3206
    def update_revisions(self, stop_revision=None, overwrite=False,
 
3207
                         graph=None):
 
3208
        """Pull in new perfect-fit revisions.
 
3209
 
 
3210
        :param stop_revision: Updated until the given revision
 
3211
        :param overwrite: Always set the branch pointer, rather than checking
 
3212
            to see if it is a proper descendant.
 
3213
        :param graph: A Graph object that can be used to query history
 
3214
            information. This can be None.
 
3215
        :return: None
 
3216
        """
 
3217
        raise NotImplementedError(self.update_revisions)
 
3218
 
 
3219
    def push(self, overwrite=False, stop_revision=None,
3287
3220
             _override_hook_source_branch=None):
3288
3221
        """Mirror the source branch into the target branch.
3289
3222
 
3291
3224
        """
3292
3225
        raise NotImplementedError(self.push)
3293
3226
 
3294
 
    @needs_write_lock
3295
 
    def copy_content_into(self, revision_id=None):
3296
 
        """Copy the content of source into target
3297
 
 
3298
 
        revision_id: if not None, the revision history in the new branch will
3299
 
                     be truncated to end with revision_id.
3300
 
        """
3301
 
        raise NotImplementedError(self.copy_content_into)
3302
 
 
3303
 
    @needs_write_lock
3304
 
    def fetch(self, stop_revision=None, limit=None):
3305
 
        """Fetch revisions.
3306
 
 
3307
 
        :param stop_revision: Last revision to fetch
3308
 
        :param limit: Optional rough limit of revisions to fetch
3309
 
        """
3310
 
        raise NotImplementedError(self.fetch)
3311
 
 
3312
3227
 
3313
3228
class GenericInterBranch(InterBranch):
3314
 
    """InterBranch implementation that uses public Branch functions."""
3315
 
 
3316
 
    @classmethod
3317
 
    def is_compatible(klass, source, target):
3318
 
        # GenericBranch uses the public API, so always compatible
3319
 
        return True
3320
 
 
3321
 
    @classmethod
3322
 
    def _get_branch_formats_to_test(klass):
3323
 
        return [(format_registry.get_default(), format_registry.get_default())]
3324
 
 
3325
 
    @classmethod
3326
 
    def unwrap_format(klass, format):
3327
 
        if isinstance(format, remote.RemoteBranchFormat):
3328
 
            format._ensure_real()
3329
 
            return format._custom_format
3330
 
        return format
3331
 
 
3332
 
    @needs_write_lock
3333
 
    def copy_content_into(self, revision_id=None):
3334
 
        """Copy the content of source into target
3335
 
 
3336
 
        revision_id: if not None, the revision history in the new branch will
3337
 
                     be truncated to end with revision_id.
3338
 
        """
3339
 
        self.source.update_references(self.target)
3340
 
        self.source._synchronize_history(self.target, revision_id)
3341
 
        try:
3342
 
            parent = self.source.get_parent()
3343
 
        except errors.InaccessibleParent, e:
3344
 
            mutter('parent was not accessible to copy: %s', e)
3345
 
        else:
3346
 
            if parent:
3347
 
                self.target.set_parent(parent)
3348
 
        if self.source._push_should_merge_tags():
3349
 
            self.source.tags.merge_to(self.target.tags)
3350
 
 
3351
 
    @needs_write_lock
3352
 
    def fetch(self, stop_revision=None, limit=None):
3353
 
        if self.target.base == self.source.base:
3354
 
            return (0, [])
 
3229
    """InterBranch implementation that uses public Branch functions.
 
3230
    """
 
3231
 
 
3232
    @staticmethod
 
3233
    def _get_branch_formats_to_test():
 
3234
        return BranchFormat._default_format, BranchFormat._default_format
 
3235
 
 
3236
    def update_revisions(self, stop_revision=None, overwrite=False,
 
3237
        graph=None):
 
3238
        """See InterBranch.update_revisions()."""
3355
3239
        self.source.lock_read()
3356
3240
        try:
3357
 
            fetch_spec_factory = fetch.FetchSpecFactory()
3358
 
            fetch_spec_factory.source_branch = self.source
3359
 
            fetch_spec_factory.source_branch_stop_revision_id = stop_revision
3360
 
            fetch_spec_factory.source_repo = self.source.repository
3361
 
            fetch_spec_factory.target_repo = self.target.repository
3362
 
            fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
3363
 
            fetch_spec_factory.limit = limit
3364
 
            fetch_spec = fetch_spec_factory.make_fetch_spec()
3365
 
            return self.target.repository.fetch(self.source.repository,
3366
 
                fetch_spec=fetch_spec)
 
3241
            other_revno, other_last_revision = self.source.last_revision_info()
 
3242
            stop_revno = None # unknown
 
3243
            if stop_revision is None:
 
3244
                stop_revision = other_last_revision
 
3245
                if _mod_revision.is_null(stop_revision):
 
3246
                    # if there are no commits, we're done.
 
3247
                    return
 
3248
                stop_revno = other_revno
 
3249
 
 
3250
            # what's the current last revision, before we fetch [and change it
 
3251
            # possibly]
 
3252
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
3253
            # we fetch here so that we don't process data twice in the common
 
3254
            # case of having something to pull, and so that the check for
 
3255
            # already merged can operate on the just fetched graph, which will
 
3256
            # be cached in memory.
 
3257
            self.target.fetch(self.source, stop_revision)
 
3258
            # Check to see if one is an ancestor of the other
 
3259
            if not overwrite:
 
3260
                if graph is None:
 
3261
                    graph = self.target.repository.get_graph()
 
3262
                if self.target._check_if_descendant_or_diverged(
 
3263
                        stop_revision, last_rev, graph, self.source):
 
3264
                    # stop_revision is a descendant of last_rev, but we aren't
 
3265
                    # overwriting, so we're done.
 
3266
                    return
 
3267
            if stop_revno is None:
 
3268
                if graph is None:
 
3269
                    graph = self.target.repository.get_graph()
 
3270
                this_revno, this_last_revision = \
 
3271
                        self.target.last_revision_info()
 
3272
                stop_revno = graph.find_distance_to_null(stop_revision,
 
3273
                                [(other_last_revision, other_revno),
 
3274
                                 (this_last_revision, this_revno)])
 
3275
            self.target.set_last_revision_info(stop_revno, stop_revision)
3367
3276
        finally:
3368
3277
            self.source.unlock()
3369
3278
 
3370
 
    @needs_write_lock
3371
 
    def _update_revisions(self, stop_revision=None, overwrite=False,
3372
 
            graph=None):
3373
 
        other_revno, other_last_revision = self.source.last_revision_info()
3374
 
        stop_revno = None # unknown
3375
 
        if stop_revision is None:
3376
 
            stop_revision = other_last_revision
3377
 
            if _mod_revision.is_null(stop_revision):
3378
 
                # if there are no commits, we're done.
3379
 
                return
3380
 
            stop_revno = other_revno
3381
 
 
3382
 
        # what's the current last revision, before we fetch [and change it
3383
 
        # possibly]
3384
 
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
3385
 
        # we fetch here so that we don't process data twice in the common
3386
 
        # case of having something to pull, and so that the check for
3387
 
        # already merged can operate on the just fetched graph, which will
3388
 
        # be cached in memory.
3389
 
        self.fetch(stop_revision=stop_revision)
3390
 
        # Check to see if one is an ancestor of the other
3391
 
        if not overwrite:
3392
 
            if graph is None:
3393
 
                graph = self.target.repository.get_graph()
3394
 
            if self.target._check_if_descendant_or_diverged(
3395
 
                    stop_revision, last_rev, graph, self.source):
3396
 
                # stop_revision is a descendant of last_rev, but we aren't
3397
 
                # overwriting, so we're done.
3398
 
                return
3399
 
        if stop_revno is None:
3400
 
            if graph is None:
3401
 
                graph = self.target.repository.get_graph()
3402
 
            this_revno, this_last_revision = \
3403
 
                    self.target.last_revision_info()
3404
 
            stop_revno = graph.find_distance_to_null(stop_revision,
3405
 
                            [(other_last_revision, other_revno),
3406
 
                             (this_last_revision, this_revno)])
3407
 
        self.target.set_last_revision_info(stop_revno, stop_revision)
3408
 
 
3409
 
    @needs_write_lock
3410
3279
    def pull(self, overwrite=False, stop_revision=None,
3411
 
             possible_transports=None, run_hooks=True,
3412
 
             _override_hook_target=None, local=False):
3413
 
        """Pull from source into self, updating my master if any.
3414
 
 
3415
 
        :param run_hooks: Private parameter - if false, this branch
3416
 
            is being called because it's the master of the primary branch,
3417
 
            so it should not run its hooks.
3418
 
        """
3419
 
        bound_location = self.target.get_bound_location()
3420
 
        if local and not bound_location:
3421
 
            raise errors.LocalRequiresBoundBranch()
3422
 
        master_branch = None
3423
 
        source_is_master = False
3424
 
        if bound_location:
3425
 
            # bound_location comes from a config file, some care has to be
3426
 
            # taken to relate it to source.user_url
3427
 
            normalized = urlutils.normalize_url(bound_location)
3428
 
            try:
3429
 
                relpath = self.source.user_transport.relpath(normalized)
3430
 
                source_is_master = (relpath == '')
3431
 
            except (errors.PathNotChild, errors.InvalidURL):
3432
 
                source_is_master = False
3433
 
        if not local and bound_location and not source_is_master:
3434
 
            # not pulling from master, so we need to update master.
3435
 
            master_branch = self.target.get_master_branch(possible_transports)
3436
 
            master_branch.lock_write()
3437
 
        try:
3438
 
            if master_branch:
3439
 
                # pull from source into master.
3440
 
                master_branch.pull(self.source, overwrite, stop_revision,
3441
 
                    run_hooks=False)
3442
 
            return self._pull(overwrite,
3443
 
                stop_revision, _hook_master=master_branch,
3444
 
                run_hooks=run_hooks,
3445
 
                _override_hook_target=_override_hook_target,
3446
 
                merge_tags_to_master=not source_is_master)
3447
 
        finally:
3448
 
            if master_branch:
3449
 
                master_branch.unlock()
3450
 
 
3451
 
    def push(self, overwrite=False, stop_revision=None, lossy=False,
3452
 
             _override_hook_source_branch=None):
3453
 
        """See InterBranch.push.
3454
 
 
3455
 
        This is the basic concrete implementation of push()
3456
 
 
3457
 
        :param _override_hook_source_branch: If specified, run the hooks
3458
 
            passing this Branch as the source, rather than self.  This is for
3459
 
            use of RemoteBranch, where push is delegated to the underlying
3460
 
            vfs-based Branch.
3461
 
        """
3462
 
        if lossy:
3463
 
            raise errors.LossyPushToSameVCS(self.source, self.target)
3464
 
        # TODO: Public option to disable running hooks - should be trivial but
3465
 
        # needs tests.
3466
 
 
3467
 
        op = cleanup.OperationWithCleanups(self._push_with_bound_branches)
3468
 
        op.add_cleanup(self.source.lock_read().unlock)
3469
 
        op.add_cleanup(self.target.lock_write().unlock)
3470
 
        return op.run(overwrite, stop_revision,
3471
 
            _override_hook_source_branch=_override_hook_source_branch)
3472
 
 
3473
 
    def _basic_push(self, overwrite, stop_revision):
3474
 
        """Basic implementation of push without bound branches or hooks.
3475
 
 
3476
 
        Must be called with source read locked and target write locked.
3477
 
        """
3478
 
        result = BranchPushResult()
3479
 
        result.source_branch = self.source
3480
 
        result.target_branch = self.target
3481
 
        result.old_revno, result.old_revid = self.target.last_revision_info()
3482
 
        self.source.update_references(self.target)
3483
 
        if result.old_revid != stop_revision:
3484
 
            # We assume that during 'push' this repository is closer than
3485
 
            # the target.
3486
 
            graph = self.source.repository.get_graph(self.target.repository)
3487
 
            self._update_revisions(stop_revision, overwrite=overwrite,
3488
 
                    graph=graph)
3489
 
        if self.source._push_should_merge_tags():
3490
 
            result.tag_updates, result.tag_conflicts = (
3491
 
                self.source.tags.merge_to(self.target.tags, overwrite))
3492
 
        result.new_revno, result.new_revid = self.target.last_revision_info()
3493
 
        return result
3494
 
 
3495
 
    def _push_with_bound_branches(self, operation, overwrite, stop_revision,
3496
 
            _override_hook_source_branch=None):
3497
 
        """Push from source into target, and into target's master if any.
3498
 
        """
3499
 
        def _run_hooks():
3500
 
            if _override_hook_source_branch:
3501
 
                result.source_branch = _override_hook_source_branch
3502
 
            for hook in Branch.hooks['post_push']:
3503
 
                hook(result)
3504
 
 
3505
 
        bound_location = self.target.get_bound_location()
3506
 
        if bound_location and self.target.base != bound_location:
3507
 
            # there is a master branch.
3508
 
            #
3509
 
            # XXX: Why the second check?  Is it even supported for a branch to
3510
 
            # be bound to itself? -- mbp 20070507
3511
 
            master_branch = self.target.get_master_branch()
3512
 
            master_branch.lock_write()
3513
 
            operation.add_cleanup(master_branch.unlock)
3514
 
            # push into the master from the source branch.
3515
 
            master_inter = InterBranch.get(self.source, master_branch)
3516
 
            master_inter._basic_push(overwrite, stop_revision)
3517
 
            # and push into the target branch from the source. Note that
3518
 
            # we push from the source branch again, because it's considered
3519
 
            # the highest bandwidth repository.
3520
 
            result = self._basic_push(overwrite, stop_revision)
3521
 
            result.master_branch = master_branch
3522
 
            result.local_branch = self.target
3523
 
        else:
3524
 
            master_branch = None
3525
 
            # no master branch
3526
 
            result = self._basic_push(overwrite, stop_revision)
3527
 
            # TODO: Why set master_branch and local_branch if there's no
3528
 
            # binding?  Maybe cleaner to just leave them unset? -- mbp
3529
 
            # 20070504
3530
 
            result.master_branch = self.target
3531
 
            result.local_branch = None
3532
 
        _run_hooks()
3533
 
        return result
3534
 
 
3535
 
    def _pull(self, overwrite=False, stop_revision=None,
3536
3280
             possible_transports=None, _hook_master=None, run_hooks=True,
3537
 
             _override_hook_target=None, local=False,
3538
 
             merge_tags_to_master=True):
 
3281
             _override_hook_target=None, local=False):
3539
3282
        """See Branch.pull.
3540
3283
 
3541
 
        This function is the core worker, used by GenericInterBranch.pull to
3542
 
        avoid duplication when pulling source->master and source->local.
3543
 
 
3544
3284
        :param _hook_master: Private parameter - set the branch to
3545
3285
            be supplied as the master to pull hooks.
3546
3286
        :param run_hooks: Private parameter - if false, this branch
3547
3287
            is being called because it's the master of the primary branch,
3548
3288
            so it should not run its hooks.
3549
 
            is being called because it's the master of the primary branch,
3550
 
            so it should not run its hooks.
3551
3289
        :param _override_hook_target: Private parameter - set the branch to be
3552
3290
            supplied as the target_branch to pull hooks.
3553
3291
        :param local: Only update the local branch, and not the bound branch.
3572
3310
            # -- JRV20090506
3573
3311
            result.old_revno, result.old_revid = \
3574
3312
                self.target.last_revision_info()
3575
 
            self._update_revisions(stop_revision, overwrite=overwrite,
3576
 
                graph=graph)
 
3313
            self.target.update_revisions(self.source, stop_revision,
 
3314
                overwrite=overwrite, graph=graph)
3577
3315
            # TODO: The old revid should be specified when merging tags, 
3578
3316
            # so a tags implementation that versions tags can only 
3579
3317
            # pull in the most recent changes. -- JRV20090506
3580
 
            result.tag_updates, result.tag_conflicts = (
3581
 
                self.source.tags.merge_to(self.target.tags, overwrite,
3582
 
                    ignore_master=not merge_tags_to_master))
 
3318
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
3319
                overwrite)
3583
3320
            result.new_revno, result.new_revid = self.target.last_revision_info()
3584
3321
            if _hook_master:
3585
3322
                result.master_branch = _hook_master
3594
3331
            self.source.unlock()
3595
3332
        return result
3596
3333
 
 
3334
    def push(self, overwrite=False, stop_revision=None,
 
3335
             _override_hook_source_branch=None):
 
3336
        """See InterBranch.push.
 
3337
 
 
3338
        This is the basic concrete implementation of push()
 
3339
 
 
3340
        :param _override_hook_source_branch: If specified, run
 
3341
        the hooks passing this Branch as the source, rather than self.
 
3342
        This is for use of RemoteBranch, where push is delegated to the
 
3343
        underlying vfs-based Branch.
 
3344
        """
 
3345
        # TODO: Public option to disable running hooks - should be trivial but
 
3346
        # needs tests.
 
3347
        self.source.lock_read()
 
3348
        try:
 
3349
            return _run_with_write_locked_target(
 
3350
                self.target, self._push_with_bound_branches, overwrite,
 
3351
                stop_revision,
 
3352
                _override_hook_source_branch=_override_hook_source_branch)
 
3353
        finally:
 
3354
            self.source.unlock()
 
3355
 
 
3356
    def _push_with_bound_branches(self, overwrite, stop_revision,
 
3357
            _override_hook_source_branch=None):
 
3358
        """Push from source into target, and into target's master if any.
 
3359
        """
 
3360
        def _run_hooks():
 
3361
            if _override_hook_source_branch:
 
3362
                result.source_branch = _override_hook_source_branch
 
3363
            for hook in Branch.hooks['post_push']:
 
3364
                hook(result)
 
3365
 
 
3366
        bound_location = self.target.get_bound_location()
 
3367
        if bound_location and self.target.base != bound_location:
 
3368
            # there is a master branch.
 
3369
            #
 
3370
            # XXX: Why the second check?  Is it even supported for a branch to
 
3371
            # be bound to itself? -- mbp 20070507
 
3372
            master_branch = self.target.get_master_branch()
 
3373
            master_branch.lock_write()
 
3374
            try:
 
3375
                # push into the master from the source branch.
 
3376
                self.source._basic_push(master_branch, overwrite, stop_revision)
 
3377
                # and push into the target branch from the source. Note that we
 
3378
                # push from the source branch again, because its considered the
 
3379
                # highest bandwidth repository.
 
3380
                result = self.source._basic_push(self.target, overwrite,
 
3381
                    stop_revision)
 
3382
                result.master_branch = master_branch
 
3383
                result.local_branch = self.target
 
3384
                _run_hooks()
 
3385
                return result
 
3386
            finally:
 
3387
                master_branch.unlock()
 
3388
        else:
 
3389
            # no master branch
 
3390
            result = self.source._basic_push(self.target, overwrite,
 
3391
                stop_revision)
 
3392
            # TODO: Why set master_branch and local_branch if there's no
 
3393
            # binding?  Maybe cleaner to just leave them unset? -- mbp
 
3394
            # 20070504
 
3395
            result.master_branch = self.target
 
3396
            result.local_branch = None
 
3397
            _run_hooks()
 
3398
            return result
 
3399
 
 
3400
    @classmethod
 
3401
    def is_compatible(self, source, target):
 
3402
        # GenericBranch uses the public API, so always compatible
 
3403
        return True
 
3404
 
 
3405
 
 
3406
class InterToBranch5(GenericInterBranch):
 
3407
 
 
3408
    @staticmethod
 
3409
    def _get_branch_formats_to_test():
 
3410
        return BranchFormat._default_format, BzrBranchFormat5()
 
3411
 
 
3412
    def pull(self, overwrite=False, stop_revision=None,
 
3413
             possible_transports=None, run_hooks=True,
 
3414
             _override_hook_target=None, local=False):
 
3415
        """Pull from source into self, updating my master if any.
 
3416
 
 
3417
        :param run_hooks: Private parameter - if false, this branch
 
3418
            is being called because it's the master of the primary branch,
 
3419
            so it should not run its hooks.
 
3420
        """
 
3421
        bound_location = self.target.get_bound_location()
 
3422
        if local and not bound_location:
 
3423
            raise errors.LocalRequiresBoundBranch()
 
3424
        master_branch = None
 
3425
        if not local and bound_location and self.source.user_url != bound_location:
 
3426
            # not pulling from master, so we need to update master.
 
3427
            master_branch = self.target.get_master_branch(possible_transports)
 
3428
            master_branch.lock_write()
 
3429
        try:
 
3430
            if master_branch:
 
3431
                # pull from source into master.
 
3432
                master_branch.pull(self.source, overwrite, stop_revision,
 
3433
                    run_hooks=False)
 
3434
            return super(InterToBranch5, self).pull(overwrite,
 
3435
                stop_revision, _hook_master=master_branch,
 
3436
                run_hooks=run_hooks,
 
3437
                _override_hook_target=_override_hook_target)
 
3438
        finally:
 
3439
            if master_branch:
 
3440
                master_branch.unlock()
 
3441
 
3597
3442
 
3598
3443
InterBranch.register_optimiser(GenericInterBranch)
 
3444
InterBranch.register_optimiser(InterToBranch5)