~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Jelmer Vernooij
  • Date: 2011-12-16 19:18:39 UTC
  • mto: This revision was merged to the branch mainline in revision 6391.
  • Revision ID: jelmer@samba.org-20111216191839-eg681lxqibi1qxu1
Fix remaining tests.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005-2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
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
import bzrlib.bzrdir
17
18
 
18
19
from cStringIO import StringIO
19
 
import sys
20
20
 
21
21
from bzrlib.lazy_import import lazy_import
22
22
lazy_import(globals(), """
23
 
from itertools import chain
 
23
import itertools
24
24
from bzrlib import (
25
 
        bzrdir,
26
 
        cache_utf8,
27
 
        config as _mod_config,
28
 
        controldir,
29
 
        debug,
30
 
        errors,
31
 
        lockdir,
32
 
        lockable_files,
33
 
        remote,
34
 
        repository,
35
 
        revision as _mod_revision,
36
 
        rio,
37
 
        symbol_versioning,
38
 
        transport,
39
 
        tsort,
40
 
        ui,
41
 
        urlutils,
42
 
        )
43
 
from bzrlib.config import BranchConfig, TransportConfig
44
 
from bzrlib.repofmt.pack_repo import RepositoryFormatKnitPack5RichRoot
45
 
from bzrlib.tag import (
46
 
    BasicTags,
47
 
    DisabledTags,
 
25
    bzrdir,
 
26
    controldir,
 
27
    cache_utf8,
 
28
    cleanup,
 
29
    config as _mod_config,
 
30
    debug,
 
31
    errors,
 
32
    fetch,
 
33
    graph as _mod_graph,
 
34
    lockdir,
 
35
    lockable_files,
 
36
    remote,
 
37
    repository,
 
38
    revision as _mod_revision,
 
39
    rio,
 
40
    tag as _mod_tag,
 
41
    transport,
 
42
    ui,
 
43
    urlutils,
 
44
    vf_search,
48
45
    )
 
46
from bzrlib.i18n import gettext, ngettext
49
47
""")
50
48
 
51
 
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
52
 
from bzrlib.hooks import HookPoint, Hooks
 
49
from bzrlib import (
 
50
    controldir,
 
51
    )
 
52
from bzrlib.decorators import (
 
53
    needs_read_lock,
 
54
    needs_write_lock,
 
55
    only_raises,
 
56
    )
 
57
from bzrlib.hooks import Hooks
53
58
from bzrlib.inter import InterObject
54
59
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
55
60
from bzrlib import registry
60
65
from bzrlib.trace import mutter, mutter_callsite, note, is_quiet
61
66
 
62
67
 
63
 
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
64
 
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
65
 
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
66
 
 
67
 
 
68
68
class Branch(controldir.ControlComponent):
69
69
    """Branch holding a history of revisions.
70
70
 
71
71
    :ivar base:
72
72
        Base directory/url of the branch; using control_url and
73
73
        control_transport is more standardized.
74
 
 
75
 
    hooks: An instance of BranchHooks.
 
74
    :ivar hooks: An instance of BranchHooks.
 
75
    :ivar _master_branch_cache: cached result of get_master_branch, see
 
76
        _clear_cached_state.
76
77
    """
77
78
    # this is really an instance variable - FIXME move it there
78
79
    # - RBC 20060112
86
87
    def user_transport(self):
87
88
        return self.bzrdir.user_transport
88
89
 
89
 
    def __init__(self, *ignored, **ignored_too):
 
90
    def __init__(self, possible_transports=None):
90
91
        self.tags = self._format.make_tags(self)
91
92
        self._revision_history_cache = None
92
93
        self._revision_id_to_revno_cache = None
93
94
        self._partial_revision_id_to_revno_cache = {}
94
95
        self._partial_revision_history_cache = []
 
96
        self._tags_bytes = None
95
97
        self._last_revision_info_cache = None
 
98
        self._master_branch_cache = None
96
99
        self._merge_sorted_revisions_cache = None
97
 
        self._open_hook()
 
100
        self._open_hook(possible_transports)
98
101
        hooks = Branch.hooks['open']
99
102
        for hook in hooks:
100
103
            hook(self)
101
104
 
102
 
    def _open_hook(self):
 
105
    def _open_hook(self, possible_transports):
103
106
        """Called by init to allow simpler extension of the base class."""
104
107
 
105
 
    def _activate_fallback_location(self, url):
 
108
    def _activate_fallback_location(self, url, possible_transports):
106
109
        """Activate the branch/repository from url as a fallback repository."""
107
 
        repo = self._get_fallback_repository(url)
 
110
        for existing_fallback_repo in self.repository._fallback_repositories:
 
111
            if existing_fallback_repo.user_url == url:
 
112
                # This fallback is already configured.  This probably only
 
113
                # happens because ControlDir.sprout is a horrible mess.  To avoid
 
114
                # confusing _unstack we don't add this a second time.
 
115
                mutter('duplicate activation of fallback %r on %r', url, self)
 
116
                return
 
117
        repo = self._get_fallback_repository(url, possible_transports)
108
118
        if repo.has_same_location(self.repository):
109
119
            raise errors.UnstackableLocationError(self.user_url, url)
110
120
        self.repository.add_fallback_repository(repo)
164
174
        For instance, if the branch is at URL/.bzr/branch,
165
175
        Branch.open(URL) -> a Branch instance.
166
176
        """
167
 
        control = bzrdir.BzrDir.open(base, _unsupported,
 
177
        control = controldir.ControlDir.open(base, _unsupported,
168
178
                                     possible_transports=possible_transports)
169
 
        return control.open_branch(unsupported=_unsupported)
 
179
        return control.open_branch(unsupported=_unsupported,
 
180
            possible_transports=possible_transports)
170
181
 
171
182
    @staticmethod
172
 
    def open_from_transport(transport, name=None, _unsupported=False):
 
183
    def open_from_transport(transport, name=None, _unsupported=False,
 
184
            possible_transports=None):
173
185
        """Open the branch rooted at transport"""
174
 
        control = bzrdir.BzrDir.open_from_transport(transport, _unsupported)
175
 
        return control.open_branch(name=name, unsupported=_unsupported)
 
186
        control = controldir.ControlDir.open_from_transport(transport, _unsupported)
 
187
        return control.open_branch(name=name, unsupported=_unsupported,
 
188
            possible_transports=possible_transports)
176
189
 
177
190
    @staticmethod
178
191
    def open_containing(url, possible_transports=None):
186
199
        format, UnknownFormatError or UnsupportedFormatError are raised.
187
200
        If there is one, it is returned, along with the unused portion of url.
188
201
        """
189
 
        control, relpath = bzrdir.BzrDir.open_containing(url,
 
202
        control, relpath = controldir.ControlDir.open_containing(url,
190
203
                                                         possible_transports)
191
 
        return control.open_branch(), relpath
 
204
        branch = control.open_branch(possible_transports=possible_transports)
 
205
        return (branch, relpath)
192
206
 
193
207
    def _push_should_merge_tags(self):
194
208
        """Should _basic_push merge this branch's tags into the target?
206
220
 
207
221
        :return: A bzrlib.config.BranchConfig.
208
222
        """
209
 
        return BranchConfig(self)
 
223
        return _mod_config.BranchConfig(self)
 
224
 
 
225
    def get_config_stack(self):
 
226
        """Get a bzrlib.config.BranchStack for this Branch.
 
227
 
 
228
        This can then be used to get and set configuration options for the
 
229
        branch.
 
230
 
 
231
        :return: A bzrlib.config.BranchStack.
 
232
        """
 
233
        return _mod_config.BranchStack(self)
210
234
 
211
235
    def _get_config(self):
212
236
        """Get the concrete config for just the config in this branch.
220
244
        """
221
245
        raise NotImplementedError(self._get_config)
222
246
 
223
 
    def _get_fallback_repository(self, url):
 
247
    def _get_fallback_repository(self, url, possible_transports):
224
248
        """Get the repository we fallback to at url."""
225
249
        url = urlutils.join(self.base, url)
226
 
        a_branch = Branch.open(url,
227
 
            possible_transports=[self.bzrdir.root_transport])
 
250
        a_branch = Branch.open(url, possible_transports=possible_transports)
228
251
        return a_branch.repository
229
252
 
 
253
    @needs_read_lock
230
254
    def _get_tags_bytes(self):
231
255
        """Get the bytes of a serialised tags dict.
232
256
 
239
263
        :return: The bytes of the tags file.
240
264
        :seealso: Branch._set_tags_bytes.
241
265
        """
242
 
        return self._transport.get_bytes('tags')
 
266
        if self._tags_bytes is None:
 
267
            self._tags_bytes = self._transport.get_bytes('tags')
 
268
        return self._tags_bytes
243
269
 
244
270
    def _get_nick(self, local=False, possible_transports=None):
245
271
        config = self.get_config()
436
462
            after. If None, the rest of history is included.
437
463
        :param stop_rule: if stop_revision_id is not None, the precise rule
438
464
            to use for termination:
 
465
 
439
466
            * 'exclude' - leave the stop revision out of the result (default)
440
467
            * 'include' - the stop revision is the last item in the result
441
468
            * 'with-merges' - include the stop revision and all of its
443
470
            * 'with-merges-without-common-ancestry' - filter out revisions 
444
471
              that are in both ancestries
445
472
        :param direction: either 'reverse' or 'forward':
 
473
 
446
474
            * reverse means return the start_revision_id first, i.e.
447
475
              start at the most recent revision and go backwards in history
448
476
            * forward returns tuples in the opposite order to reverse.
492
520
        rev_iter = iter(merge_sorted_revisions)
493
521
        if start_revision_id is not None:
494
522
            for node in rev_iter:
495
 
                rev_id = node.key[-1]
 
523
                rev_id = node.key
496
524
                if rev_id != start_revision_id:
497
525
                    continue
498
526
                else:
499
527
                    # The decision to include the start or not
500
528
                    # depends on the stop_rule if a stop is provided
501
529
                    # so pop this node back into the iterator
502
 
                    rev_iter = chain(iter([node]), rev_iter)
 
530
                    rev_iter = itertools.chain(iter([node]), rev_iter)
503
531
                    break
504
532
        if stop_revision_id is None:
505
533
            # Yield everything
506
534
            for node in rev_iter:
507
 
                rev_id = node.key[-1]
 
535
                rev_id = node.key
508
536
                yield (rev_id, node.merge_depth, node.revno,
509
537
                       node.end_of_merge)
510
538
        elif stop_rule == 'exclude':
511
539
            for node in rev_iter:
512
 
                rev_id = node.key[-1]
 
540
                rev_id = node.key
513
541
                if rev_id == stop_revision_id:
514
542
                    return
515
543
                yield (rev_id, node.merge_depth, node.revno,
516
544
                       node.end_of_merge)
517
545
        elif stop_rule == 'include':
518
546
            for node in rev_iter:
519
 
                rev_id = node.key[-1]
 
547
                rev_id = node.key
520
548
                yield (rev_id, node.merge_depth, node.revno,
521
549
                       node.end_of_merge)
522
550
                if rev_id == stop_revision_id:
528
556
            ancestors = graph.find_unique_ancestors(start_revision_id,
529
557
                                                    [stop_revision_id])
530
558
            for node in rev_iter:
531
 
                rev_id = node.key[-1]
 
559
                rev_id = node.key
532
560
                if rev_id not in ancestors:
533
561
                    continue
534
562
                yield (rev_id, node.merge_depth, node.revno,
544
572
            reached_stop_revision_id = False
545
573
            revision_id_whitelist = []
546
574
            for node in rev_iter:
547
 
                rev_id = node.key[-1]
 
575
                rev_id = node.key
548
576
                if rev_id == left_parent:
549
577
                    # reached the left parent after the stop_revision
550
578
                    return
630
658
        """
631
659
        raise errors.UpgradeRequired(self.user_url)
632
660
 
 
661
    def get_append_revisions_only(self):
 
662
        """Whether it is only possible to append revisions to the history.
 
663
        """
 
664
        if not self._format.supports_set_append_revisions_only():
 
665
            return False
 
666
        return self.get_config_stack().get('append_revisions_only')
 
667
 
633
668
    def set_append_revisions_only(self, enabled):
634
669
        if not self._format.supports_set_append_revisions_only():
635
670
            raise errors.UpgradeRequired(self.user_url)
636
 
        if enabled:
637
 
            value = 'True'
638
 
        else:
639
 
            value = 'False'
640
 
        self.get_config().set_user_option('append_revisions_only', value,
641
 
            warn_masked=True)
 
671
        self.get_config_stack().set('append_revisions_only', enabled)
642
672
 
643
673
    def set_reference_info(self, file_id, tree_path, branch_location):
644
674
        """Set the branch location to use for a tree reference."""
649
679
        raise errors.UnsupportedOperation(self.get_reference_info, self)
650
680
 
651
681
    @needs_write_lock
652
 
    def fetch(self, from_branch, last_revision=None, pb=None):
 
682
    def fetch(self, from_branch, last_revision=None, limit=None):
653
683
        """Copy revisions from from_branch into this branch.
654
684
 
655
685
        :param from_branch: Where to copy from.
656
686
        :param last_revision: What revision to stop at (None for at the end
657
687
                              of the branch.
658
 
        :param pb: An optional progress bar to use.
 
688
        :param limit: Optional rough limit of revisions to fetch
659
689
        :return: None
660
690
        """
661
 
        if self.base == from_branch.base:
662
 
            return (0, [])
663
 
        if pb is not None:
664
 
            symbol_versioning.warn(
665
 
                symbol_versioning.deprecated_in((1, 14, 0))
666
 
                % "pb parameter to fetch()")
667
 
        from_branch.lock_read()
668
 
        try:
669
 
            if last_revision is None:
670
 
                last_revision = from_branch.last_revision()
671
 
                last_revision = _mod_revision.ensure_null(last_revision)
672
 
            return self.repository.fetch(from_branch.repository,
673
 
                                         revision_id=last_revision,
674
 
                                         pb=pb)
675
 
        finally:
676
 
            from_branch.unlock()
 
691
        return InterBranch.get(from_branch, self).fetch(last_revision, limit=limit)
677
692
 
678
693
    def get_bound_location(self):
679
694
        """Return the URL of the branch we are bound to.
688
703
        """
689
704
        raise errors.UpgradeRequired(self.user_url)
690
705
 
691
 
    def get_commit_builder(self, parents, config=None, timestamp=None,
 
706
    def get_commit_builder(self, parents, config_stack=None, timestamp=None,
692
707
                           timezone=None, committer=None, revprops=None,
693
 
                           revision_id=None):
 
708
                           revision_id=None, lossy=False):
694
709
        """Obtain a CommitBuilder for this branch.
695
710
 
696
711
        :param parents: Revision ids of the parents of the new revision.
700
715
        :param committer: Optional committer to set for commit.
701
716
        :param revprops: Optional dictionary of revision properties.
702
717
        :param revision_id: Optional revision id.
 
718
        :param lossy: Whether to discard data that can not be natively
 
719
            represented, when pushing to a foreign VCS 
703
720
        """
704
721
 
705
 
        if config is None:
706
 
            config = self.get_config()
 
722
        if config_stack is None:
 
723
            config_stack = self.get_config_stack()
707
724
 
708
 
        return self.repository.get_commit_builder(self, parents, config,
709
 
            timestamp, timezone, committer, revprops, revision_id)
 
725
        return self.repository.get_commit_builder(self, parents, config_stack,
 
726
            timestamp, timezone, committer, revprops, revision_id,
 
727
            lossy)
710
728
 
711
729
    def get_master_branch(self, possible_transports=None):
712
730
        """Return the branch we are bound to.
715
733
        """
716
734
        return None
717
735
 
 
736
    @deprecated_method(deprecated_in((2, 5, 0)))
718
737
    def get_revision_delta(self, revno):
719
738
        """Return the delta for one revision.
720
739
 
721
740
        The delta is relative to its mainline predecessor, or the
722
741
        empty tree for revision 1.
723
742
        """
724
 
        rh = self.revision_history()
725
 
        if not (1 <= revno <= len(rh)):
 
743
        try:
 
744
            revid = self.get_rev_id(revno)
 
745
        except errors.NoSuchRevision:
726
746
            raise errors.InvalidRevisionNumber(revno)
727
 
        return self.repository.get_revision_delta(rh[revno-1])
 
747
        return self.repository.get_revision_delta(revid)
728
748
 
729
749
    def get_stacked_on_url(self):
730
750
        """Get the URL this branch is stacked against.
739
759
        """Print `file` to stdout."""
740
760
        raise NotImplementedError(self.print_file)
741
761
 
 
762
    @deprecated_method(deprecated_in((2, 4, 0)))
742
763
    def set_revision_history(self, rev_history):
743
 
        raise NotImplementedError(self.set_revision_history)
 
764
        """See Branch.set_revision_history."""
 
765
        self._set_revision_history(rev_history)
 
766
 
 
767
    @needs_write_lock
 
768
    def _set_revision_history(self, rev_history):
 
769
        if len(rev_history) == 0:
 
770
            revid = _mod_revision.NULL_REVISION
 
771
        else:
 
772
            revid = rev_history[-1]
 
773
        if rev_history != self._lefthand_history(revid):
 
774
            raise errors.NotLefthandHistory(rev_history)
 
775
        self.set_last_revision_info(len(rev_history), revid)
 
776
        self._cache_revision_history(rev_history)
 
777
        for hook in Branch.hooks['set_rh']:
 
778
            hook(self, rev_history)
 
779
 
 
780
    @needs_write_lock
 
781
    def set_last_revision_info(self, revno, revision_id):
 
782
        """Set the last revision of this branch.
 
783
 
 
784
        The caller is responsible for checking that the revno is correct
 
785
        for this revision id.
 
786
 
 
787
        It may be possible to set the branch last revision to an id not
 
788
        present in the repository.  However, branches can also be
 
789
        configured to check constraints on history, in which case this may not
 
790
        be permitted.
 
791
        """
 
792
        raise NotImplementedError(self.set_last_revision_info)
 
793
 
 
794
    @needs_write_lock
 
795
    def generate_revision_history(self, revision_id, last_rev=None,
 
796
                                  other_branch=None):
 
797
        """See Branch.generate_revision_history"""
 
798
        graph = self.repository.get_graph()
 
799
        (last_revno, last_revid) = self.last_revision_info()
 
800
        known_revision_ids = [
 
801
            (last_revid, last_revno),
 
802
            (_mod_revision.NULL_REVISION, 0),
 
803
            ]
 
804
        if last_rev is not None:
 
805
            if not graph.is_ancestor(last_rev, revision_id):
 
806
                # our previous tip is not merged into stop_revision
 
807
                raise errors.DivergedBranches(self, other_branch)
 
808
        revno = graph.find_distance_to_null(revision_id, known_revision_ids)
 
809
        self.set_last_revision_info(revno, revision_id)
744
810
 
745
811
    @needs_write_lock
746
812
    def set_parent(self, url):
783
849
                return
784
850
            self._unstack()
785
851
        else:
786
 
            self._activate_fallback_location(url)
 
852
            self._activate_fallback_location(url,
 
853
                possible_transports=[self.bzrdir.root_transport])
787
854
        # write this out after the repository is stacked to avoid setting a
788
855
        # stacked config that doesn't work.
789
856
        self._set_config_location('stacked_on_location', url)
790
857
 
791
858
    def _unstack(self):
792
859
        """Change a branch to be unstacked, copying data as needed.
793
 
        
 
860
 
794
861
        Don't call this directly, use set_stacked_on_url(None).
795
862
        """
796
863
        pb = ui.ui_factory.nested_progress_bar()
797
864
        try:
798
 
            pb.update("Unstacking")
 
865
            pb.update(gettext("Unstacking"))
799
866
            # The basic approach here is to fetch the tip of the branch,
800
867
            # including all available ghosts, from the existing stacked
801
868
            # repository into a new repository object without the fallbacks. 
805
872
            old_repository = self.repository
806
873
            if len(old_repository._fallback_repositories) != 1:
807
874
                raise AssertionError("can't cope with fallback repositories "
808
 
                    "of %r" % (self.repository,))
 
875
                    "of %r (fallbacks: %r)" % (old_repository,
 
876
                        old_repository._fallback_repositories))
809
877
            # Open the new repository object.
810
878
            # Repositories don't offer an interface to remove fallback
811
879
            # repositories today; take the conceptually simpler option and just
814
882
            # stream from one of them to the other.  This does mean doing
815
883
            # separate SSH connection setup, but unstacking is not a
816
884
            # common operation so it's tolerable.
817
 
            new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
 
885
            new_bzrdir = controldir.ControlDir.open(
 
886
                self.bzrdir.root_transport.base)
818
887
            new_repository = new_bzrdir.find_repository()
819
888
            if new_repository._fallback_repositories:
820
889
                raise AssertionError("didn't expect %r to have "
859
928
                # XXX: If you unstack a branch while it has a working tree
860
929
                # with a pending merge, the pending-merged revisions will no
861
930
                # longer be present.  You can (probably) revert and remerge.
862
 
                #
863
 
                # XXX: This only fetches up to the tip of the repository; it
864
 
                # doesn't bring across any tags.  That's fairly consistent
865
 
                # with how branch works, but perhaps not ideal.
866
 
                self.repository.fetch(old_repository,
867
 
                    revision_id=self.last_revision(),
868
 
                    find_ghosts=True)
 
931
                try:
 
932
                    tags_to_fetch = set(self.tags.get_reverse_tag_dict())
 
933
                except errors.TagsNotSupported:
 
934
                    tags_to_fetch = set()
 
935
                fetch_spec = vf_search.NotInOtherForRevs(self.repository,
 
936
                    old_repository, required_ids=[self.last_revision()],
 
937
                    if_present_ids=tags_to_fetch, find_ghosts=True).execute()
 
938
                self.repository.fetch(old_repository, fetch_spec=fetch_spec)
869
939
            finally:
870
940
                old_repository.unlock()
871
941
        finally:
876
946
 
877
947
        :seealso: Branch._get_tags_bytes.
878
948
        """
879
 
        return _run_with_write_locked_target(self, self._transport.put_bytes,
880
 
            'tags', bytes)
 
949
        op = cleanup.OperationWithCleanups(self._set_tags_bytes_locked)
 
950
        op.add_cleanup(self.lock_write().unlock)
 
951
        return op.run_simple(bytes)
 
952
 
 
953
    def _set_tags_bytes_locked(self, bytes):
 
954
        self._tags_bytes = bytes
 
955
        return self._transport.put_bytes('tags', bytes)
881
956
 
882
957
    def _cache_revision_history(self, rev_history):
883
958
        """Set the cached revision history to rev_history.
910
985
        self._revision_history_cache = None
911
986
        self._revision_id_to_revno_cache = None
912
987
        self._last_revision_info_cache = None
 
988
        self._master_branch_cache = None
913
989
        self._merge_sorted_revisions_cache = None
914
990
        self._partial_revision_history_cache = []
915
991
        self._partial_revision_id_to_revno_cache = {}
 
992
        self._tags_bytes = None
916
993
 
917
994
    def _gen_revision_history(self):
918
995
        """Return sequence of revision hashes on to this branch.
929
1006
        """
930
1007
        raise NotImplementedError(self._gen_revision_history)
931
1008
 
 
1009
    @deprecated_method(deprecated_in((2, 5, 0)))
932
1010
    @needs_read_lock
933
1011
    def revision_history(self):
934
1012
        """Return sequence of revision ids on this branch.
936
1014
        This method will cache the revision history for as long as it is safe to
937
1015
        do so.
938
1016
        """
 
1017
        return self._revision_history()
 
1018
 
 
1019
    def _revision_history(self):
939
1020
        if 'evil' in debug.debug_flags:
940
1021
            mutter_callsite(3, "revision_history scales with history.")
941
1022
        if self._revision_history_cache is not None:
968
1049
        :return: A tuple (revno, revision_id).
969
1050
        """
970
1051
        if self._last_revision_info_cache is None:
971
 
            self._last_revision_info_cache = self._last_revision_info()
 
1052
            self._last_revision_info_cache = self._read_last_revision_info()
972
1053
        return self._last_revision_info_cache
973
1054
 
974
 
    def _last_revision_info(self):
975
 
        rh = self.revision_history()
976
 
        revno = len(rh)
977
 
        if revno:
978
 
            return (revno, rh[-1])
979
 
        else:
980
 
            return (0, _mod_revision.NULL_REVISION)
981
 
 
982
 
    @deprecated_method(deprecated_in((1, 6, 0)))
983
 
    def missing_revisions(self, other, stop_revision=None):
984
 
        """Return a list of new revisions that would perfectly fit.
985
 
 
986
 
        If self and other have not diverged, return a list of the revisions
987
 
        present in other, but missing from self.
988
 
        """
989
 
        self_history = self.revision_history()
990
 
        self_len = len(self_history)
991
 
        other_history = other.revision_history()
992
 
        other_len = len(other_history)
993
 
        common_index = min(self_len, other_len) -1
994
 
        if common_index >= 0 and \
995
 
            self_history[common_index] != other_history[common_index]:
996
 
            raise errors.DivergedBranches(self, other)
997
 
 
998
 
        if stop_revision is None:
999
 
            stop_revision = other_len
1000
 
        else:
1001
 
            if stop_revision > other_len:
1002
 
                raise errors.NoSuchRevision(self, stop_revision)
1003
 
        return other_history[self_len:stop_revision]
1004
 
 
1005
 
    def update_revisions(self, other, stop_revision=None, overwrite=False,
1006
 
                         graph=None):
1007
 
        """Pull in new perfect-fit revisions.
1008
 
 
1009
 
        :param other: Another Branch to pull from
1010
 
        :param stop_revision: Updated until the given revision
1011
 
        :param overwrite: Always set the branch pointer, rather than checking
1012
 
            to see if it is a proper descendant.
1013
 
        :param graph: A Graph object that can be used to query history
1014
 
            information. This can be None.
1015
 
        :return: None
1016
 
        """
1017
 
        return InterBranch.get(other, self).update_revisions(stop_revision,
1018
 
            overwrite, graph)
1019
 
 
 
1055
    def _read_last_revision_info(self):
 
1056
        raise NotImplementedError(self._read_last_revision_info)
 
1057
 
 
1058
    @deprecated_method(deprecated_in((2, 4, 0)))
1020
1059
    def import_last_revision_info(self, source_repo, revno, revid):
1021
1060
        """Set the last revision info, importing from another repo if necessary.
1022
1061
 
1023
 
        This is used by the bound branch code to upload a revision to
1024
 
        the master branch first before updating the tip of the local branch.
1025
 
 
1026
1062
        :param source_repo: Source repository to optionally fetch from
1027
1063
        :param revno: Revision number of the new tip
1028
1064
        :param revid: Revision id of the new tip
1031
1067
            self.repository.fetch(source_repo, revision_id=revid)
1032
1068
        self.set_last_revision_info(revno, revid)
1033
1069
 
 
1070
    def import_last_revision_info_and_tags(self, source, revno, revid,
 
1071
                                           lossy=False):
 
1072
        """Set the last revision info, importing from another repo if necessary.
 
1073
 
 
1074
        This is used by the bound branch code to upload a revision to
 
1075
        the master branch first before updating the tip of the local branch.
 
1076
        Revisions referenced by source's tags are also transferred.
 
1077
 
 
1078
        :param source: Source branch to optionally fetch from
 
1079
        :param revno: Revision number of the new tip
 
1080
        :param revid: Revision id of the new tip
 
1081
        :param lossy: Whether to discard metadata that can not be
 
1082
            natively represented
 
1083
        :return: Tuple with the new revision number and revision id
 
1084
            (should only be different from the arguments when lossy=True)
 
1085
        """
 
1086
        if not self.repository.has_same_location(source.repository):
 
1087
            self.fetch(source, revid)
 
1088
        self.set_last_revision_info(revno, revid)
 
1089
        return (revno, revid)
 
1090
 
1034
1091
    def revision_id_to_revno(self, revision_id):
1035
1092
        """Given a revision id, return its revno"""
1036
1093
        if _mod_revision.is_null(revision_id):
1037
1094
            return 0
1038
 
        history = self.revision_history()
 
1095
        history = self._revision_history()
1039
1096
        try:
1040
1097
            return history.index(revision_id) + 1
1041
1098
        except ValueError:
1068
1125
            stop_revision=stop_revision,
1069
1126
            possible_transports=possible_transports, *args, **kwargs)
1070
1127
 
1071
 
    def push(self, target, overwrite=False, stop_revision=None, *args,
1072
 
        **kwargs):
 
1128
    def push(self, target, overwrite=False, stop_revision=None, lossy=False,
 
1129
            *args, **kwargs):
1073
1130
        """Mirror this branch into target.
1074
1131
 
1075
1132
        This branch is considered to be 'local', having low latency.
1076
1133
        """
1077
1134
        return InterBranch.get(self, target).push(overwrite, stop_revision,
1078
 
            *args, **kwargs)
1079
 
 
1080
 
    def lossy_push(self, target, stop_revision=None):
1081
 
        """Push deltas into another branch.
1082
 
 
1083
 
        :note: This does not, like push, retain the revision ids from 
1084
 
            the source branch and will, rather than adding bzr-specific 
1085
 
            metadata, push only those semantics of the revision that can be 
1086
 
            natively represented by this branch' VCS.
1087
 
 
1088
 
        :param target: Target branch
1089
 
        :param stop_revision: Revision to push, defaults to last revision.
1090
 
        :return: BranchPushResult with an extra member revidmap: 
1091
 
            A dictionary mapping revision ids from the target branch 
1092
 
            to new revision ids in the target branch, for each 
1093
 
            revision that was pushed.
1094
 
        """
1095
 
        inter = InterBranch.get(self, target)
1096
 
        lossy_push = getattr(inter, "lossy_push", None)
1097
 
        if lossy_push is None:
1098
 
            raise errors.LossyPushToSameVCS(self, target)
1099
 
        return lossy_push(stop_revision)
 
1135
            lossy, *args, **kwargs)
1100
1136
 
1101
1137
    def basis_tree(self):
1102
1138
        """Return `Tree` object for last revision."""
1257
1293
        return result
1258
1294
 
1259
1295
    @needs_read_lock
1260
 
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None):
 
1296
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None,
 
1297
            repository=None):
1261
1298
        """Create a new line of development from the branch, into to_bzrdir.
1262
1299
 
1263
1300
        to_bzrdir controls the branch format.
1268
1305
        if (repository_policy is not None and
1269
1306
            repository_policy.requires_stacking()):
1270
1307
            to_bzrdir._format.require_stacking(_skip_repo=True)
1271
 
        result = to_bzrdir.create_branch()
 
1308
        result = to_bzrdir.create_branch(repository=repository)
1272
1309
        result.lock_write()
1273
1310
        try:
1274
1311
            if repository_policy is not None:
1275
1312
                repository_policy.configure_branch(result)
1276
1313
            self.copy_content_into(result, revision_id=revision_id)
1277
 
            result.set_parent(self.bzrdir.root_transport.base)
 
1314
            master_url = self.get_bound_location()
 
1315
            if master_url is None:
 
1316
                result.set_parent(self.bzrdir.root_transport.base)
 
1317
            else:
 
1318
                result.set_parent(master_url)
1278
1319
        finally:
1279
1320
            result.unlock()
1280
1321
        return result
1354
1395
        # TODO: We should probably also check that self.revision_history
1355
1396
        # matches the repository for older branch formats.
1356
1397
        # If looking for the code that cross-checks repository parents against
1357
 
        # the iter_reverse_revision_history output, that is now a repository
 
1398
        # the Graph.iter_lefthand_ancestry output, that is now a repository
1358
1399
        # specific check.
1359
1400
        return result
1360
1401
 
1361
 
    def _get_checkout_format(self):
 
1402
    def _get_checkout_format(self, lightweight=False):
1362
1403
        """Return the most suitable metadir for a checkout of this branch.
1363
1404
        Weaves are used if this branch's repository uses weaves.
1364
1405
        """
1365
 
        if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
1366
 
            from bzrlib.repofmt import weaverepo
1367
 
            format = bzrdir.BzrDirMetaFormat1()
1368
 
            format.repository_format = weaverepo.RepositoryFormat7()
1369
 
        else:
1370
 
            format = self.repository.bzrdir.checkout_metadir()
1371
 
            format.set_branch_format(self._format)
 
1406
        format = self.repository.bzrdir.checkout_metadir()
 
1407
        format.set_branch_format(self._format)
1372
1408
        return format
1373
1409
 
1374
1410
    def create_clone_on_transport(self, to_transport, revision_id=None,
1404
1440
        :param to_location: The url to produce the checkout at
1405
1441
        :param revision_id: The revision to check out
1406
1442
        :param lightweight: If True, produce a lightweight checkout, otherwise,
1407
 
        produce a bound branch (heavyweight checkout)
 
1443
            produce a bound branch (heavyweight checkout)
1408
1444
        :param accelerator_tree: A tree which can be used for retrieving file
1409
1445
            contents more quickly than the revision tree, i.e. a workingtree.
1410
1446
            The revision tree will be used for cases where accelerator_tree's
1415
1451
        """
1416
1452
        t = transport.get_transport(to_location)
1417
1453
        t.ensure_base()
 
1454
        format = self._get_checkout_format(lightweight=lightweight)
1418
1455
        if lightweight:
1419
 
            format = self._get_checkout_format()
1420
1456
            checkout = format.initialize_on_transport(t)
1421
1457
            from_branch = BranchReferenceFormat().initialize(checkout, 
1422
1458
                target_branch=self)
1423
1459
        else:
1424
 
            format = self._get_checkout_format()
1425
 
            checkout_branch = bzrdir.BzrDir.create_branch_convenience(
 
1460
            checkout_branch = controldir.ControlDir.create_branch_convenience(
1426
1461
                to_location, force_new_tree=False, format=format)
1427
1462
            checkout = checkout_branch.bzrdir
1428
1463
            checkout_branch.bind(self)
1456
1491
 
1457
1492
    def reference_parent(self, file_id, path, possible_transports=None):
1458
1493
        """Return the parent branch for a tree-reference file_id
 
1494
 
1459
1495
        :param file_id: The file_id of the tree reference
1460
1496
        :param path: The path of the file_id in the tree
1461
1497
        :return: A branch associated with the file_id
1514
1550
        else:
1515
1551
            raise AssertionError("invalid heads: %r" % (heads,))
1516
1552
 
1517
 
 
1518
 
class BranchFormat(object):
 
1553
    def heads_to_fetch(self):
 
1554
        """Return the heads that must and that should be fetched to copy this
 
1555
        branch into another repo.
 
1556
 
 
1557
        :returns: a 2-tuple of (must_fetch, if_present_fetch).  must_fetch is a
 
1558
            set of heads that must be fetched.  if_present_fetch is a set of
 
1559
            heads that must be fetched if present, but no error is necessary if
 
1560
            they are not present.
 
1561
        """
 
1562
        # For bzr native formats must_fetch is just the tip, and if_present_fetch
 
1563
        # are the tags.
 
1564
        must_fetch = set([self.last_revision()])
 
1565
        if_present_fetch = set()
 
1566
        c = self.get_config()
 
1567
        include_tags = c.get_user_option_as_bool('branch.fetch_tags',
 
1568
                                                 default=False)
 
1569
        if include_tags:
 
1570
            try:
 
1571
                if_present_fetch = set(self.tags.get_reverse_tag_dict())
 
1572
            except errors.TagsNotSupported:
 
1573
                pass
 
1574
        must_fetch.discard(_mod_revision.NULL_REVISION)
 
1575
        if_present_fetch.discard(_mod_revision.NULL_REVISION)
 
1576
        return must_fetch, if_present_fetch
 
1577
 
 
1578
 
 
1579
class BranchFormat(controldir.ControlComponentFormat):
1519
1580
    """An encapsulation of the initialization and open routines for a format.
1520
1581
 
1521
1582
    Formats provide three things:
1533
1594
    object will be created every time regardless.
1534
1595
    """
1535
1596
 
1536
 
    _default_format = None
1537
 
    """The default format used for new branches."""
1538
 
 
1539
 
    _formats = {}
1540
 
    """The known formats."""
1541
 
 
1542
 
    can_set_append_revisions_only = True
1543
 
 
1544
1597
    def __eq__(self, other):
1545
1598
        return self.__class__ is other.__class__
1546
1599
 
1548
1601
        return not (self == other)
1549
1602
 
1550
1603
    @classmethod
1551
 
    def find_format(klass, a_bzrdir, name=None):
1552
 
        """Return the format for the branch object in a_bzrdir."""
1553
 
        try:
1554
 
            transport = a_bzrdir.get_branch_transport(None, name=name)
1555
 
            format_string = transport.get_bytes("format")
1556
 
            format = klass._formats[format_string]
1557
 
            if isinstance(format, MetaDirBranchFormatFactory):
1558
 
                return format()
1559
 
            return format
1560
 
        except errors.NoSuchFile:
1561
 
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1562
 
        except KeyError:
1563
 
            raise errors.UnknownFormatError(format=format_string, kind='branch')
1564
 
 
1565
 
    @classmethod
 
1604
    @deprecated_method(deprecated_in((2, 4, 0)))
1566
1605
    def get_default_format(klass):
1567
1606
        """Return the current default format."""
1568
 
        return klass._default_format
 
1607
        return format_registry.get_default()
1569
1608
 
1570
1609
    @classmethod
 
1610
    @deprecated_method(deprecated_in((2, 4, 0)))
1571
1611
    def get_formats(klass):
1572
1612
        """Get all the known formats.
1573
1613
 
1574
1614
        Warning: This triggers a load of all lazy registered formats: do not
1575
1615
        use except when that is desireed.
1576
1616
        """
1577
 
        result = []
1578
 
        for fmt in klass._formats.values():
1579
 
            if isinstance(fmt, MetaDirBranchFormatFactory):
1580
 
                fmt = fmt()
1581
 
            result.append(fmt)
1582
 
        return result
 
1617
        return format_registry._get_all()
1583
1618
 
1584
 
    def get_reference(self, a_bzrdir, name=None):
1585
 
        """Get the target reference of the branch in a_bzrdir.
 
1619
    def get_reference(self, controldir, name=None):
 
1620
        """Get the target reference of the branch in controldir.
1586
1621
 
1587
1622
        format probing must have been completed before calling
1588
1623
        this method - it is assumed that the format of the branch
1589
 
        in a_bzrdir is correct.
 
1624
        in controldir is correct.
1590
1625
 
1591
 
        :param a_bzrdir: The bzrdir to get the branch data from.
 
1626
        :param controldir: The controldir to get the branch data from.
1592
1627
        :param name: Name of the colocated branch to fetch
1593
1628
        :return: None if the branch is not a reference branch.
1594
1629
        """
1595
1630
        return None
1596
1631
 
1597
1632
    @classmethod
1598
 
    def set_reference(self, a_bzrdir, name, to_branch):
1599
 
        """Set the target reference of the branch in a_bzrdir.
 
1633
    def set_reference(self, controldir, name, to_branch):
 
1634
        """Set the target reference of the branch in controldir.
1600
1635
 
1601
1636
        format probing must have been completed before calling
1602
1637
        this method - it is assumed that the format of the branch
1603
 
        in a_bzrdir is correct.
 
1638
        in controldir is correct.
1604
1639
 
1605
 
        :param a_bzrdir: The bzrdir to set the branch reference for.
 
1640
        :param controldir: The controldir to set the branch reference for.
1606
1641
        :param name: Name of colocated branch to set, None for default
1607
1642
        :param to_branch: branch that the checkout is to reference
1608
1643
        """
1609
1644
        raise NotImplementedError(self.set_reference)
1610
1645
 
1611
 
    def get_format_string(self):
1612
 
        """Return the ASCII format string that identifies this format."""
1613
 
        raise NotImplementedError(self.get_format_string)
1614
 
 
1615
1646
    def get_format_description(self):
1616
1647
        """Return the short format description for this format."""
1617
1648
        raise NotImplementedError(self.get_format_description)
1618
1649
 
1619
 
    def _run_post_branch_init_hooks(self, a_bzrdir, name, branch):
 
1650
    def _run_post_branch_init_hooks(self, controldir, name, branch):
1620
1651
        hooks = Branch.hooks['post_branch_init']
1621
1652
        if not hooks:
1622
1653
            return
1623
 
        params = BranchInitHookParams(self, a_bzrdir, name, branch)
 
1654
        params = BranchInitHookParams(self, controldir, name, branch)
1624
1655
        for hook in hooks:
1625
1656
            hook(params)
1626
1657
 
1627
 
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
1628
 
                           lock_type='metadir', set_format=True):
1629
 
        """Initialize a branch in a bzrdir, with specified files
1630
 
 
1631
 
        :param a_bzrdir: The bzrdir to initialize the branch in
1632
 
        :param utf8_files: The files to create as a list of
1633
 
            (filename, content) tuples
1634
 
        :param name: Name of colocated branch to create, if any
1635
 
        :param set_format: If True, set the format with
1636
 
            self.get_format_string.  (BzrBranch4 has its format set
1637
 
            elsewhere)
1638
 
        :return: a branch in this format
1639
 
        """
1640
 
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
1641
 
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
1642
 
        lock_map = {
1643
 
            'metadir': ('lock', lockdir.LockDir),
1644
 
            'branch4': ('branch-lock', lockable_files.TransportLock),
1645
 
        }
1646
 
        lock_name, lock_class = lock_map[lock_type]
1647
 
        control_files = lockable_files.LockableFiles(branch_transport,
1648
 
            lock_name, lock_class)
1649
 
        control_files.create_lock()
1650
 
        try:
1651
 
            control_files.lock_write()
1652
 
        except errors.LockContention:
1653
 
            if lock_type != 'branch4':
1654
 
                raise
1655
 
            lock_taken = False
1656
 
        else:
1657
 
            lock_taken = True
1658
 
        if set_format:
1659
 
            utf8_files += [('format', self.get_format_string())]
1660
 
        try:
1661
 
            for (filename, content) in utf8_files:
1662
 
                branch_transport.put_bytes(
1663
 
                    filename, content,
1664
 
                    mode=a_bzrdir._get_file_mode())
1665
 
        finally:
1666
 
            if lock_taken:
1667
 
                control_files.unlock()
1668
 
        branch = self.open(a_bzrdir, name, _found=True)
1669
 
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
1670
 
        return branch
1671
 
 
1672
 
    def initialize(self, a_bzrdir, name=None):
1673
 
        """Create a branch of this format in a_bzrdir.
1674
 
        
 
1658
    def initialize(self, controldir, name=None, repository=None,
 
1659
                   append_revisions_only=None):
 
1660
        """Create a branch of this format in controldir.
 
1661
 
1675
1662
        :param name: Name of the colocated branch to create.
1676
1663
        """
1677
1664
        raise NotImplementedError(self.initialize)
1697
1684
        Note that it is normal for branch to be a RemoteBranch when using tags
1698
1685
        on a RemoteBranch.
1699
1686
        """
1700
 
        return DisabledTags(branch)
 
1687
        return _mod_tag.DisabledTags(branch)
1701
1688
 
1702
1689
    def network_name(self):
1703
1690
        """A simple byte string uniquely identifying this format for RPC calls.
1709
1696
        """
1710
1697
        raise NotImplementedError(self.network_name)
1711
1698
 
1712
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
1713
 
        """Return the branch object for a_bzrdir
 
1699
    def open(self, controldir, name=None, _found=False, ignore_fallbacks=False,
 
1700
            found_repository=None, possible_transports=None):
 
1701
        """Return the branch object for controldir.
1714
1702
 
1715
 
        :param a_bzrdir: A BzrDir that contains a branch.
 
1703
        :param controldir: A ControlDir that contains a branch.
1716
1704
        :param name: Name of colocated branch to open
1717
1705
        :param _found: a private parameter, do not use it. It is used to
1718
1706
            indicate if format probing has already be done.
1722
1710
        raise NotImplementedError(self.open)
1723
1711
 
1724
1712
    @classmethod
 
1713
    @deprecated_method(deprecated_in((2, 4, 0)))
1725
1714
    def register_format(klass, format):
1726
1715
        """Register a metadir format.
1727
 
        
 
1716
 
1728
1717
        See MetaDirBranchFormatFactory for the ability to register a format
1729
1718
        without loading the code the format needs until it is actually used.
1730
1719
        """
1731
 
        klass._formats[format.get_format_string()] = format
1732
 
        # Metadir formats have a network name of their format string, and get
1733
 
        # registered as factories.
1734
 
        if isinstance(format, MetaDirBranchFormatFactory):
1735
 
            network_format_registry.register(format.get_format_string(), format)
1736
 
        else:
1737
 
            network_format_registry.register(format.get_format_string(),
1738
 
                format.__class__)
 
1720
        format_registry.register(format)
1739
1721
 
1740
1722
    @classmethod
 
1723
    @deprecated_method(deprecated_in((2, 4, 0)))
1741
1724
    def set_default_format(klass, format):
1742
 
        klass._default_format = format
 
1725
        format_registry.set_default(format)
1743
1726
 
1744
1727
    def supports_set_append_revisions_only(self):
1745
1728
        """True if this format supports set_append_revisions_only."""
1749
1732
        """True if this format records a stacked-on branch."""
1750
1733
        return False
1751
1734
 
 
1735
    def supports_leaving_lock(self):
 
1736
        """True if this format supports leaving locks in place."""
 
1737
        return False # by default
 
1738
 
1752
1739
    @classmethod
 
1740
    @deprecated_method(deprecated_in((2, 4, 0)))
1753
1741
    def unregister_format(klass, format):
1754
 
        del klass._formats[format.get_format_string()]
 
1742
        format_registry.remove(format)
1755
1743
 
1756
1744
    def __str__(self):
1757
1745
        return self.get_format_description().rstrip()
1760
1748
        """True if this format supports tags stored in the branch"""
1761
1749
        return False  # by default
1762
1750
 
 
1751
    def tags_are_versioned(self):
 
1752
        """Whether the tag container for this branch versions tags."""
 
1753
        return False
 
1754
 
 
1755
    def supports_tags_referencing_ghosts(self):
 
1756
        """True if tags can reference ghost revisions."""
 
1757
        return True
 
1758
 
1763
1759
 
1764
1760
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
1765
1761
    """A factory for a BranchFormat object, permitting simple lazy registration.
1779
1775
        """
1780
1776
        registry._LazyObjectGetter.__init__(self, module_name, member_name)
1781
1777
        self._format_string = format_string
1782
 
        
 
1778
 
1783
1779
    def get_format_string(self):
1784
1780
        """See BranchFormat.get_format_string."""
1785
1781
        return self._format_string
1802
1798
        These are all empty initially, because by default nothing should get
1803
1799
        notified.
1804
1800
        """
1805
 
        Hooks.__init__(self)
1806
 
        self.create_hook(HookPoint('set_rh',
 
1801
        Hooks.__init__(self, "bzrlib.branch", "Branch.hooks")
 
1802
        self.add_hook('set_rh',
1807
1803
            "Invoked whenever the revision history has been set via "
1808
1804
            "set_revision_history. The api signature is (branch, "
1809
1805
            "revision_history), and the branch will be write-locked. "
1810
1806
            "The set_rh hook can be expensive for bzr to trigger, a better "
1811
 
            "hook to use is Branch.post_change_branch_tip.", (0, 15), None))
1812
 
        self.create_hook(HookPoint('open',
 
1807
            "hook to use is Branch.post_change_branch_tip.", (0, 15))
 
1808
        self.add_hook('open',
1813
1809
            "Called with the Branch object that has been opened after a "
1814
 
            "branch is opened.", (1, 8), None))
1815
 
        self.create_hook(HookPoint('post_push',
 
1810
            "branch is opened.", (1, 8))
 
1811
        self.add_hook('post_push',
1816
1812
            "Called after a push operation completes. post_push is called "
1817
1813
            "with a bzrlib.branch.BranchPushResult object and only runs in the "
1818
 
            "bzr client.", (0, 15), None))
1819
 
        self.create_hook(HookPoint('post_pull',
 
1814
            "bzr client.", (0, 15))
 
1815
        self.add_hook('post_pull',
1820
1816
            "Called after a pull operation completes. post_pull is called "
1821
1817
            "with a bzrlib.branch.PullResult object and only runs in the "
1822
 
            "bzr client.", (0, 15), None))
1823
 
        self.create_hook(HookPoint('pre_commit',
 
1818
            "bzr client.", (0, 15))
 
1819
        self.add_hook('pre_commit',
1824
1820
            "Called after a commit is calculated but before it is "
1825
1821
            "completed. pre_commit is called with (local, master, old_revno, "
1826
1822
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
1829
1825
            "basis revision. hooks MUST NOT modify this delta. "
1830
1826
            " future_tree is an in-memory tree obtained from "
1831
1827
            "CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1832
 
            "tree.", (0,91), None))
1833
 
        self.create_hook(HookPoint('post_commit',
 
1828
            "tree.", (0,91))
 
1829
        self.add_hook('post_commit',
1834
1830
            "Called in the bzr client after a commit has completed. "
1835
1831
            "post_commit is called with (local, master, old_revno, old_revid, "
1836
1832
            "new_revno, new_revid). old_revid is NULL_REVISION for the first "
1837
 
            "commit to a branch.", (0, 15), None))
1838
 
        self.create_hook(HookPoint('post_uncommit',
 
1833
            "commit to a branch.", (0, 15))
 
1834
        self.add_hook('post_uncommit',
1839
1835
            "Called in the bzr client after an uncommit completes. "
1840
1836
            "post_uncommit is called with (local, master, old_revno, "
1841
1837
            "old_revid, new_revno, new_revid) where local is the local branch "
1842
1838
            "or None, master is the target branch, and an empty branch "
1843
 
            "receives new_revno of 0, new_revid of None.", (0, 15), None))
1844
 
        self.create_hook(HookPoint('pre_change_branch_tip',
 
1839
            "receives new_revno of 0, new_revid of None.", (0, 15))
 
1840
        self.add_hook('pre_change_branch_tip',
1845
1841
            "Called in bzr client and server before a change to the tip of a "
1846
1842
            "branch is made. pre_change_branch_tip is called with a "
1847
1843
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1848
 
            "commit, uncommit will all trigger this hook.", (1, 6), None))
1849
 
        self.create_hook(HookPoint('post_change_branch_tip',
 
1844
            "commit, uncommit will all trigger this hook.", (1, 6))
 
1845
        self.add_hook('post_change_branch_tip',
1850
1846
            "Called in bzr client and server after a change to the tip of a "
1851
1847
            "branch is made. post_change_branch_tip is called with a "
1852
1848
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1853
 
            "commit, uncommit will all trigger this hook.", (1, 4), None))
1854
 
        self.create_hook(HookPoint('transform_fallback_location',
 
1849
            "commit, uncommit will all trigger this hook.", (1, 4))
 
1850
        self.add_hook('transform_fallback_location',
1855
1851
            "Called when a stacked branch is activating its fallback "
1856
1852
            "locations. transform_fallback_location is called with (branch, "
1857
1853
            "url), and should return a new url. Returning the same url "
1862
1858
            "fallback locations have not been activated. When there are "
1863
1859
            "multiple hooks installed for transform_fallback_location, "
1864
1860
            "all are called with the url returned from the previous hook."
1865
 
            "The order is however undefined.", (1, 9), None))
1866
 
        self.create_hook(HookPoint('automatic_tag_name',
 
1861
            "The order is however undefined.", (1, 9))
 
1862
        self.add_hook('automatic_tag_name',
1867
1863
            "Called to determine an automatic tag name for a revision. "
1868
1864
            "automatic_tag_name is called with (branch, revision_id) and "
1869
1865
            "should return a tag name or None if no tag name could be "
1870
1866
            "determined. The first non-None tag name returned will be used.",
1871
 
            (2, 2), None))
1872
 
        self.create_hook(HookPoint('post_branch_init',
 
1867
            (2, 2))
 
1868
        self.add_hook('post_branch_init',
1873
1869
            "Called after new branch initialization completes. "
1874
1870
            "post_branch_init is called with a "
1875
1871
            "bzrlib.branch.BranchInitHookParams. "
1876
1872
            "Note that init, branch and checkout (both heavyweight and "
1877
 
            "lightweight) will all trigger this hook.", (2, 2), None))
1878
 
        self.create_hook(HookPoint('post_switch',
 
1873
            "lightweight) will all trigger this hook.", (2, 2))
 
1874
        self.add_hook('post_switch',
1879
1875
            "Called after a checkout switches branch. "
1880
1876
            "post_switch is called with a "
1881
 
            "bzrlib.branch.SwitchHookParams.", (2, 2), None))
 
1877
            "bzrlib.branch.SwitchHookParams.", (2, 2))
1882
1878
 
1883
1879
 
1884
1880
 
1887
1883
 
1888
1884
 
1889
1885
class ChangeBranchTipParams(object):
1890
 
    """Object holding parameters passed to *_change_branch_tip hooks.
 
1886
    """Object holding parameters passed to `*_change_branch_tip` hooks.
1891
1887
 
1892
1888
    There are 5 fields that hooks may wish to access:
1893
1889
 
1925
1921
 
1926
1922
 
1927
1923
class BranchInitHookParams(object):
1928
 
    """Object holding parameters passed to *_branch_init hooks.
 
1924
    """Object holding parameters passed to `*_branch_init` hooks.
1929
1925
 
1930
1926
    There are 4 fields that hooks may wish to access:
1931
1927
 
1932
1928
    :ivar format: the branch format
1933
 
    :ivar bzrdir: the BzrDir where the branch will be/has been initialized
 
1929
    :ivar bzrdir: the ControlDir where the branch will be/has been initialized
1934
1930
    :ivar name: name of colocated branch, if any (or None)
1935
1931
    :ivar branch: the branch created
1936
1932
 
1939
1935
    branch, which refer to the original branch.
1940
1936
    """
1941
1937
 
1942
 
    def __init__(self, format, a_bzrdir, name, branch):
 
1938
    def __init__(self, format, controldir, name, branch):
1943
1939
        """Create a group of BranchInitHook parameters.
1944
1940
 
1945
1941
        :param format: the branch format
1946
 
        :param a_bzrdir: the BzrDir where the branch will be/has been
 
1942
        :param controldir: the ControlDir where the branch will be/has been
1947
1943
            initialized
1948
1944
        :param name: name of colocated branch, if any (or None)
1949
1945
        :param branch: the branch created
1953
1949
        in branch, which refer to the original branch.
1954
1950
        """
1955
1951
        self.format = format
1956
 
        self.bzrdir = a_bzrdir
 
1952
        self.bzrdir = controldir
1957
1953
        self.name = name
1958
1954
        self.branch = branch
1959
1955
 
1965
1961
 
1966
1962
 
1967
1963
class SwitchHookParams(object):
1968
 
    """Object holding parameters passed to *_switch hooks.
 
1964
    """Object holding parameters passed to `*_switch` hooks.
1969
1965
 
1970
1966
    There are 4 fields that hooks may wish to access:
1971
1967
 
1972
 
    :ivar control_dir: BzrDir of the checkout to change
 
1968
    :ivar control_dir: ControlDir of the checkout to change
1973
1969
    :ivar to_branch: branch that the checkout is to reference
1974
1970
    :ivar force: skip the check for local commits in a heavy checkout
1975
1971
    :ivar revision_id: revision ID to switch to (or None)
1978
1974
    def __init__(self, control_dir, to_branch, force, revision_id):
1979
1975
        """Create a group of SwitchHook parameters.
1980
1976
 
1981
 
        :param control_dir: BzrDir of the checkout to change
 
1977
        :param control_dir: ControlDir of the checkout to change
1982
1978
        :param to_branch: branch that the checkout is to reference
1983
1979
        :param force: skip the check for local commits in a heavy checkout
1984
1980
        :param revision_id: revision ID to switch to (or None)
1997
1993
            self.revision_id)
1998
1994
 
1999
1995
 
2000
 
class BzrBranchFormat4(BranchFormat):
2001
 
    """Bzr branch format 4.
2002
 
 
2003
 
    This format has:
2004
 
     - a revision-history file.
2005
 
     - a branch-lock lock file [ to be shared with the bzrdir ]
 
1996
class BranchFormatMetadir(bzrdir.BzrDirMetaComponentFormat, BranchFormat):
 
1997
    """Base class for branch formats that live in meta directories.
2006
1998
    """
2007
1999
 
2008
 
    def get_format_description(self):
2009
 
        """See BranchFormat.get_format_description()."""
2010
 
        return "Branch format 4"
2011
 
 
2012
 
    def initialize(self, a_bzrdir, name=None):
2013
 
        """Create a branch of this format in a_bzrdir."""
2014
 
        utf8_files = [('revision-history', ''),
2015
 
                      ('branch-name', ''),
2016
 
                      ]
2017
 
        return self._initialize_helper(a_bzrdir, utf8_files, name=name,
2018
 
                                       lock_type='branch4', set_format=False)
2019
 
 
2020
2000
    def __init__(self):
2021
 
        super(BzrBranchFormat4, self).__init__()
2022
 
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
2023
 
 
2024
 
    def network_name(self):
2025
 
        """The network name for this format is the control dirs disk label."""
2026
 
        return self._matchingbzrdir.get_format_string()
2027
 
 
2028
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
2029
 
        """See BranchFormat.open()."""
2030
 
        if not _found:
2031
 
            # we are being called directly and must probe.
2032
 
            raise NotImplementedError
2033
 
        return BzrBranch(_format=self,
2034
 
                         _control_files=a_bzrdir._control_files,
2035
 
                         a_bzrdir=a_bzrdir,
2036
 
                         name=name,
2037
 
                         _repository=a_bzrdir.open_repository())
2038
 
 
2039
 
    def __str__(self):
2040
 
        return "Bazaar-NG branch format 4"
2041
 
 
2042
 
 
2043
 
class BranchFormatMetadir(BranchFormat):
2044
 
    """Common logic for meta-dir based branch formats."""
 
2001
        BranchFormat.__init__(self)
 
2002
        bzrdir.BzrDirMetaComponentFormat.__init__(self)
 
2003
 
 
2004
    @classmethod
 
2005
    def find_format(klass, controldir, name=None):
 
2006
        """Return the format for the branch object in controldir."""
 
2007
        try:
 
2008
            transport = controldir.get_branch_transport(None, name=name)
 
2009
        except errors.NoSuchFile:
 
2010
            raise errors.NotBranchError(path=name, bzrdir=controldir)
 
2011
        try:
 
2012
            format_string = transport.get_bytes("format")
 
2013
        except errors.NoSuchFile:
 
2014
            raise errors.NotBranchError(path=transport.base, bzrdir=controldir)
 
2015
        return klass._find_format(format_registry, 'branch', format_string)
2045
2016
 
2046
2017
    def _branch_class(self):
2047
2018
        """What class to instantiate on open calls."""
2048
2019
        raise NotImplementedError(self._branch_class)
2049
2020
 
2050
 
    def network_name(self):
2051
 
        """A simple byte string uniquely identifying this format for RPC calls.
2052
 
 
2053
 
        Metadir branch formats use their format string.
 
2021
    def _get_initial_config(self, append_revisions_only=None):
 
2022
        if append_revisions_only:
 
2023
            return "append_revisions_only = True\n"
 
2024
        else:
 
2025
            # Avoid writing anything if append_revisions_only is disabled,
 
2026
            # as that is the default.
 
2027
            return ""
 
2028
 
 
2029
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
 
2030
                           repository=None):
 
2031
        """Initialize a branch in a bzrdir, with specified files
 
2032
 
 
2033
        :param a_bzrdir: The bzrdir to initialize the branch in
 
2034
        :param utf8_files: The files to create as a list of
 
2035
            (filename, content) tuples
 
2036
        :param name: Name of colocated branch to create, if any
 
2037
        :return: a branch in this format
2054
2038
        """
2055
 
        return self.get_format_string()
 
2039
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
 
2040
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
2041
        control_files = lockable_files.LockableFiles(branch_transport,
 
2042
            'lock', lockdir.LockDir)
 
2043
        control_files.create_lock()
 
2044
        control_files.lock_write()
 
2045
        try:
 
2046
            utf8_files += [('format', self.get_format_string())]
 
2047
            for (filename, content) in utf8_files:
 
2048
                branch_transport.put_bytes(
 
2049
                    filename, content,
 
2050
                    mode=a_bzrdir._get_file_mode())
 
2051
        finally:
 
2052
            control_files.unlock()
 
2053
        branch = self.open(a_bzrdir, name, _found=True,
 
2054
                found_repository=repository)
 
2055
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
 
2056
        return branch
2056
2057
 
2057
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
2058
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
 
2059
            found_repository=None, possible_transports=None):
2058
2060
        """See BranchFormat.open()."""
2059
2061
        if not _found:
2060
 
            format = BranchFormat.find_format(a_bzrdir, name=name)
 
2062
            format = BranchFormatMetadir.find_format(a_bzrdir, name=name)
2061
2063
            if format.__class__ != self.__class__:
2062
2064
                raise AssertionError("wrong format %r found for %r" %
2063
2065
                    (format, self))
2065
2067
        try:
2066
2068
            control_files = lockable_files.LockableFiles(transport, 'lock',
2067
2069
                                                         lockdir.LockDir)
 
2070
            if found_repository is None:
 
2071
                found_repository = a_bzrdir.find_repository()
2068
2072
            return self._branch_class()(_format=self,
2069
2073
                              _control_files=control_files,
2070
2074
                              name=name,
2071
2075
                              a_bzrdir=a_bzrdir,
2072
 
                              _repository=a_bzrdir.find_repository(),
2073
 
                              ignore_fallbacks=ignore_fallbacks)
 
2076
                              _repository=found_repository,
 
2077
                              ignore_fallbacks=ignore_fallbacks,
 
2078
                              possible_transports=possible_transports)
2074
2079
        except errors.NoSuchFile:
2075
2080
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
2076
2081
 
2077
 
    def __init__(self):
2078
 
        super(BranchFormatMetadir, self).__init__()
2079
 
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
2080
 
        self._matchingbzrdir.set_branch_format(self)
 
2082
    @property
 
2083
    def _matchingbzrdir(self):
 
2084
        ret = bzrdir.BzrDirMetaFormat1()
 
2085
        ret.set_branch_format(self)
 
2086
        return ret
2081
2087
 
2082
2088
    def supports_tags(self):
2083
2089
        return True
2084
2090
 
 
2091
    def supports_leaving_lock(self):
 
2092
        return True
 
2093
 
2085
2094
 
2086
2095
class BzrBranchFormat5(BranchFormatMetadir):
2087
2096
    """Bzr branch format 5.
2099
2108
    def _branch_class(self):
2100
2109
        return BzrBranch5
2101
2110
 
2102
 
    def get_format_string(self):
 
2111
    @classmethod
 
2112
    def get_format_string(cls):
2103
2113
        """See BranchFormat.get_format_string()."""
2104
2114
        return "Bazaar-NG branch format 5\n"
2105
2115
 
2107
2117
        """See BranchFormat.get_format_description()."""
2108
2118
        return "Branch format 5"
2109
2119
 
2110
 
    def initialize(self, a_bzrdir, name=None):
 
2120
    def initialize(self, a_bzrdir, name=None, repository=None,
 
2121
                   append_revisions_only=None):
2111
2122
        """Create a branch of this format in a_bzrdir."""
 
2123
        if append_revisions_only:
 
2124
            raise errors.UpgradeRequired(a_bzrdir.user_url)
2112
2125
        utf8_files = [('revision-history', ''),
2113
2126
                      ('branch-name', ''),
2114
2127
                      ]
2115
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2128
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2116
2129
 
2117
2130
    def supports_tags(self):
2118
2131
        return False
2132
2145
    def _branch_class(self):
2133
2146
        return BzrBranch6
2134
2147
 
2135
 
    def get_format_string(self):
 
2148
    @classmethod
 
2149
    def get_format_string(cls):
2136
2150
        """See BranchFormat.get_format_string()."""
2137
2151
        return "Bazaar Branch Format 6 (bzr 0.15)\n"
2138
2152
 
2140
2154
        """See BranchFormat.get_format_description()."""
2141
2155
        return "Branch format 6"
2142
2156
 
2143
 
    def initialize(self, a_bzrdir, name=None):
 
2157
    def initialize(self, a_bzrdir, name=None, repository=None,
 
2158
                   append_revisions_only=None):
2144
2159
        """Create a branch of this format in a_bzrdir."""
2145
2160
        utf8_files = [('last-revision', '0 null:\n'),
2146
 
                      ('branch.conf', ''),
 
2161
                      ('branch.conf',
 
2162
                          self._get_initial_config(append_revisions_only)),
2147
2163
                      ('tags', ''),
2148
2164
                      ]
2149
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2165
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2150
2166
 
2151
2167
    def make_tags(self, branch):
2152
2168
        """See bzrlib.branch.BranchFormat.make_tags()."""
2153
 
        return BasicTags(branch)
 
2169
        return _mod_tag.BasicTags(branch)
2154
2170
 
2155
2171
    def supports_set_append_revisions_only(self):
2156
2172
        return True
2162
2178
    def _branch_class(self):
2163
2179
        return BzrBranch8
2164
2180
 
2165
 
    def get_format_string(self):
 
2181
    @classmethod
 
2182
    def get_format_string(cls):
2166
2183
        """See BranchFormat.get_format_string()."""
2167
2184
        return "Bazaar Branch Format 8 (needs bzr 1.15)\n"
2168
2185
 
2170
2187
        """See BranchFormat.get_format_description()."""
2171
2188
        return "Branch format 8"
2172
2189
 
2173
 
    def initialize(self, a_bzrdir, name=None):
 
2190
    def initialize(self, a_bzrdir, name=None, repository=None,
 
2191
                   append_revisions_only=None):
2174
2192
        """Create a branch of this format in a_bzrdir."""
2175
2193
        utf8_files = [('last-revision', '0 null:\n'),
2176
 
                      ('branch.conf', ''),
 
2194
                      ('branch.conf',
 
2195
                          self._get_initial_config(append_revisions_only)),
2177
2196
                      ('tags', ''),
2178
2197
                      ('references', '')
2179
2198
                      ]
2180
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
2181
 
 
2182
 
    def __init__(self):
2183
 
        super(BzrBranchFormat8, self).__init__()
2184
 
        self._matchingbzrdir.repository_format = \
2185
 
            RepositoryFormatKnitPack5RichRoot()
 
2199
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2186
2200
 
2187
2201
    def make_tags(self, branch):
2188
2202
        """See bzrlib.branch.BranchFormat.make_tags()."""
2189
 
        return BasicTags(branch)
 
2203
        return _mod_tag.BasicTags(branch)
2190
2204
 
2191
2205
    def supports_set_append_revisions_only(self):
2192
2206
        return True
2197
2211
    supports_reference_locations = True
2198
2212
 
2199
2213
 
2200
 
class BzrBranchFormat7(BzrBranchFormat8):
 
2214
class BzrBranchFormat7(BranchFormatMetadir):
2201
2215
    """Branch format with last-revision, tags, and a stacked location pointer.
2202
2216
 
2203
2217
    The stacked location pointer is passed down to the repository and requires
2206
2220
    This format was introduced in bzr 1.6.
2207
2221
    """
2208
2222
 
2209
 
    def initialize(self, a_bzrdir, name=None):
 
2223
    def initialize(self, a_bzrdir, name=None, repository=None,
 
2224
                   append_revisions_only=None):
2210
2225
        """Create a branch of this format in a_bzrdir."""
2211
2226
        utf8_files = [('last-revision', '0 null:\n'),
2212
 
                      ('branch.conf', ''),
 
2227
                      ('branch.conf',
 
2228
                          self._get_initial_config(append_revisions_only)),
2213
2229
                      ('tags', ''),
2214
2230
                      ]
2215
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2231
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2216
2232
 
2217
2233
    def _branch_class(self):
2218
2234
        return BzrBranch7
2219
2235
 
2220
 
    def get_format_string(self):
 
2236
    @classmethod
 
2237
    def get_format_string(cls):
2221
2238
        """See BranchFormat.get_format_string()."""
2222
2239
        return "Bazaar Branch Format 7 (needs bzr 1.6)\n"
2223
2240
 
2228
2245
    def supports_set_append_revisions_only(self):
2229
2246
        return True
2230
2247
 
 
2248
    def supports_stacking(self):
 
2249
        return True
 
2250
 
 
2251
    def make_tags(self, branch):
 
2252
        """See bzrlib.branch.BranchFormat.make_tags()."""
 
2253
        return _mod_tag.BasicTags(branch)
 
2254
 
2231
2255
    supports_reference_locations = False
2232
2256
 
2233
2257
 
2234
 
class BranchReferenceFormat(BranchFormat):
 
2258
class BranchReferenceFormat(BranchFormatMetadir):
2235
2259
    """Bzr branch reference format.
2236
2260
 
2237
2261
    Branch references are used in implementing checkouts, they
2242
2266
     - a format string
2243
2267
    """
2244
2268
 
2245
 
    def get_format_string(self):
 
2269
    @classmethod
 
2270
    def get_format_string(cls):
2246
2271
        """See BranchFormat.get_format_string()."""
2247
2272
        return "Bazaar-NG Branch Reference Format 1\n"
2248
2273
 
2260
2285
        transport = a_bzrdir.get_branch_transport(None, name=name)
2261
2286
        location = transport.put_bytes('location', to_branch.base)
2262
2287
 
2263
 
    def initialize(self, a_bzrdir, name=None, target_branch=None):
 
2288
    def initialize(self, a_bzrdir, name=None, target_branch=None,
 
2289
            repository=None, append_revisions_only=None):
2264
2290
        """Create a branch of this format in a_bzrdir."""
2265
2291
        if target_branch is None:
2266
2292
            # this format does not implement branch itself, thus the implicit
2267
2293
            # creation contract must see it as uninitializable
2268
2294
            raise errors.UninitializableFormat(self)
2269
2295
        mutter('creating branch reference in %s', a_bzrdir.user_url)
 
2296
        if a_bzrdir._format.fixed_components:
 
2297
            raise errors.IncompatibleFormat(self, a_bzrdir._format)
2270
2298
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
2271
2299
        branch_transport.put_bytes('location',
2272
 
            target_branch.bzrdir.user_url)
 
2300
            target_branch.user_url)
2273
2301
        branch_transport.put_bytes('format', self.get_format_string())
2274
2302
        branch = self.open(
2275
2303
            a_bzrdir, name, _found=True,
2277
2305
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2278
2306
        return branch
2279
2307
 
2280
 
    def __init__(self):
2281
 
        super(BranchReferenceFormat, self).__init__()
2282
 
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
2283
 
        self._matchingbzrdir.set_branch_format(self)
2284
 
 
2285
2308
    def _make_reference_clone_function(format, a_branch):
2286
2309
        """Create a clone() routine for a branch dynamically."""
2287
2310
        def clone(to_bzrdir, revision_id=None,
2294
2317
        return clone
2295
2318
 
2296
2319
    def open(self, a_bzrdir, name=None, _found=False, location=None,
2297
 
             possible_transports=None, ignore_fallbacks=False):
 
2320
             possible_transports=None, ignore_fallbacks=False,
 
2321
             found_repository=None):
2298
2322
        """Return the branch that the branch reference in a_bzrdir points at.
2299
2323
 
2300
2324
        :param a_bzrdir: A BzrDir that contains a branch.
2309
2333
        :param possible_transports: An optional reusable transports list.
2310
2334
        """
2311
2335
        if not _found:
2312
 
            format = BranchFormat.find_format(a_bzrdir, name=name)
 
2336
            format = BranchFormatMetadir.find_format(a_bzrdir, name=name)
2313
2337
            if format.__class__ != self.__class__:
2314
2338
                raise AssertionError("wrong format %r found for %r" %
2315
2339
                    (format, self))
2316
2340
        if location is None:
2317
2341
            location = self.get_reference(a_bzrdir, name)
2318
 
        real_bzrdir = bzrdir.BzrDir.open(
 
2342
        real_bzrdir = controldir.ControlDir.open(
2319
2343
            location, possible_transports=possible_transports)
2320
2344
        result = real_bzrdir.open_branch(name=name, 
2321
 
            ignore_fallbacks=ignore_fallbacks)
 
2345
            ignore_fallbacks=ignore_fallbacks,
 
2346
            possible_transports=possible_transports)
2322
2347
        # this changes the behaviour of result.clone to create a new reference
2323
2348
        # rather than a copy of the content of the branch.
2324
2349
        # I did not use a proxy object because that needs much more extensive
2331
2356
        return result
2332
2357
 
2333
2358
 
 
2359
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
 
2360
    """Branch format registry."""
 
2361
 
 
2362
    def __init__(self, other_registry=None):
 
2363
        super(BranchFormatRegistry, self).__init__(other_registry)
 
2364
        self._default_format = None
 
2365
 
 
2366
    def set_default(self, format):
 
2367
        self._default_format = format
 
2368
 
 
2369
    def get_default(self):
 
2370
        return self._default_format
 
2371
 
 
2372
 
2334
2373
network_format_registry = registry.FormatRegistry()
2335
2374
"""Registry of formats indexed by their network name.
2336
2375
 
2339
2378
BranchFormat.network_name() for more detail.
2340
2379
"""
2341
2380
 
 
2381
format_registry = BranchFormatRegistry(network_format_registry)
 
2382
 
2342
2383
 
2343
2384
# formats which have no format string are not discoverable
2344
2385
# and not independently creatable, so are not registered.
2346
2387
__format6 = BzrBranchFormat6()
2347
2388
__format7 = BzrBranchFormat7()
2348
2389
__format8 = BzrBranchFormat8()
2349
 
BranchFormat.register_format(__format5)
2350
 
BranchFormat.register_format(BranchReferenceFormat())
2351
 
BranchFormat.register_format(__format6)
2352
 
BranchFormat.register_format(__format7)
2353
 
BranchFormat.register_format(__format8)
2354
 
BranchFormat.set_default_format(__format7)
2355
 
_legacy_formats = [BzrBranchFormat4(),
2356
 
    ]
2357
 
network_format_registry.register(
2358
 
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
 
2390
format_registry.register(__format5)
 
2391
format_registry.register(BranchReferenceFormat())
 
2392
format_registry.register(__format6)
 
2393
format_registry.register(__format7)
 
2394
format_registry.register(__format8)
 
2395
format_registry.set_default(__format7)
2359
2396
 
2360
2397
 
2361
2398
class BranchWriteLockResult(LogicalLockResult):
2393
2430
 
2394
2431
    def __init__(self, _format=None,
2395
2432
                 _control_files=None, a_bzrdir=None, name=None,
2396
 
                 _repository=None, ignore_fallbacks=False):
 
2433
                 _repository=None, ignore_fallbacks=False,
 
2434
                 possible_transports=None):
2397
2435
        """Create new branch object at a particular location."""
2398
2436
        if a_bzrdir is None:
2399
2437
            raise ValueError('a_bzrdir must be supplied')
2400
2438
        else:
2401
2439
            self.bzrdir = a_bzrdir
2402
 
        self._base = self.bzrdir.transport.clone('..').base
 
2440
        self._user_transport = self.bzrdir.transport.clone('..')
 
2441
        if name is not None:
 
2442
            self._user_transport.set_segment_parameter(
 
2443
                "branch", urlutils.escape(name))
 
2444
        self._base = self._user_transport.base
2403
2445
        self.name = name
2404
 
        # XXX: We should be able to just do
2405
 
        #   self.base = self.bzrdir.root_transport.base
2406
 
        # but this does not quite work yet -- mbp 20080522
2407
2446
        self._format = _format
2408
2447
        if _control_files is None:
2409
2448
            raise ValueError('BzrBranch _control_files is None')
2410
2449
        self.control_files = _control_files
2411
2450
        self._transport = _control_files._transport
2412
2451
        self.repository = _repository
2413
 
        Branch.__init__(self)
 
2452
        Branch.__init__(self, possible_transports)
2414
2453
 
2415
2454
    def __str__(self):
2416
 
        if self.name is None:
2417
 
            return '%s(%s)' % (self.__class__.__name__, self.user_url)
2418
 
        else:
2419
 
            return '%s(%s,%s)' % (self.__class__.__name__, self.user_url,
2420
 
                self.name)
 
2455
        return '%s(%s)' % (self.__class__.__name__, self.user_url)
2421
2456
 
2422
2457
    __repr__ = __str__
2423
2458
 
2427
2462
 
2428
2463
    base = property(_get_base, doc="The URL for the root of this branch.")
2429
2464
 
 
2465
    @property
 
2466
    def user_transport(self):
 
2467
        return self._user_transport
 
2468
 
2430
2469
    def _get_config(self):
2431
 
        return TransportConfig(self._transport, 'branch.conf')
 
2470
        return _mod_config.TransportConfig(self._transport, 'branch.conf')
 
2471
 
 
2472
    def _get_config_store(self):
 
2473
        return _mod_config.BranchStore(self)
2432
2474
 
2433
2475
    def is_locked(self):
2434
2476
        return self.control_files.is_locked()
2509
2551
        """See Branch.print_file."""
2510
2552
        return self.repository.print_file(file, revision_id)
2511
2553
 
2512
 
    def _write_revision_history(self, history):
2513
 
        """Factored out of set_revision_history.
2514
 
 
2515
 
        This performs the actual writing to disk.
2516
 
        It is intended to be called by BzrBranch5.set_revision_history."""
2517
 
        self._transport.put_bytes(
2518
 
            'revision-history', '\n'.join(history),
2519
 
            mode=self.bzrdir._get_file_mode())
2520
 
 
2521
 
    @needs_write_lock
2522
 
    def set_revision_history(self, rev_history):
2523
 
        """See Branch.set_revision_history."""
2524
 
        if 'evil' in debug.debug_flags:
2525
 
            mutter_callsite(3, "set_revision_history scales with history.")
2526
 
        check_not_reserved_id = _mod_revision.check_not_reserved_id
2527
 
        for rev_id in rev_history:
2528
 
            check_not_reserved_id(rev_id)
2529
 
        if Branch.hooks['post_change_branch_tip']:
2530
 
            # Don't calculate the last_revision_info() if there are no hooks
2531
 
            # that will use it.
2532
 
            old_revno, old_revid = self.last_revision_info()
2533
 
        if len(rev_history) == 0:
2534
 
            revid = _mod_revision.NULL_REVISION
2535
 
        else:
2536
 
            revid = rev_history[-1]
2537
 
        self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
2538
 
        self._write_revision_history(rev_history)
2539
 
        self._clear_cached_state()
2540
 
        self._cache_revision_history(rev_history)
2541
 
        for hook in Branch.hooks['set_rh']:
2542
 
            hook(self, rev_history)
2543
 
        if Branch.hooks['post_change_branch_tip']:
2544
 
            self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2545
 
 
2546
 
    def _synchronize_history(self, destination, revision_id):
2547
 
        """Synchronize last revision and revision history between branches.
2548
 
 
2549
 
        This version is most efficient when the destination is also a
2550
 
        BzrBranch5, but works for BzrBranch6 as long as the revision
2551
 
        history is the true lefthand parent history, and all of the revisions
2552
 
        are in the destination's repository.  If not, set_revision_history
2553
 
        will fail.
2554
 
 
2555
 
        :param destination: The branch to copy the history into
2556
 
        :param revision_id: The revision-id to truncate history at.  May
2557
 
          be None to copy complete history.
2558
 
        """
2559
 
        if not isinstance(destination._format, BzrBranchFormat5):
2560
 
            super(BzrBranch, self)._synchronize_history(
2561
 
                destination, revision_id)
2562
 
            return
2563
 
        if revision_id == _mod_revision.NULL_REVISION:
2564
 
            new_history = []
2565
 
        else:
2566
 
            new_history = self.revision_history()
2567
 
        if revision_id is not None and new_history != []:
2568
 
            try:
2569
 
                new_history = new_history[:new_history.index(revision_id) + 1]
2570
 
            except ValueError:
2571
 
                rev = self.repository.get_revision(revision_id)
2572
 
                new_history = rev.get_history(self.repository)[1:]
2573
 
        destination.set_revision_history(new_history)
2574
 
 
2575
2554
    @needs_write_lock
2576
2555
    def set_last_revision_info(self, revno, revision_id):
2577
 
        """Set the last revision of this branch.
2578
 
 
2579
 
        The caller is responsible for checking that the revno is correct
2580
 
        for this revision id.
2581
 
 
2582
 
        It may be possible to set the branch last revision to an id not
2583
 
        present in the repository.  However, branches can also be
2584
 
        configured to check constraints on history, in which case this may not
2585
 
        be permitted.
2586
 
        """
 
2556
        if not revision_id or not isinstance(revision_id, basestring):
 
2557
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2587
2558
        revision_id = _mod_revision.ensure_null(revision_id)
2588
 
        # this old format stores the full history, but this api doesn't
2589
 
        # provide it, so we must generate, and might as well check it's
2590
 
        # correct
2591
 
        history = self._lefthand_history(revision_id)
2592
 
        if len(history) != revno:
2593
 
            raise AssertionError('%d != %d' % (len(history), revno))
2594
 
        self.set_revision_history(history)
2595
 
 
2596
 
    def _gen_revision_history(self):
2597
 
        history = self._transport.get_bytes('revision-history').split('\n')
2598
 
        if history[-1:] == ['']:
2599
 
            # There shouldn't be a trailing newline, but just in case.
2600
 
            history.pop()
2601
 
        return history
2602
 
 
2603
 
    @needs_write_lock
2604
 
    def generate_revision_history(self, revision_id, last_rev=None,
2605
 
        other_branch=None):
2606
 
        """Create a new revision history that will finish with revision_id.
2607
 
 
2608
 
        :param revision_id: the new tip to use.
2609
 
        :param last_rev: The previous last_revision. If not None, then this
2610
 
            must be a ancestory of revision_id, or DivergedBranches is raised.
2611
 
        :param other_branch: The other branch that DivergedBranches should
2612
 
            raise with respect to.
2613
 
        """
2614
 
        self.set_revision_history(self._lefthand_history(revision_id,
2615
 
            last_rev, other_branch))
 
2559
        old_revno, old_revid = self.last_revision_info()
 
2560
        if self.get_append_revisions_only():
 
2561
            self._check_history_violation(revision_id)
 
2562
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
 
2563
        self._write_last_revision_info(revno, revision_id)
 
2564
        self._clear_cached_state()
 
2565
        self._last_revision_info_cache = revno, revision_id
 
2566
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2616
2567
 
2617
2568
    def basis_tree(self):
2618
2569
        """See Branch.basis_tree."""
2627
2578
                pass
2628
2579
        return None
2629
2580
 
2630
 
    def _basic_push(self, target, overwrite, stop_revision):
2631
 
        """Basic implementation of push without bound branches or hooks.
2632
 
 
2633
 
        Must be called with source read locked and target write locked.
2634
 
        """
2635
 
        result = BranchPushResult()
2636
 
        result.source_branch = self
2637
 
        result.target_branch = target
2638
 
        result.old_revno, result.old_revid = target.last_revision_info()
2639
 
        self.update_references(target)
2640
 
        if result.old_revid != self.last_revision():
2641
 
            # We assume that during 'push' this repository is closer than
2642
 
            # the target.
2643
 
            graph = self.repository.get_graph(target.repository)
2644
 
            target.update_revisions(self, stop_revision,
2645
 
                overwrite=overwrite, graph=graph)
2646
 
        if self._push_should_merge_tags():
2647
 
            result.tag_conflicts = self.tags.merge_to(target.tags,
2648
 
                overwrite)
2649
 
        result.new_revno, result.new_revid = target.last_revision_info()
2650
 
        return result
2651
 
 
2652
2581
    def get_stacked_on_url(self):
2653
2582
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
2654
2583
 
2665
2594
            self._transport.put_bytes('parent', url + '\n',
2666
2595
                mode=self.bzrdir._get_file_mode())
2667
2596
 
2668
 
 
2669
 
class BzrBranch5(BzrBranch):
2670
 
    """A format 5 branch. This supports new features over plain branches.
2671
 
 
2672
 
    It has support for a master_branch which is the data for bound branches.
2673
 
    """
2674
 
 
2675
 
    def get_bound_location(self):
2676
 
        try:
2677
 
            return self._transport.get_bytes('bound')[:-1]
2678
 
        except errors.NoSuchFile:
2679
 
            return None
2680
 
 
2681
 
    @needs_read_lock
2682
 
    def get_master_branch(self, possible_transports=None):
2683
 
        """Return the branch we are bound to.
2684
 
 
2685
 
        :return: Either a Branch, or None
2686
 
 
2687
 
        This could memoise the branch, but if thats done
2688
 
        it must be revalidated on each new lock.
2689
 
        So for now we just don't memoise it.
2690
 
        # RBC 20060304 review this decision.
2691
 
        """
2692
 
        bound_loc = self.get_bound_location()
2693
 
        if not bound_loc:
2694
 
            return None
2695
 
        try:
2696
 
            return Branch.open(bound_loc,
2697
 
                               possible_transports=possible_transports)
2698
 
        except (errors.NotBranchError, errors.ConnectionError), e:
2699
 
            raise errors.BoundBranchConnectionFailure(
2700
 
                    self, bound_loc, e)
2701
 
 
2702
2597
    @needs_write_lock
2703
 
    def set_bound_location(self, location):
2704
 
        """Set the target where this branch is bound to.
2705
 
 
2706
 
        :param location: URL to the target branch
2707
 
        """
2708
 
        if location:
2709
 
            self._transport.put_bytes('bound', location+'\n',
2710
 
                mode=self.bzrdir._get_file_mode())
2711
 
        else:
2712
 
            try:
2713
 
                self._transport.delete('bound')
2714
 
            except errors.NoSuchFile:
2715
 
                return False
2716
 
            return True
 
2598
    def unbind(self):
 
2599
        """If bound, unbind"""
 
2600
        return self.set_bound_location(None)
2717
2601
 
2718
2602
    @needs_write_lock
2719
2603
    def bind(self, other):
2741
2625
        # history around
2742
2626
        self.set_bound_location(other.base)
2743
2627
 
 
2628
    def get_bound_location(self):
 
2629
        try:
 
2630
            return self._transport.get_bytes('bound')[:-1]
 
2631
        except errors.NoSuchFile:
 
2632
            return None
 
2633
 
 
2634
    @needs_read_lock
 
2635
    def get_master_branch(self, possible_transports=None):
 
2636
        """Return the branch we are bound to.
 
2637
 
 
2638
        :return: Either a Branch, or None
 
2639
        """
 
2640
        if self._master_branch_cache is None:
 
2641
            self._master_branch_cache = self._get_master_branch(
 
2642
                possible_transports)
 
2643
        return self._master_branch_cache
 
2644
 
 
2645
    def _get_master_branch(self, possible_transports):
 
2646
        bound_loc = self.get_bound_location()
 
2647
        if not bound_loc:
 
2648
            return None
 
2649
        try:
 
2650
            return Branch.open(bound_loc,
 
2651
                               possible_transports=possible_transports)
 
2652
        except (errors.NotBranchError, errors.ConnectionError), e:
 
2653
            raise errors.BoundBranchConnectionFailure(
 
2654
                    self, bound_loc, e)
 
2655
 
2744
2656
    @needs_write_lock
2745
 
    def unbind(self):
2746
 
        """If bound, unbind"""
2747
 
        return self.set_bound_location(None)
 
2657
    def set_bound_location(self, location):
 
2658
        """Set the target where this branch is bound to.
 
2659
 
 
2660
        :param location: URL to the target branch
 
2661
        """
 
2662
        self._master_branch_cache = None
 
2663
        if location:
 
2664
            self._transport.put_bytes('bound', location+'\n',
 
2665
                mode=self.bzrdir._get_file_mode())
 
2666
        else:
 
2667
            try:
 
2668
                self._transport.delete('bound')
 
2669
            except errors.NoSuchFile:
 
2670
                return False
 
2671
            return True
2748
2672
 
2749
2673
    @needs_write_lock
2750
2674
    def update(self, possible_transports=None):
2763
2687
            return old_tip
2764
2688
        return None
2765
2689
 
2766
 
 
2767
 
class BzrBranch8(BzrBranch5):
 
2690
    def _read_last_revision_info(self):
 
2691
        revision_string = self._transport.get_bytes('last-revision')
 
2692
        revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
 
2693
        revision_id = cache_utf8.get_cached_utf8(revision_id)
 
2694
        revno = int(revno)
 
2695
        return revno, revision_id
 
2696
 
 
2697
    def _write_last_revision_info(self, revno, revision_id):
 
2698
        """Simply write out the revision id, with no checks.
 
2699
 
 
2700
        Use set_last_revision_info to perform this safely.
 
2701
 
 
2702
        Does not update the revision_history cache.
 
2703
        """
 
2704
        revision_id = _mod_revision.ensure_null(revision_id)
 
2705
        out_string = '%d %s\n' % (revno, revision_id)
 
2706
        self._transport.put_bytes('last-revision', out_string,
 
2707
            mode=self.bzrdir._get_file_mode())
 
2708
 
 
2709
 
 
2710
class FullHistoryBzrBranch(BzrBranch):
 
2711
    """Bzr branch which contains the full revision history."""
 
2712
 
 
2713
    @needs_write_lock
 
2714
    def set_last_revision_info(self, revno, revision_id):
 
2715
        if not revision_id or not isinstance(revision_id, basestring):
 
2716
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
 
2717
        revision_id = _mod_revision.ensure_null(revision_id)
 
2718
        # this old format stores the full history, but this api doesn't
 
2719
        # provide it, so we must generate, and might as well check it's
 
2720
        # correct
 
2721
        history = self._lefthand_history(revision_id)
 
2722
        if len(history) != revno:
 
2723
            raise AssertionError('%d != %d' % (len(history), revno))
 
2724
        self._set_revision_history(history)
 
2725
 
 
2726
    def _read_last_revision_info(self):
 
2727
        rh = self._revision_history()
 
2728
        revno = len(rh)
 
2729
        if revno:
 
2730
            return (revno, rh[-1])
 
2731
        else:
 
2732
            return (0, _mod_revision.NULL_REVISION)
 
2733
 
 
2734
    @deprecated_method(deprecated_in((2, 4, 0)))
 
2735
    @needs_write_lock
 
2736
    def set_revision_history(self, rev_history):
 
2737
        """See Branch.set_revision_history."""
 
2738
        self._set_revision_history(rev_history)
 
2739
 
 
2740
    def _set_revision_history(self, rev_history):
 
2741
        if 'evil' in debug.debug_flags:
 
2742
            mutter_callsite(3, "set_revision_history scales with history.")
 
2743
        check_not_reserved_id = _mod_revision.check_not_reserved_id
 
2744
        for rev_id in rev_history:
 
2745
            check_not_reserved_id(rev_id)
 
2746
        if Branch.hooks['post_change_branch_tip']:
 
2747
            # Don't calculate the last_revision_info() if there are no hooks
 
2748
            # that will use it.
 
2749
            old_revno, old_revid = self.last_revision_info()
 
2750
        if len(rev_history) == 0:
 
2751
            revid = _mod_revision.NULL_REVISION
 
2752
        else:
 
2753
            revid = rev_history[-1]
 
2754
        self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
 
2755
        self._write_revision_history(rev_history)
 
2756
        self._clear_cached_state()
 
2757
        self._cache_revision_history(rev_history)
 
2758
        for hook in Branch.hooks['set_rh']:
 
2759
            hook(self, rev_history)
 
2760
        if Branch.hooks['post_change_branch_tip']:
 
2761
            self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2762
 
 
2763
    def _write_revision_history(self, history):
 
2764
        """Factored out of set_revision_history.
 
2765
 
 
2766
        This performs the actual writing to disk.
 
2767
        It is intended to be called by set_revision_history."""
 
2768
        self._transport.put_bytes(
 
2769
            'revision-history', '\n'.join(history),
 
2770
            mode=self.bzrdir._get_file_mode())
 
2771
 
 
2772
    def _gen_revision_history(self):
 
2773
        history = self._transport.get_bytes('revision-history').split('\n')
 
2774
        if history[-1:] == ['']:
 
2775
            # There shouldn't be a trailing newline, but just in case.
 
2776
            history.pop()
 
2777
        return history
 
2778
 
 
2779
    def _synchronize_history(self, destination, revision_id):
 
2780
        if not isinstance(destination, FullHistoryBzrBranch):
 
2781
            super(BzrBranch, self)._synchronize_history(
 
2782
                destination, revision_id)
 
2783
            return
 
2784
        if revision_id == _mod_revision.NULL_REVISION:
 
2785
            new_history = []
 
2786
        else:
 
2787
            new_history = self._revision_history()
 
2788
        if revision_id is not None and new_history != []:
 
2789
            try:
 
2790
                new_history = new_history[:new_history.index(revision_id) + 1]
 
2791
            except ValueError:
 
2792
                rev = self.repository.get_revision(revision_id)
 
2793
                new_history = rev.get_history(self.repository)[1:]
 
2794
        destination._set_revision_history(new_history)
 
2795
 
 
2796
    @needs_write_lock
 
2797
    def generate_revision_history(self, revision_id, last_rev=None,
 
2798
        other_branch=None):
 
2799
        """Create a new revision history that will finish with revision_id.
 
2800
 
 
2801
        :param revision_id: the new tip to use.
 
2802
        :param last_rev: The previous last_revision. If not None, then this
 
2803
            must be a ancestory of revision_id, or DivergedBranches is raised.
 
2804
        :param other_branch: The other branch that DivergedBranches should
 
2805
            raise with respect to.
 
2806
        """
 
2807
        self._set_revision_history(self._lefthand_history(revision_id,
 
2808
            last_rev, other_branch))
 
2809
 
 
2810
 
 
2811
class BzrBranch5(FullHistoryBzrBranch):
 
2812
    """A format 5 branch. This supports new features over plain branches.
 
2813
 
 
2814
    It has support for a master_branch which is the data for bound branches.
 
2815
    """
 
2816
 
 
2817
 
 
2818
class BzrBranch8(BzrBranch):
2768
2819
    """A branch that stores tree-reference locations."""
2769
2820
 
2770
 
    def _open_hook(self):
 
2821
    def _open_hook(self, possible_transports=None):
2771
2822
        if self._ignore_fallbacks:
2772
2823
            return
 
2824
        if possible_transports is None:
 
2825
            possible_transports = [self.bzrdir.root_transport]
2773
2826
        try:
2774
2827
            url = self.get_stacked_on_url()
2775
2828
        except (errors.UnstackableRepositoryFormat, errors.NotStacked,
2783
2836
                    raise AssertionError(
2784
2837
                        "'transform_fallback_location' hook %s returned "
2785
2838
                        "None, not a URL." % hook_name)
2786
 
            self._activate_fallback_location(url)
 
2839
            self._activate_fallback_location(url,
 
2840
                possible_transports=possible_transports)
2787
2841
 
2788
2842
    def __init__(self, *args, **kwargs):
2789
2843
        self._ignore_fallbacks = kwargs.get('ignore_fallbacks', False)
2796
2850
        self._last_revision_info_cache = None
2797
2851
        self._reference_info = None
2798
2852
 
2799
 
    def _last_revision_info(self):
2800
 
        revision_string = self._transport.get_bytes('last-revision')
2801
 
        revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
2802
 
        revision_id = cache_utf8.get_cached_utf8(revision_id)
2803
 
        revno = int(revno)
2804
 
        return revno, revision_id
2805
 
 
2806
 
    def _write_last_revision_info(self, revno, revision_id):
2807
 
        """Simply write out the revision id, with no checks.
2808
 
 
2809
 
        Use set_last_revision_info to perform this safely.
2810
 
 
2811
 
        Does not update the revision_history cache.
2812
 
        Intended to be called by set_last_revision_info and
2813
 
        _write_revision_history.
2814
 
        """
2815
 
        revision_id = _mod_revision.ensure_null(revision_id)
2816
 
        out_string = '%d %s\n' % (revno, revision_id)
2817
 
        self._transport.put_bytes('last-revision', out_string,
2818
 
            mode=self.bzrdir._get_file_mode())
2819
 
 
2820
 
    @needs_write_lock
2821
 
    def set_last_revision_info(self, revno, revision_id):
2822
 
        revision_id = _mod_revision.ensure_null(revision_id)
2823
 
        old_revno, old_revid = self.last_revision_info()
2824
 
        if self._get_append_revisions_only():
2825
 
            self._check_history_violation(revision_id)
2826
 
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
2827
 
        self._write_last_revision_info(revno, revision_id)
2828
 
        self._clear_cached_state()
2829
 
        self._last_revision_info_cache = revno, revision_id
2830
 
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2831
 
 
2832
 
    def _synchronize_history(self, destination, revision_id):
2833
 
        """Synchronize last revision and revision history between branches.
2834
 
 
2835
 
        :see: Branch._synchronize_history
2836
 
        """
2837
 
        # XXX: The base Branch has a fast implementation of this method based
2838
 
        # on set_last_revision_info, but BzrBranch/BzrBranch5 have a slower one
2839
 
        # that uses set_revision_history.  This class inherits from BzrBranch5,
2840
 
        # but wants the fast implementation, so it calls
2841
 
        # Branch._synchronize_history directly.
2842
 
        Branch._synchronize_history(self, destination, revision_id)
2843
 
 
2844
2853
    def _check_history_violation(self, revision_id):
2845
 
        last_revision = _mod_revision.ensure_null(self.last_revision())
 
2854
        current_revid = self.last_revision()
 
2855
        last_revision = _mod_revision.ensure_null(current_revid)
2846
2856
        if _mod_revision.is_null(last_revision):
2847
2857
            return
2848
 
        if last_revision not in self._lefthand_history(revision_id):
2849
 
            raise errors.AppendRevisionsOnlyViolation(self.user_url)
 
2858
        graph = self.repository.get_graph()
 
2859
        for lh_ancestor in graph.iter_lefthand_ancestry(revision_id):
 
2860
            if lh_ancestor == current_revid:
 
2861
                return
 
2862
        raise errors.AppendRevisionsOnlyViolation(self.user_url)
2850
2863
 
2851
2864
    def _gen_revision_history(self):
2852
2865
        """Generate the revision history from last revision
2855
2868
        self._extend_partial_history(stop_index=last_revno-1)
2856
2869
        return list(reversed(self._partial_revision_history_cache))
2857
2870
 
2858
 
    def _write_revision_history(self, history):
2859
 
        """Factored out of set_revision_history.
2860
 
 
2861
 
        This performs the actual writing to disk, with format-specific checks.
2862
 
        It is intended to be called by BzrBranch5.set_revision_history.
2863
 
        """
2864
 
        if len(history) == 0:
2865
 
            last_revision = 'null:'
2866
 
        else:
2867
 
            if history != self._lefthand_history(history[-1]):
2868
 
                raise errors.NotLefthandHistory(history)
2869
 
            last_revision = history[-1]
2870
 
        if self._get_append_revisions_only():
2871
 
            self._check_history_violation(last_revision)
2872
 
        self._write_last_revision_info(len(history), last_revision)
2873
 
 
2874
2871
    @needs_write_lock
2875
2872
    def _set_parent_location(self, url):
2876
2873
        """Set the parent branch"""
2962
2959
 
2963
2960
    def set_bound_location(self, location):
2964
2961
        """See Branch.set_push_location."""
 
2962
        self._master_branch_cache = None
2965
2963
        result = None
2966
2964
        config = self.get_config()
2967
2965
        if location is None:
2998
2996
        # you can always ask for the URL; but you might not be able to use it
2999
2997
        # if the repo can't support stacking.
3000
2998
        ## self._check_stackable_repo()
3001
 
        stacked_url = self._get_config_location('stacked_on_location')
 
2999
        # stacked_on_location is only ever defined in branch.conf, so don't
 
3000
        # waste effort reading the whole stack of config files.
 
3001
        config = self.get_config()._get_branch_data_config()
 
3002
        stacked_url = self._get_config_location('stacked_on_location',
 
3003
            config=config)
3002
3004
        if stacked_url is None:
3003
3005
            raise errors.NotStacked(self)
3004
3006
        return stacked_url
3005
3007
 
3006
 
    def _get_append_revisions_only(self):
3007
 
        return self.get_config(
3008
 
            ).get_user_option_as_bool('append_revisions_only')
3009
 
 
3010
 
    @needs_write_lock
3011
 
    def generate_revision_history(self, revision_id, last_rev=None,
3012
 
                                  other_branch=None):
3013
 
        """See BzrBranch5.generate_revision_history"""
3014
 
        history = self._lefthand_history(revision_id, last_rev, other_branch)
3015
 
        revno = len(history)
3016
 
        self.set_last_revision_info(revno, revision_id)
3017
 
 
3018
3008
    @needs_read_lock
3019
3009
    def get_rev_id(self, revno, history=None):
3020
3010
        """Find the revision id of the specified revno."""
3044
3034
        try:
3045
3035
            index = self._partial_revision_history_cache.index(revision_id)
3046
3036
        except ValueError:
3047
 
            self._extend_partial_history(stop_revision=revision_id)
 
3037
            try:
 
3038
                self._extend_partial_history(stop_revision=revision_id)
 
3039
            except errors.RevisionNotPresent, e:
 
3040
                raise errors.GhostRevisionsHaveNoRevno(revision_id, e.revision_id)
3048
3041
            index = len(self._partial_revision_history_cache) - 1
 
3042
            if index < 0:
 
3043
                raise errors.NoSuchRevision(self, revision_id)
3049
3044
            if self._partial_revision_history_cache[index] != revision_id:
3050
3045
                raise errors.NoSuchRevision(self, revision_id)
3051
3046
        return self.revno() - index
3103
3098
    :ivar local_branch: target branch if there is a Master, else None
3104
3099
    :ivar target_branch: Target/destination branch object. (write locked)
3105
3100
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
 
3101
    :ivar tag_updates: A dict with new tags, see BasicTags.merge_to
3106
3102
    """
3107
3103
 
3108
3104
    @deprecated_method(deprecated_in((2, 3, 0)))
3114
3110
        return self.new_revno - self.old_revno
3115
3111
 
3116
3112
    def report(self, to_file):
 
3113
        tag_conflicts = getattr(self, "tag_conflicts", None)
 
3114
        tag_updates = getattr(self, "tag_updates", None)
3117
3115
        if not is_quiet():
3118
 
            if self.old_revid == self.new_revid:
3119
 
                to_file.write('No revisions to pull.\n')
3120
 
            else:
 
3116
            if self.old_revid != self.new_revid:
3121
3117
                to_file.write('Now on revision %d.\n' % self.new_revno)
 
3118
            if tag_updates:
 
3119
                to_file.write('%d tag(s) updated.\n' % len(tag_updates))
 
3120
            if self.old_revid == self.new_revid and not tag_updates:
 
3121
                if not tag_conflicts:
 
3122
                    to_file.write('No revisions or tags to pull.\n')
 
3123
                else:
 
3124
                    to_file.write('No revisions to pull.\n')
3122
3125
        self._show_tag_conficts(to_file)
3123
3126
 
3124
3127
 
3150
3153
        return self.new_revno - self.old_revno
3151
3154
 
3152
3155
    def report(self, to_file):
3153
 
        """Write a human-readable description of the result."""
3154
 
        if self.old_revid == self.new_revid:
3155
 
            note('No new revisions to push.')
3156
 
        else:
3157
 
            note('Pushed up to revision %d.' % self.new_revno)
 
3156
        # TODO: This function gets passed a to_file, but then
 
3157
        # ignores it and calls note() instead. This is also
 
3158
        # inconsistent with PullResult(), which writes to stdout.
 
3159
        # -- JRV20110901, bug #838853
 
3160
        tag_conflicts = getattr(self, "tag_conflicts", None)
 
3161
        tag_updates = getattr(self, "tag_updates", None)
 
3162
        if not is_quiet():
 
3163
            if self.old_revid != self.new_revid:
 
3164
                note(gettext('Pushed up to revision %d.') % self.new_revno)
 
3165
            if tag_updates:
 
3166
                note(ngettext('%d tag updated.', '%d tags updated.', len(tag_updates)) % len(tag_updates))
 
3167
            if self.old_revid == self.new_revid and not tag_updates:
 
3168
                if not tag_conflicts:
 
3169
                    note(gettext('No new revisions or tags to push.'))
 
3170
                else:
 
3171
                    note(gettext('No new revisions to push.'))
3158
3172
        self._show_tag_conficts(to_file)
3159
3173
 
3160
3174
 
3174
3188
        :param verbose: Requests more detailed display of what was checked,
3175
3189
            if any.
3176
3190
        """
3177
 
        note('checked branch %s format %s', self.branch.user_url,
3178
 
            self.branch._format)
 
3191
        note(gettext('checked branch {0} format {1}').format(
 
3192
                                self.branch.user_url, self.branch._format))
3179
3193
        for error in self.errors:
3180
 
            note('found error:%s', error)
 
3194
            note(gettext('found error:%s'), error)
3181
3195
 
3182
3196
 
3183
3197
class Converter5to6(object):
3222
3236
 
3223
3237
 
3224
3238
class Converter7to8(object):
3225
 
    """Perform an in-place upgrade of format 6 to format 7"""
 
3239
    """Perform an in-place upgrade of format 7 to format 8"""
3226
3240
 
3227
3241
    def convert(self, branch):
3228
3242
        format = BzrBranchFormat8()
3231
3245
        branch._transport.put_bytes('format', format.get_format_string())
3232
3246
 
3233
3247
 
3234
 
def _run_with_write_locked_target(target, callable, *args, **kwargs):
3235
 
    """Run ``callable(*args, **kwargs)``, write-locking target for the
3236
 
    duration.
3237
 
 
3238
 
    _run_with_write_locked_target will attempt to release the lock it acquires.
3239
 
 
3240
 
    If an exception is raised by callable, then that exception *will* be
3241
 
    propagated, even if the unlock attempt raises its own error.  Thus
3242
 
    _run_with_write_locked_target should be preferred to simply doing::
3243
 
 
3244
 
        target.lock_write()
3245
 
        try:
3246
 
            return callable(*args, **kwargs)
3247
 
        finally:
3248
 
            target.unlock()
3249
 
 
3250
 
    """
3251
 
    # This is very similar to bzrlib.decorators.needs_write_lock.  Perhaps they
3252
 
    # should share code?
3253
 
    target.lock_write()
3254
 
    try:
3255
 
        result = callable(*args, **kwargs)
3256
 
    except:
3257
 
        exc_info = sys.exc_info()
3258
 
        try:
3259
 
            target.unlock()
3260
 
        finally:
3261
 
            raise exc_info[0], exc_info[1], exc_info[2]
3262
 
    else:
3263
 
        target.unlock()
3264
 
        return result
3265
 
 
3266
 
 
3267
3248
class InterBranch(InterObject):
3268
3249
    """This class represents operations taking place between two branches.
3269
3250
 
3297
3278
        raise NotImplementedError(self.pull)
3298
3279
 
3299
3280
    @needs_write_lock
3300
 
    def update_revisions(self, stop_revision=None, overwrite=False,
3301
 
                         graph=None):
3302
 
        """Pull in new perfect-fit revisions.
3303
 
 
3304
 
        :param stop_revision: Updated until the given revision
3305
 
        :param overwrite: Always set the branch pointer, rather than checking
3306
 
            to see if it is a proper descendant.
3307
 
        :param graph: A Graph object that can be used to query history
3308
 
            information. This can be None.
3309
 
        :return: None
3310
 
        """
3311
 
        raise NotImplementedError(self.update_revisions)
3312
 
 
3313
 
    @needs_write_lock
3314
 
    def push(self, overwrite=False, stop_revision=None,
 
3281
    def push(self, overwrite=False, stop_revision=None, lossy=False,
3315
3282
             _override_hook_source_branch=None):
3316
3283
        """Mirror the source branch into the target branch.
3317
3284
 
3328
3295
        """
3329
3296
        raise NotImplementedError(self.copy_content_into)
3330
3297
 
 
3298
    @needs_write_lock
 
3299
    def fetch(self, stop_revision=None, limit=None):
 
3300
        """Fetch revisions.
 
3301
 
 
3302
        :param stop_revision: Last revision to fetch
 
3303
        :param limit: Optional rough limit of revisions to fetch
 
3304
        """
 
3305
        raise NotImplementedError(self.fetch)
 
3306
 
3331
3307
 
3332
3308
class GenericInterBranch(InterBranch):
3333
3309
    """InterBranch implementation that uses public Branch functions."""
3339
3315
 
3340
3316
    @classmethod
3341
3317
    def _get_branch_formats_to_test(klass):
3342
 
        return [(BranchFormat._default_format, BranchFormat._default_format)]
 
3318
        return [(format_registry.get_default(), format_registry.get_default())]
3343
3319
 
3344
3320
    @classmethod
3345
3321
    def unwrap_format(klass, format):
3346
3322
        if isinstance(format, remote.RemoteBranchFormat):
3347
3323
            format._ensure_real()
3348
3324
            return format._custom_format
3349
 
        return format                                                                                                  
 
3325
        return format
3350
3326
 
3351
3327
    @needs_write_lock
3352
3328
    def copy_content_into(self, revision_id=None):
3368
3344
            self.source.tags.merge_to(self.target.tags)
3369
3345
 
3370
3346
    @needs_write_lock
3371
 
    def update_revisions(self, stop_revision=None, overwrite=False,
3372
 
        graph=None):
3373
 
        """See InterBranch.update_revisions()."""
 
3347
    def fetch(self, stop_revision=None, limit=None):
 
3348
        if self.target.base == self.source.base:
 
3349
            return (0, [])
 
3350
        self.source.lock_read()
 
3351
        try:
 
3352
            fetch_spec_factory = fetch.FetchSpecFactory()
 
3353
            fetch_spec_factory.source_branch = self.source
 
3354
            fetch_spec_factory.source_branch_stop_revision_id = stop_revision
 
3355
            fetch_spec_factory.source_repo = self.source.repository
 
3356
            fetch_spec_factory.target_repo = self.target.repository
 
3357
            fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
 
3358
            fetch_spec_factory.limit = limit
 
3359
            fetch_spec = fetch_spec_factory.make_fetch_spec()
 
3360
            return self.target.repository.fetch(self.source.repository,
 
3361
                fetch_spec=fetch_spec)
 
3362
        finally:
 
3363
            self.source.unlock()
 
3364
 
 
3365
    @needs_write_lock
 
3366
    def _update_revisions(self, stop_revision=None, overwrite=False,
 
3367
            graph=None):
3374
3368
        other_revno, other_last_revision = self.source.last_revision_info()
3375
3369
        stop_revno = None # unknown
3376
3370
        if stop_revision is None:
3387
3381
        # case of having something to pull, and so that the check for
3388
3382
        # already merged can operate on the just fetched graph, which will
3389
3383
        # be cached in memory.
3390
 
        self.target.fetch(self.source, stop_revision)
 
3384
        self.fetch(stop_revision=stop_revision)
3391
3385
        # Check to see if one is an ancestor of the other
3392
3386
        if not overwrite:
3393
3387
            if graph is None:
3421
3415
        if local and not bound_location:
3422
3416
            raise errors.LocalRequiresBoundBranch()
3423
3417
        master_branch = None
3424
 
        if not local and bound_location and self.source.user_url != bound_location:
 
3418
        source_is_master = False
 
3419
        if bound_location:
 
3420
            # bound_location comes from a config file, some care has to be
 
3421
            # taken to relate it to source.user_url
 
3422
            normalized = urlutils.normalize_url(bound_location)
 
3423
            try:
 
3424
                relpath = self.source.user_transport.relpath(normalized)
 
3425
                source_is_master = (relpath == '')
 
3426
            except (errors.PathNotChild, errors.InvalidURL):
 
3427
                source_is_master = False
 
3428
        if not local and bound_location and not source_is_master:
3425
3429
            # not pulling from master, so we need to update master.
3426
3430
            master_branch = self.target.get_master_branch(possible_transports)
3427
3431
            master_branch.lock_write()
3433
3437
            return self._pull(overwrite,
3434
3438
                stop_revision, _hook_master=master_branch,
3435
3439
                run_hooks=run_hooks,
3436
 
                _override_hook_target=_override_hook_target)
 
3440
                _override_hook_target=_override_hook_target,
 
3441
                merge_tags_to_master=not source_is_master)
3437
3442
        finally:
3438
3443
            if master_branch:
3439
3444
                master_branch.unlock()
3440
3445
 
3441
 
    def push(self, overwrite=False, stop_revision=None,
 
3446
    def push(self, overwrite=False, stop_revision=None, lossy=False,
3442
3447
             _override_hook_source_branch=None):
3443
3448
        """See InterBranch.push.
3444
3449
 
3445
3450
        This is the basic concrete implementation of push()
3446
3451
 
3447
 
        :param _override_hook_source_branch: If specified, run
3448
 
        the hooks passing this Branch as the source, rather than self.
3449
 
        This is for use of RemoteBranch, where push is delegated to the
3450
 
        underlying vfs-based Branch.
 
3452
        :param _override_hook_source_branch: If specified, run the hooks
 
3453
            passing this Branch as the source, rather than self.  This is for
 
3454
            use of RemoteBranch, where push is delegated to the underlying
 
3455
            vfs-based Branch.
3451
3456
        """
 
3457
        if lossy:
 
3458
            raise errors.LossyPushToSameVCS(self.source, self.target)
3452
3459
        # TODO: Public option to disable running hooks - should be trivial but
3453
3460
        # needs tests.
3454
 
        self.source.lock_read()
3455
 
        try:
3456
 
            return _run_with_write_locked_target(
3457
 
                self.target, self._push_with_bound_branches, overwrite,
3458
 
                stop_revision,
3459
 
                _override_hook_source_branch=_override_hook_source_branch)
3460
 
        finally:
3461
 
            self.source.unlock()
3462
 
 
3463
 
    def _push_with_bound_branches(self, overwrite, stop_revision,
 
3461
 
 
3462
        op = cleanup.OperationWithCleanups(self._push_with_bound_branches)
 
3463
        op.add_cleanup(self.source.lock_read().unlock)
 
3464
        op.add_cleanup(self.target.lock_write().unlock)
 
3465
        return op.run(overwrite, stop_revision,
 
3466
            _override_hook_source_branch=_override_hook_source_branch)
 
3467
 
 
3468
    def _basic_push(self, overwrite, stop_revision):
 
3469
        """Basic implementation of push without bound branches or hooks.
 
3470
 
 
3471
        Must be called with source read locked and target write locked.
 
3472
        """
 
3473
        result = BranchPushResult()
 
3474
        result.source_branch = self.source
 
3475
        result.target_branch = self.target
 
3476
        result.old_revno, result.old_revid = self.target.last_revision_info()
 
3477
        self.source.update_references(self.target)
 
3478
        if result.old_revid != stop_revision:
 
3479
            # We assume that during 'push' this repository is closer than
 
3480
            # the target.
 
3481
            graph = self.source.repository.get_graph(self.target.repository)
 
3482
            self._update_revisions(stop_revision, overwrite=overwrite,
 
3483
                    graph=graph)
 
3484
        if self.source._push_should_merge_tags():
 
3485
            result.tag_updates, result.tag_conflicts = (
 
3486
                self.source.tags.merge_to(self.target.tags, overwrite))
 
3487
        result.new_revno, result.new_revid = self.target.last_revision_info()
 
3488
        return result
 
3489
 
 
3490
    def _push_with_bound_branches(self, operation, overwrite, stop_revision,
3464
3491
            _override_hook_source_branch=None):
3465
3492
        """Push from source into target, and into target's master if any.
3466
3493
        """
3478
3505
            # be bound to itself? -- mbp 20070507
3479
3506
            master_branch = self.target.get_master_branch()
3480
3507
            master_branch.lock_write()
3481
 
            try:
3482
 
                # push into the master from the source branch.
3483
 
                self.source._basic_push(master_branch, overwrite, stop_revision)
3484
 
                # and push into the target branch from the source. Note that we
3485
 
                # push from the source branch again, because it's considered the
3486
 
                # highest bandwidth repository.
3487
 
                result = self.source._basic_push(self.target, overwrite,
3488
 
                    stop_revision)
3489
 
                result.master_branch = master_branch
3490
 
                result.local_branch = self.target
3491
 
                _run_hooks()
3492
 
                return result
3493
 
            finally:
3494
 
                master_branch.unlock()
 
3508
            operation.add_cleanup(master_branch.unlock)
 
3509
            # push into the master from the source branch.
 
3510
            master_inter = InterBranch.get(self.source, master_branch)
 
3511
            master_inter._basic_push(overwrite, stop_revision)
 
3512
            # and push into the target branch from the source. Note that
 
3513
            # we push from the source branch again, because it's considered
 
3514
            # the highest bandwidth repository.
 
3515
            result = self._basic_push(overwrite, stop_revision)
 
3516
            result.master_branch = master_branch
 
3517
            result.local_branch = self.target
3495
3518
        else:
 
3519
            master_branch = None
3496
3520
            # no master branch
3497
 
            result = self.source._basic_push(self.target, overwrite,
3498
 
                stop_revision)
 
3521
            result = self._basic_push(overwrite, stop_revision)
3499
3522
            # TODO: Why set master_branch and local_branch if there's no
3500
3523
            # binding?  Maybe cleaner to just leave them unset? -- mbp
3501
3524
            # 20070504
3502
3525
            result.master_branch = self.target
3503
3526
            result.local_branch = None
3504
 
            _run_hooks()
3505
 
            return result
 
3527
        _run_hooks()
 
3528
        return result
3506
3529
 
3507
3530
    def _pull(self, overwrite=False, stop_revision=None,
3508
3531
             possible_transports=None, _hook_master=None, run_hooks=True,
3509
 
             _override_hook_target=None, local=False):
 
3532
             _override_hook_target=None, local=False,
 
3533
             merge_tags_to_master=True):
3510
3534
        """See Branch.pull.
3511
3535
 
3512
3536
        This function is the core worker, used by GenericInterBranch.pull to
3517
3541
        :param run_hooks: Private parameter - if false, this branch
3518
3542
            is being called because it's the master of the primary branch,
3519
3543
            so it should not run its hooks.
 
3544
            is being called because it's the master of the primary branch,
 
3545
            so it should not run its hooks.
3520
3546
        :param _override_hook_target: Private parameter - set the branch to be
3521
3547
            supplied as the target_branch to pull hooks.
3522
3548
        :param local: Only update the local branch, and not the bound branch.
3541
3567
            # -- JRV20090506
3542
3568
            result.old_revno, result.old_revid = \
3543
3569
                self.target.last_revision_info()
3544
 
            self.target.update_revisions(self.source, stop_revision,
3545
 
                overwrite=overwrite, graph=graph)
 
3570
            self._update_revisions(stop_revision, overwrite=overwrite,
 
3571
                graph=graph)
3546
3572
            # TODO: The old revid should be specified when merging tags, 
3547
3573
            # so a tags implementation that versions tags can only 
3548
3574
            # pull in the most recent changes. -- JRV20090506
3549
 
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3550
 
                overwrite)
 
3575
            result.tag_updates, result.tag_conflicts = (
 
3576
                self.source.tags.merge_to(self.target.tags, overwrite,
 
3577
                    ignore_master=not merge_tags_to_master))
3551
3578
            result.new_revno, result.new_revid = self.target.last_revision_info()
3552
3579
            if _hook_master:
3553
3580
                result.master_branch = _hook_master