/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
6404.6.1 by Vincent Ladeuil
Tests passing for a first rough version of a cached branch config store. The changes here are too invasive and several parallel proposals have been made.
1
# Copyright (C) 2005-2012 Canonical Ltd
1553.5.70 by Martin Pool
doc
2
#
1 by mbp at sourcefrog
import from baz patch-364
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
1553.5.70 by Martin Pool
doc
7
#
1 by mbp at sourcefrog
import from baz patch-364
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
1553.5.70 by Martin Pool
doc
12
#
1 by mbp at sourcefrog
import from baz patch-364
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1 by mbp at sourcefrog
import from baz patch-364
16
6379.6.1 by Jelmer Vernooij
Import absolute_import in a few places.
17
from __future__ import absolute_import
18
6973.5.10 by Jelmer Vernooij
Random bunch of python3 bee-improvements.
19
import sys
20
6653.1.1 by Jelmer Vernooij
Split bzr branch code out into breezy.bzrbranch.
21
from . import errors
1 by mbp at sourcefrog
import from baz patch-364
22
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
23
from .lazy_import import lazy_import
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
24
lazy_import(globals(), """
6105.1.1 by Jelmer Vernooij
Fix "pydoc bzrlib.branch" by importing modules, not objects, using lazy_import.
25
import itertools
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
26
from breezy import (
6754.8.12 by Jelmer Vernooij
FIx remaining tests.
27
    cleanup,
6207.3.3 by jelmer at samba
Fix tests and the like.
28
    config as _mod_config,
29
    debug,
30
    fetch,
6883.8.1 by Jelmer Vernooij
Add Branch.create_memorytree.
31
    memorytree,
6207.3.3 by jelmer at samba
Fix tests and the like.
32
    repository,
33
    revision as _mod_revision,
34
    tag as _mod_tag,
35
    transport,
36
    ui,
37
    urlutils,
6670.4.3 by Jelmer Vernooij
Fix more imports.
38
    )
39
from breezy.bzr import (
6670.4.15 by Jelmer Vernooij
Fix per workingtree tests.
40
    remote,
6341.1.4 by Jelmer Vernooij
Move more functionality to vf_search.
41
    vf_search,
6207.3.3 by jelmer at samba
Fix tests and the like.
42
    )
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
43
from breezy.i18n import gettext, ngettext
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
44
""")
45
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
46
from . import (
5697.2.1 by Jelmer Vernooij
Move weave branch to bzrlib.branch_weave.
47
    controldir,
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
48
    registry,
5697.2.1 by Jelmer Vernooij
Move weave branch to bzrlib.branch_weave.
49
    )
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
50
from .decorators import (
5697.2.1 by Jelmer Vernooij
Move weave branch to bzrlib.branch_weave.
51
    only_raises,
52
    )
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
53
from .hooks import Hooks
54
from .inter import InterObject
6653.1.1 by Jelmer Vernooij
Split bzr branch code out into breezy.bzrbranch.
55
from .lock import LogicalLockResult
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
56
from .sixish import (
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
57
    BytesIO,
6855.4.5 by Jelmer Vernooij
Fix more bees, use with rather than try/finally for some files.
58
    text_type,
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
59
    viewitems,
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
60
    )
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
61
from .trace import mutter, mutter_callsite, note, is_quiet
1104 by Martin Pool
- Add a simple UIFactory
62
1094 by Martin Pool
- merge aaron's merge improvements 999..1008
63
6734.1.11 by Jelmer Vernooij
Move UnstackableBranchFormat.
64
class UnstackableBranchFormat(errors.BzrError):
65
66
    _fmt = ("The branch '%(url)s'(%(format)s) is not a stackable format. "
67
        "You will need to upgrade the branch to permit branch stacking.")
68
69
    def __init__(self, format, url):
70
        errors.BzrError.__init__(self)
71
        self.format = format
72
        self.url = url
73
74
5363.2.10 by Jelmer Vernooij
base ControlDir on ControlComponent.
75
class Branch(controldir.ControlComponent):
1 by mbp at sourcefrog
import from baz patch-364
76
    """Branch holding a history of revisions.
77
5158.6.2 by Martin Pool
Branch provides user_url etc
78
    :ivar base:
79
        Base directory/url of the branch; using control_url and
80
        control_transport is more standardized.
5609.25.6 by Andrew Bennetts
Docstring tweaks.
81
    :ivar hooks: An instance of BranchHooks.
82
    :ivar _master_branch_cache: cached result of get_master_branch, see
83
        _clear_cached_state.
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
84
    """
1534.4.1 by Robert Collins
Allow parameterisation of the branch initialisation for bzrlib.
85
    # this is really an instance variable - FIXME move it there
86
    # - RBC 20060112
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
87
    base = None
88
5158.6.2 by Martin Pool
Branch provides user_url etc
89
    @property
90
    def control_transport(self):
91
        return self._transport
92
93
    @property
94
    def user_transport(self):
6653.6.1 by Jelmer Vernooij
Rename a number of attributes from bzrdir to controldir.
95
        return self.controldir.user_transport
5158.6.2 by Martin Pool
Branch provides user_url etc
96
6305.3.2 by Jelmer Vernooij
Only make a single connection.
97
    def __init__(self, possible_transports=None):
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
98
        self.tags = self._format.make_tags(self)
2375.1.3 by Andrew Bennetts
Don't use Branch.get_transaction to cache revision history.
99
        self._revision_history_cache = None
2418.5.6 by John Arbash Meinel
Cache the revision_id => revno map as appropriate.
100
        self._revision_id_to_revno_cache = None
3949.2.6 by Ian Clatworthy
review feedback from jam
101
        self._partial_revision_id_to_revno_cache = {}
4419.2.1 by Andrew Bennetts
Move _extend_partial_history into Branch base class, and use it in get_rev_id rather than self.revision_history().
102
        self._partial_revision_history_cache = []
3441.5.27 by Andrew Bennetts
Tweaks suggested by John's review: rename _check_if_descendant_or_diverged, move caching last_revision_info into base Branch, better use of lock decorators.
103
        self._last_revision_info_cache = None
5609.25.3 by Andrew Bennetts
Alternative fix: cache the result of get_master_branch for the lifetime of the branch lock.
104
        self._master_branch_cache = None
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
105
        self._merge_sorted_revisions_cache = None
6305.3.2 by Jelmer Vernooij
Only make a single connection.
106
        self._open_hook(possible_transports)
3681.1.1 by Robert Collins
Create a new hook Branch.open. (Robert Collins)
107
        hooks = Branch.hooks['open']
108
        for hook in hooks:
109
            hook(self)
3221.11.11 by Robert Collins
Ensure opening a stacked branch gives a ready to use repository.
110
6305.3.2 by Jelmer Vernooij
Only make a single connection.
111
    def _open_hook(self, possible_transports):
3221.11.11 by Robert Collins
Ensure opening a stacked branch gives a ready to use repository.
112
        """Called by init to allow simpler extension of the base class."""
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
113
6305.3.2 by Jelmer Vernooij
Only make a single connection.
114
    def _activate_fallback_location(self, url, possible_transports):
4226.1.3 by Robert Collins
Lift Branch.set_stacked_on_url up from BzrBranch7.
115
        """Activate the branch/repository from url as a fallback repository."""
5536.1.1 by Andrew Bennetts
Avoid reopening (and relocking) the same branches/repositories in ControlDir.sprout. Still a few rough edges, but the tests I've run are passing.
116
        for existing_fallback_repo in self.repository._fallback_repositories:
117
            if existing_fallback_repo.user_url == url:
118
                # This fallback is already configured.  This probably only
6653.1.1 by Jelmer Vernooij
Split bzr branch code out into breezy.bzrbranch.
119
                # happens because ControlDir.sprout is a horrible mess.  To
120
                # avoid confusing _unstack we don't add this a second time.
5536.1.9 by Andrew Bennetts
Do as the XXX and John's review suggest: log a warning about duplicate fallback activation.
121
                mutter('duplicate activation of fallback %r on %r', url, self)
5536.1.1 by Andrew Bennetts
Avoid reopening (and relocking) the same branches/repositories in ControlDir.sprout. Still a few rough edges, but the tests I've run are passing.
122
                return
6305.3.2 by Jelmer Vernooij
Only make a single connection.
123
        repo = self._get_fallback_repository(url, possible_transports)
4462.3.2 by Robert Collins
Do not stack on the same branch/repository anymore. This was never supported and would generally result in infinite recursion. Fixes bug 376243.
124
        if repo.has_same_location(self.repository):
5158.6.3 by Martin Pool
Update some Branch calls to use ControlComponent style.
125
            raise errors.UnstackableLocationError(self.user_url, url)
4288.1.10 by Robert Collins
Fix up lock correctness to deal with adding fallback repositories to locked branch objects.
126
        self.repository.add_fallback_repository(repo)
4226.1.3 by Robert Collins
Lift Branch.set_stacked_on_url up from BzrBranch7.
127
1687.1.8 by Robert Collins
Teach Branch about break_lock.
128
    def break_lock(self):
129
        """Break a lock if one is present from another instance.
130
131
        Uses the ui factory to ask for confirmation if the lock may be from
132
        an active process.
133
134
        This will probe the repository for its lock as well.
135
        """
136
        self.control_files.break_lock()
137
        self.repository.break_lock()
1687.1.10 by Robert Collins
Branch.break_lock should handle bound branches too
138
        master = self.get_master_branch()
139
        if master is not None:
140
            master.break_lock()
1687.1.8 by Robert Collins
Teach Branch about break_lock.
141
4226.1.3 by Robert Collins
Lift Branch.set_stacked_on_url up from BzrBranch7.
142
    def _check_stackable_repo(self):
143
        if not self.repository._format.supports_external_lookups:
6653.1.1 by Jelmer Vernooij
Split bzr branch code out into breezy.bzrbranch.
144
            raise errors.UnstackableRepositoryFormat(
145
                self.repository._format, self.repository.base)
4226.1.3 by Robert Collins
Lift Branch.set_stacked_on_url up from BzrBranch7.
146
4419.2.1 by Andrew Bennetts
Move _extend_partial_history into Branch base class, and use it in get_rev_id rather than self.revision_history().
147
    def _extend_partial_history(self, stop_index=None, stop_revision=None):
148
        """Extend the partial history to include a given index
149
150
        If a stop_index is supplied, stop when that index has been reached.
151
        If a stop_revision is supplied, stop when that revision is
152
        encountered.  Otherwise, stop when the beginning of history is
153
        reached.
154
155
        :param stop_index: The index which should be present.  When it is
156
            present, history extension will stop.
4419.2.3 by Andrew Bennetts
Refactor _extend_partial_history into a standalone function that can be used without a branch.
157
        :param stop_revision: The revision id which should be present.  When
4419.2.1 by Andrew Bennetts
Move _extend_partial_history into Branch base class, and use it in get_rev_id rather than self.revision_history().
158
            it is encountered, history extension will stop.
159
        """
160
        if len(self._partial_revision_history_cache) == 0:
4419.2.3 by Andrew Bennetts
Refactor _extend_partial_history into a standalone function that can be used without a branch.
161
            self._partial_revision_history_cache = [self.last_revision()]
162
        repository._iter_for_revno(
163
            self.repository, self._partial_revision_history_cache,
164
            stop_index=stop_index, stop_revision=stop_revision)
165
        if self._partial_revision_history_cache[-1] == _mod_revision.NULL_REVISION:
166
            self._partial_revision_history_cache.pop()
4419.2.1 by Andrew Bennetts
Move _extend_partial_history into Branch base class, and use it in get_rev_id rather than self.revision_history().
167
4332.3.5 by Robert Collins
Add Branch._get_check_refs.
168
    def _get_check_refs(self):
169
        """Get the references needed for check().
170
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
171
        See breezy.check.
4332.3.5 by Robert Collins
Add Branch._get_check_refs.
172
        """
173
        revid = self.last_revision()
174
        return [('revision-existence', revid), ('lefthand-distance', revid)]
175
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
176
    @staticmethod
2806.2.2 by Vincent Ladeuil
Fix #128076 and #131396 by reusing bound branch transport.
177
    def open(base, _unsupported=False, possible_transports=None):
1815.1.1 by Jelmer Vernooij
Fix copy-pasted comment.
178
        """Open the branch rooted at base.
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
179
1815.1.1 by Jelmer Vernooij
Fix copy-pasted comment.
180
        For instance, if the branch is at URL/.bzr/branch,
181
        Branch.open(URL) -> a Branch instance.
1534.4.7 by Robert Collins
Move downlevel check up to the Branch.open logic, removing it from the Branch constructor and deprecating relax_version_check to the same.
182
        """
6402.3.3 by Jelmer Vernooij
Simplify safe open a bit more.
183
        control = controldir.ControlDir.open(base,
184
            possible_transports=possible_transports, _unsupported=_unsupported)
6305.3.2 by Jelmer Vernooij
Only make a single connection.
185
        return control.open_branch(unsupported=_unsupported,
186
            possible_transports=possible_transports)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
187
188
    @staticmethod
6305.3.2 by Jelmer Vernooij
Only make a single connection.
189
    def open_from_transport(transport, name=None, _unsupported=False,
190
            possible_transports=None):
2485.8.35 by Vincent Ladeuil
Fix pull multiple connections.
191
        """Open the branch rooted at transport"""
6207.3.3 by jelmer at samba
Fix tests and the like.
192
        control = controldir.ControlDir.open_from_transport(transport, _unsupported)
6305.3.2 by Jelmer Vernooij
Only make a single connection.
193
        return control.open_branch(name=name, unsupported=_unsupported,
194
            possible_transports=possible_transports)
2485.8.35 by Vincent Ladeuil
Fix pull multiple connections.
195
196
    @staticmethod
2485.8.37 by Vincent Ladeuil
Fix merge multiple connections. Test suite *not* passing (sftp
197
    def open_containing(url, possible_transports=None):
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
198
        """Open an existing branch which contains url.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
199
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
200
        This probes for a branch at url, and searches upwards from there.
1185.17.2 by Martin Pool
[pick] avoid problems in fetching when .bzr is not listable
201
202
        Basically we keep looking up until we find the control directory or
203
        run into the root.  If there isn't one, raises NotBranchError.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
204
        If there is one and it is either an unrecognised format or an unsupported
1534.4.22 by Robert Collins
update TODOs and move abstract methods that were misplaced on BzrBranchFormat5 to Branch.
205
        format, UnknownFormatError or UnsupportedFormatError are raised.
1442.1.64 by Robert Collins
Branch.open_containing now returns a tuple (Branch, relative-path).
206
        If there is one, it is returned, along with the unused portion of url.
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
207
        """
6207.3.3 by jelmer at samba
Fix tests and the like.
208
        control, relpath = controldir.ControlDir.open_containing(url,
2485.8.37 by Vincent Ladeuil
Fix merge multiple connections. Test suite *not* passing (sftp
209
                                                         possible_transports)
6305.3.2 by Jelmer Vernooij
Only make a single connection.
210
        branch = control.open_branch(possible_transports=possible_transports)
211
        return (branch, relpath)
1534.4.1 by Robert Collins
Allow parameterisation of the branch initialisation for bzrlib.
212
4032.3.5 by Robert Collins
Move BzrBranch._push_should_merge_tags to Branch.
213
    def _push_should_merge_tags(self):
214
        """Should _basic_push merge this branch's tags into the target?
215
216
        The default implementation returns False if this branch has no tags,
217
        and True the rest of the time.  Subclasses may override this.
218
        """
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
219
        return self.supports_tags() and self.tags.get_tag_dict()
4032.3.5 by Robert Collins
Move BzrBranch._push_should_merge_tags to Branch.
220
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
221
    def get_config(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
222
        """Get a breezy.config.BranchConfig for this Branch.
5284.3.1 by Robert Collins
Document bzrlib.branch.Branch.get_config.
223
224
        This can then be used to get and set configuration options for the
225
        branch.
226
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
227
        :return: A breezy.config.BranchConfig.
5284.3.1 by Robert Collins
Document bzrlib.branch.Branch.get_config.
228
        """
6105.1.1 by Jelmer Vernooij
Fix "pydoc bzrlib.branch" by importing modules, not objects, using lazy_import.
229
        return _mod_config.BranchConfig(self)
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
230
6155.2.1 by Vincent Ladeuil
Migrate dpush_strict, push_strict and send_strict options to the stack based config design, introducing get_config_stack for branches.
231
    def get_config_stack(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
232
        """Get a breezy.config.BranchStack for this Branch.
6155.2.1 by Vincent Ladeuil
Migrate dpush_strict, push_strict and send_strict options to the stack based config design, introducing get_config_stack for branches.
233
234
        This can then be used to get and set configuration options for the
235
        branch.
236
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
237
        :return: A breezy.config.BranchStack.
6155.2.1 by Vincent Ladeuil
Migrate dpush_strict, push_strict and send_strict options to the stack based config design, introducing get_config_stack for branches.
238
        """
239
        return _mod_config.BranchStack(self)
240
6538.1.29 by Aaron Bentley
Remove unused 'message'
241
    def store_uncommitted(self, creator):
6538.1.20 by Aaron Bentley
Cleanup
242
        """Store uncommitted changes from a ShelfCreator.
243
6538.1.21 by Aaron Bentley
Ensure shelves are deleted when restored.
244
        :param creator: The ShelfCreator containing uncommitted changes, or
245
            None to delete any stored changes.
6538.1.20 by Aaron Bentley
Cleanup
246
        :raises: ChangesAlreadyStored if the branch already has changes.
247
        """
6538.1.23 by Aaron Bentley
Move uncommitted API to BzrBranch/RemoteBranch.
248
        raise NotImplementedError(self.store_uncommitted)
6538.1.4 by Aaron Bentley
Implement store_uncommitted.
249
6538.1.12 by Aaron Bentley
Move unshelver construction to Branch.
250
    def get_unshelver(self, tree):
6538.1.20 by Aaron Bentley
Cleanup
251
        """Return a shelf.Unshelver for this branch and tree.
252
253
        :param tree: The tree to use to construct the Unshelver.
254
        :return: an Unshelver or None if no changes are stored.
255
        """
6538.1.23 by Aaron Bentley
Move uncommitted API to BzrBranch/RemoteBranch.
256
        raise NotImplementedError(self.get_unshelver)
6538.1.8 by Aaron Bentley
Implement branch.get_uncommitted_data.
257
6305.3.2 by Jelmer Vernooij
Only make a single connection.
258
    def _get_fallback_repository(self, url, possible_transports):
4226.1.3 by Robert Collins
Lift Branch.set_stacked_on_url up from BzrBranch7.
259
        """Get the repository we fallback to at url."""
260
        url = urlutils.join(self.base, url)
6305.3.2 by Jelmer Vernooij
Only make a single connection.
261
        a_branch = Branch.open(url, possible_transports=possible_transports)
5051.3.14 by Jelmer Vernooij
Remove use of BzrDir.open_branch() without arguments.
262
        return a_branch.repository
4226.1.3 by Robert Collins
Lift Branch.set_stacked_on_url up from BzrBranch7.
263
3815.3.4 by Marius Kruger
When doing a `commit --local`, don't try to connect to the master branch.
264
    def _get_nick(self, local=False, possible_transports=None):
3565.6.7 by Marius Kruger
* checkouts now use master nick when no explicit nick is set.
265
        config = self.get_config()
3815.3.4 by Marius Kruger
When doing a `commit --local`, don't try to connect to the master branch.
266
        # explicit overrides master, but don't look for master if local is True
267
        if not local and not config.has_explicit_nickname():
3565.6.10 by Marius Kruger
Silently fall back to local implicit nick if the master is unavailable
268
            try:
269
                master = self.get_master_branch(possible_transports)
5050.7.4 by Parth Malwankar
fixed recursion detection to handle shared repos
270
                if master and self.user_url == master.user_url:
5050.7.5 by Parth Malwankar
better error message for RecursiveBind
271
                    raise errors.RecursiveBind(self.user_url)
3565.6.10 by Marius Kruger
Silently fall back to local implicit nick if the master is unavailable
272
                if master is not None:
273
                    # return the master branch value
3815.3.3 by Marius Kruger
apply Martin's fix for #293440
274
                    return master.nick
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
275
            except errors.RecursiveBind as e:
5050.7.2 by Parth Malwankar
recursive binding now shows a clear error
276
                raise e
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
277
            except errors.BzrError as e:
3565.6.10 by Marius Kruger
Silently fall back to local implicit nick if the master is unavailable
278
                # Silently fall back to local implicit nick if the master is
279
                # unavailable
280
                mutter("Could not connect to bound branch, "
281
                    "falling back to local nick.\n " + str(e))
3565.6.7 by Marius Kruger
* checkouts now use master nick when no explicit nick is set.
282
        return config.get_nickname()
1185.35.11 by Aaron Bentley
Added support for branch nicks
283
284
    def _set_nick(self, nick):
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
285
        self.get_config().set_user_option('nickname', nick, warn_masked=True)
1185.35.11 by Aaron Bentley
Added support for branch nicks
286
287
    nick = property(_get_nick, _set_nick)
1694.2.6 by Martin Pool
[merge] bzr.dev
288
289
    def is_locked(self):
1910.3.2 by Andrew Bennetts
Improve some NotImplementedErrors.
290
        raise NotImplementedError(self.is_locked)
1694.2.6 by Martin Pool
[merge] bzr.dev
291
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
292
    def _lefthand_history(self, revision_id, last_rev=None,
293
                          other_branch=None):
294
        if 'evil' in debug.debug_flags:
295
            mutter_callsite(4, "_lefthand_history scales with history.")
296
        # stop_revision must be a descendant of last_revision
297
        graph = self.repository.get_graph()
298
        if last_rev is not None:
299
            if not graph.is_ancestor(last_rev, revision_id):
300
                # our previous tip is not merged into stop_revision
301
                raise errors.DivergedBranches(self, other_branch)
302
        # make a new revision history from the graph
303
        parents_map = graph.get_parent_map([revision_id])
304
        if revision_id not in parents_map:
305
            raise errors.NoSuchRevision(self, revision_id)
306
        current_rev_id = revision_id
307
        new_history = []
308
        check_not_reserved_id = _mod_revision.check_not_reserved_id
309
        # Do not include ghosts or graph origin in revision_history
310
        while (current_rev_id in parents_map and
311
               len(parents_map[current_rev_id]) > 0):
312
            check_not_reserved_id(current_rev_id)
313
            new_history.append(current_rev_id)
314
            current_rev_id = parents_map[current_rev_id][0]
315
            parents_map = graph.get_parent_map([current_rev_id])
316
        new_history.reverse()
317
        return new_history
318
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
319
    def lock_write(self, token=None):
320
        """Lock the branch for write operations.
321
322
        :param token: A token to permit reacquiring a previously held and
323
            preserved lock.
324
        :return: A BranchWriteLockResult.
325
        """
1910.3.2 by Andrew Bennetts
Improve some NotImplementedErrors.
326
        raise NotImplementedError(self.lock_write)
1694.2.6 by Martin Pool
[merge] bzr.dev
327
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
328
    def lock_read(self):
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
329
        """Lock the branch for read operations.
330
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
331
        :return: A breezy.lock.LogicalLockResult.
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
332
        """
1910.3.2 by Andrew Bennetts
Improve some NotImplementedErrors.
333
        raise NotImplementedError(self.lock_read)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
334
335
    def unlock(self):
1910.3.2 by Andrew Bennetts
Improve some NotImplementedErrors.
336
        raise NotImplementedError(self.unlock)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
337
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
338
    def peek_lock_mode(self):
339
        """Return lock mode for the Branch: 'r', 'w' or None"""
1185.70.6 by Martin Pool
review fixups from John
340
        raise NotImplementedError(self.peek_lock_mode)
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
341
1694.2.6 by Martin Pool
[merge] bzr.dev
342
    def get_physical_lock_status(self):
1910.3.2 by Andrew Bennetts
Improve some NotImplementedErrors.
343
        raise NotImplementedError(self.get_physical_lock_status)
1694.2.6 by Martin Pool
[merge] bzr.dev
344
3949.2.6 by Ian Clatworthy
review feedback from jam
345
    def dotted_revno_to_revision_id(self, revno, _cache_reverse=False):
3949.2.1 by Ian Clatworthy
Branch.dotted_revno_to_revision_id API
346
        """Return the revision_id for a dotted revno.
347
348
        :param revno: a tuple like (1,) or (1,1,2)
3949.2.4 by Ian Clatworthy
add top level revno cache
349
        :param _cache_reverse: a private parameter enabling storage
350
           of the reverse mapping in a top level cache. (This should
351
           only be done in selective circumstances as we want to
352
           avoid having the mapping cached multiple times.)
3949.2.1 by Ian Clatworthy
Branch.dotted_revno_to_revision_id API
353
        :return: the revision_id
354
        :raises errors.NoSuchRevision: if the revno doesn't exist
355
        """
6754.8.6 by Jelmer Vernooij
Remove more decorators.
356
        with self.lock_read():
357
            rev_id = self._do_dotted_revno_to_revision_id(revno)
358
            if _cache_reverse:
359
                self._partial_revision_id_to_revno_cache[rev_id] = revno
360
            return rev_id
3949.2.1 by Ian Clatworthy
Branch.dotted_revno_to_revision_id API
361
3949.2.6 by Ian Clatworthy
review feedback from jam
362
    def _do_dotted_revno_to_revision_id(self, revno):
3949.2.1 by Ian Clatworthy
Branch.dotted_revno_to_revision_id API
363
        """Worker function for dotted_revno_to_revision_id.
364
365
        Subclasses should override this if they wish to
366
        provide a more efficient implementation.
367
        """
368
        if len(revno) == 1:
369
            return self.get_rev_id(revno[0])
370
        revision_id_to_revno = self.get_revision_id_to_revno_map()
3949.2.6 by Ian Clatworthy
review feedback from jam
371
        revision_ids = [revision_id for revision_id, this_revno
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
372
                        in viewitems(revision_id_to_revno)
3949.2.6 by Ian Clatworthy
review feedback from jam
373
                        if revno == this_revno]
374
        if len(revision_ids) == 1:
375
            return revision_ids[0]
3949.2.1 by Ian Clatworthy
Branch.dotted_revno_to_revision_id API
376
        else:
377
            revno_str = '.'.join(map(str, revno))
378
            raise errors.NoSuchRevision(self, revno_str)
379
3949.2.3 by Ian Clatworthy
add Branch.revision_id_to_dotted_revno()
380
    def revision_id_to_dotted_revno(self, revision_id):
381
        """Given a revision id, return its dotted revno.
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
382
3949.2.3 by Ian Clatworthy
add Branch.revision_id_to_dotted_revno()
383
        :return: a tuple like (1,) or (400,1,3).
384
        """
6754.8.6 by Jelmer Vernooij
Remove more decorators.
385
        with self.lock_read():
386
            return self._do_revision_id_to_dotted_revno(revision_id)
3949.2.3 by Ian Clatworthy
add Branch.revision_id_to_dotted_revno()
387
3949.2.6 by Ian Clatworthy
review feedback from jam
388
    def _do_revision_id_to_dotted_revno(self, revision_id):
3949.2.3 by Ian Clatworthy
add Branch.revision_id_to_dotted_revno()
389
        """Worker function for revision_id_to_revno."""
3949.2.4 by Ian Clatworthy
add top level revno cache
390
        # Try the caches if they are loaded
3949.2.6 by Ian Clatworthy
review feedback from jam
391
        result = self._partial_revision_id_to_revno_cache.get(revision_id)
392
        if result is not None:
393
            return result
394
        if self._revision_id_to_revno_cache:
3949.2.3 by Ian Clatworthy
add Branch.revision_id_to_dotted_revno()
395
            result = self._revision_id_to_revno_cache.get(revision_id)
3949.2.6 by Ian Clatworthy
review feedback from jam
396
            if result is None:
397
                raise errors.NoSuchRevision(self, revision_id)
398
        # Try the mainline as it's optimised
399
        try:
400
            revno = self.revision_id_to_revno(revision_id)
401
            return (revno,)
402
        except errors.NoSuchRevision:
403
            # We need to load and use the full revno map after all
404
            result = self.get_revision_id_to_revno_map().get(revision_id)
405
            if result is None:
406
                raise errors.NoSuchRevision(self, revision_id)
3949.2.3 by Ian Clatworthy
add Branch.revision_id_to_dotted_revno()
407
        return result
408
2418.5.12 by John Arbash Meinel
Move functions from BzrBranch to base Branch object.
409
    def get_revision_id_to_revno_map(self):
410
        """Return the revision_id => dotted revno map.
411
412
        This will be regenerated on demand, but will be cached.
413
414
        :return: A dictionary mapping revision_id => dotted revno.
415
            This dictionary should not be modified by the caller.
416
        """
6997.7.2 by Jelmer Vernooij
Add evil debug flag for get_revision_id_to_revno_map.
417
        if 'evil' in debug.debug_flags:
418
            mutter_callsite(3, "get_revision_id_to_revno_map scales with ancestry.")
6754.8.5 by Jelmer Vernooij
Avoid decorators.
419
        with self.lock_read():
420
            if self._revision_id_to_revno_cache is not None:
421
                mapping = self._revision_id_to_revno_cache
422
            else:
423
                mapping = self._gen_revno_map()
424
                self._cache_revision_id_to_revno(mapping)
425
            # TODO: jam 20070417 Since this is being cached, should we be returning
426
            #       a copy?
427
            # I would rather not, and instead just declare that users should not
428
            # modify the return value.
429
            return mapping
2418.5.12 by John Arbash Meinel
Move functions from BzrBranch to base Branch object.
430
431
    def _gen_revno_map(self):
432
        """Create a new mapping from revision ids to dotted revnos.
433
434
        Dotted revnos are generated based on the current tip in the revision
435
        history.
436
        This is the worker function for get_revision_id_to_revno_map, which
437
        just caches the return value.
438
439
        :return: A dictionary mapping revision_id => dotted revno.
440
        """
3949.3.1 by Ian Clatworthy
introduce Branch.merge_sorted_revisions API
441
        revision_id_to_revno = dict((rev_id, revno)
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
442
            for rev_id, depth, revno, end_of_merge
443
             in self.iter_merge_sorted_revisions())
3949.3.1 by Ian Clatworthy
introduce Branch.merge_sorted_revisions API
444
        return revision_id_to_revno
445
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
446
    def iter_merge_sorted_revisions(self, start_revision_id=None,
3960.3.1 by Ian Clatworthy
add stop_rule to Branch.iter_merge_sorted_revisions()
447
            stop_revision_id=None, stop_rule='exclude', direction='reverse'):
3949.3.2 by Ian Clatworthy
feedback from jam
448
        """Walk the revisions for a branch in merge sorted order.
3949.3.1 by Ian Clatworthy
introduce Branch.merge_sorted_revisions API
449
3949.3.8 by Ian Clatworthy
feedback from poolie
450
        Merge sorted order is the output from a merge-aware,
451
        topological sort, i.e. all parents come before their
452
        children going forward; the opposite for reverse.
453
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
454
        :param start_revision_id: the revision_id to begin walking from.
455
            If None, the branch tip is used.
456
        :param stop_revision_id: the revision_id to terminate the walk
3960.3.1 by Ian Clatworthy
add stop_rule to Branch.iter_merge_sorted_revisions()
457
            after. If None, the rest of history is included.
458
        :param stop_rule: if stop_revision_id is not None, the precise rule
459
            to use for termination:
5891.1.3 by Andrew Bennetts
Move docstring formatting fixes.
460
3960.3.1 by Ian Clatworthy
add stop_rule to Branch.iter_merge_sorted_revisions()
461
            * 'exclude' - leave the stop revision out of the result (default)
462
            * 'include' - the stop revision is the last item in the result
463
            * 'with-merges' - include the stop revision and all of its
464
              merged revisions in the result
5155.1.5 by Vincent Ladeuil
Fixed as per Andrew's review.
465
            * 'with-merges-without-common-ancestry' - filter out revisions 
466
              that are in both ancestries
3949.3.3 by Ian Clatworthy
simplify the meaning of forward to be appropriate to this layer
467
        :param direction: either 'reverse' or 'forward':
5891.1.3 by Andrew Bennetts
Move docstring formatting fixes.
468
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
469
            * reverse means return the start_revision_id first, i.e.
470
              start at the most recent revision and go backwards in history
3949.3.3 by Ian Clatworthy
simplify the meaning of forward to be appropriate to this layer
471
            * forward returns tuples in the opposite order to reverse.
472
              Note in particular that forward does *not* do any intelligent
473
              ordering w.r.t. depth as some clients of this API may like.
3949.3.8 by Ian Clatworthy
feedback from poolie
474
              (If required, that ought to be done at higher layers.)
475
476
        :return: an iterator over (revision_id, depth, revno, end_of_merge)
477
            tuples where:
478
479
            * revision_id: the unique id of the revision
480
            * depth: How many levels of merging deep this node has been
481
              found.
482
            * revno_sequence: This field provides a sequence of
483
              revision numbers for all revisions. The format is:
484
              (REVNO, BRANCHNUM, BRANCHREVNO). BRANCHNUM is the number of the
485
              branch that the revno is on. From left to right the REVNO numbers
486
              are the sequence numbers within that branch of the revision.
487
            * end_of_merge: When True the next node (earlier in history) is
488
              part of a different merge.
3949.3.1 by Ian Clatworthy
introduce Branch.merge_sorted_revisions API
489
        """
6754.8.5 by Jelmer Vernooij
Avoid decorators.
490
        with self.lock_read():
491
            # Note: depth and revno values are in the context of the branch so
492
            # we need the full graph to get stable numbers, regardless of the
493
            # start_revision_id.
494
            if self._merge_sorted_revisions_cache is None:
495
                last_revision = self.last_revision()
496
                known_graph = self.repository.get_known_graph_ancestry(
497
                    [last_revision])
498
                self._merge_sorted_revisions_cache = known_graph.merge_sort(
499
                    last_revision)
500
            filtered = self._filter_merge_sorted_revisions(
501
                self._merge_sorted_revisions_cache, start_revision_id,
502
                stop_revision_id, stop_rule)
503
            # Make sure we don't return revisions that are not part of the
504
            # start_revision_id ancestry.
505
            filtered = self._filter_start_non_ancestors(filtered)
506
            if direction == 'reverse':
507
                return filtered
508
            if direction == 'forward':
509
                return reversed(list(filtered))
510
            else:
511
                raise ValueError('invalid direction %r' % direction)
2418.5.12 by John Arbash Meinel
Move functions from BzrBranch to base Branch object.
512
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
513
    def _filter_merge_sorted_revisions(self, merge_sorted_revisions,
3960.3.1 by Ian Clatworthy
add stop_rule to Branch.iter_merge_sorted_revisions()
514
        start_revision_id, stop_revision_id, stop_rule):
3949.3.7 by Ian Clatworthy
drop seqnum from in-memory cache
515
        """Iterate over an inclusive range of sorted revisions."""
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
516
        rev_iter = iter(merge_sorted_revisions)
517
        if start_revision_id is not None:
4593.5.34 by John Arbash Meinel
Change the KnownGraph.merge_sort api.
518
            for node in rev_iter:
5988.1.2 by Jelmer Vernooij
Fix log.
519
                rev_id = node.key
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
520
                if rev_id != start_revision_id:
521
                    continue
522
                else:
3936.3.30 by Ian Clatworthy
use iter_merge_sorted_revisions() with stop_range feature
523
                    # The decision to include the start or not
524
                    # depends on the stop_rule if a stop is provided
4593.5.34 by John Arbash Meinel
Change the KnownGraph.merge_sort api.
525
                    # so pop this node back into the iterator
6105.1.1 by Jelmer Vernooij
Fix "pydoc bzrlib.branch" by importing modules, not objects, using lazy_import.
526
                    rev_iter = itertools.chain(iter([node]), rev_iter)
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
527
                    break
3960.3.1 by Ian Clatworthy
add stop_rule to Branch.iter_merge_sorted_revisions()
528
        if stop_revision_id is None:
4593.5.34 by John Arbash Meinel
Change the KnownGraph.merge_sort api.
529
            # Yield everything
530
            for node in rev_iter:
5988.1.2 by Jelmer Vernooij
Fix log.
531
                rev_id = node.key
4593.5.34 by John Arbash Meinel
Change the KnownGraph.merge_sort api.
532
                yield (rev_id, node.merge_depth, node.revno,
533
                       node.end_of_merge)
3960.3.1 by Ian Clatworthy
add stop_rule to Branch.iter_merge_sorted_revisions()
534
        elif stop_rule == 'exclude':
4593.5.34 by John Arbash Meinel
Change the KnownGraph.merge_sort api.
535
            for node in rev_iter:
5988.1.2 by Jelmer Vernooij
Fix log.
536
                rev_id = node.key
3960.3.1 by Ian Clatworthy
add stop_rule to Branch.iter_merge_sorted_revisions()
537
                if rev_id == stop_revision_id:
538
                    return
4593.5.34 by John Arbash Meinel
Change the KnownGraph.merge_sort api.
539
                yield (rev_id, node.merge_depth, node.revno,
540
                       node.end_of_merge)
3960.3.1 by Ian Clatworthy
add stop_rule to Branch.iter_merge_sorted_revisions()
541
        elif stop_rule == 'include':
4593.5.34 by John Arbash Meinel
Change the KnownGraph.merge_sort api.
542
            for node in rev_iter:
5988.1.2 by Jelmer Vernooij
Fix log.
543
                rev_id = node.key
4593.5.34 by John Arbash Meinel
Change the KnownGraph.merge_sort api.
544
                yield (rev_id, node.merge_depth, node.revno,
545
                       node.end_of_merge)
3960.3.1 by Ian Clatworthy
add stop_rule to Branch.iter_merge_sorted_revisions()
546
                if rev_id == stop_revision_id:
547
                    return
5097.1.11 by Vincent Ladeuil
Fix bug #320119 in a crude way.
548
        elif stop_rule == 'with-merges-without-common-ancestry':
549
            # We want to exclude all revisions that are already part of the
550
            # stop_revision_id ancestry.
551
            graph = self.repository.get_graph()
5155.1.3 by Vincent Ladeuil
Fix the performance by finding the relevant subgraph once.
552
            ancestors = graph.find_unique_ancestors(start_revision_id,
553
                                                    [stop_revision_id])
5097.1.11 by Vincent Ladeuil
Fix bug #320119 in a crude way.
554
            for node in rev_iter:
5988.1.2 by Jelmer Vernooij
Fix log.
555
                rev_id = node.key
5155.1.3 by Vincent Ladeuil
Fix the performance by finding the relevant subgraph once.
556
                if rev_id not in ancestors:
5097.1.11 by Vincent Ladeuil
Fix bug #320119 in a crude way.
557
                    continue
558
                yield (rev_id, node.merge_depth, node.revno,
559
                       node.end_of_merge)
3960.3.1 by Ian Clatworthy
add stop_rule to Branch.iter_merge_sorted_revisions()
560
        elif stop_rule == 'with-merges':
3960.3.4 by Ian Clatworthy
implement with-merges by checking for left-hand parent, not depth
561
            stop_rev = self.repository.get_revision(stop_revision_id)
562
            if stop_rev.parent_ids:
4511.3.15 by Marius Kruger
mainline_stop_rev -> left_parent
563
                left_parent = stop_rev.parent_ids[0]
3960.3.4 by Ian Clatworthy
implement with-merges by checking for left-hand parent, not depth
564
            else:
4511.3.15 by Marius Kruger
mainline_stop_rev -> left_parent
565
                left_parent = _mod_revision.NULL_REVISION
566
            # left_parent is the actual revision we want to stop logging at,
567
            # since we want to show the merged revisions after the stop_rev too
4511.3.10 by Marius Kruger
log -n0 should log up until the stop_revision with its meges and no further.
568
            reached_stop_revision_id = False
4511.3.12 by Marius Kruger
ununinvert logic and improve some variable names.
569
            revision_id_whitelist = []
4593.5.34 by John Arbash Meinel
Change the KnownGraph.merge_sort api.
570
            for node in rev_iter:
5988.1.2 by Jelmer Vernooij
Fix log.
571
                rev_id = node.key
4511.3.15 by Marius Kruger
mainline_stop_rev -> left_parent
572
                if rev_id == left_parent:
573
                    # reached the left parent after the stop_revision
3960.3.1 by Ian Clatworthy
add stop_rule to Branch.iter_merge_sorted_revisions()
574
                    return
4511.3.12 by Marius Kruger
ununinvert logic and improve some variable names.
575
                if (not reached_stop_revision_id or
576
                        rev_id in revision_id_whitelist):
4511.3.10 by Marius Kruger
log -n0 should log up until the stop_revision with its meges and no further.
577
                    yield (rev_id, node.merge_depth, node.revno,
4593.5.34 by John Arbash Meinel
Change the KnownGraph.merge_sort api.
578
                       node.end_of_merge)
4511.3.10 by Marius Kruger
log -n0 should log up until the stop_revision with its meges and no further.
579
                    if reached_stop_revision_id or rev_id == stop_revision_id:
580
                        # only do the merged revs of rev_id from now on
581
                        rev = self.repository.get_revision(rev_id)
582
                        if rev.parent_ids:
583
                            reached_stop_revision_id = True
4511.3.12 by Marius Kruger
ununinvert logic and improve some variable names.
584
                            revision_id_whitelist.extend(rev.parent_ids)
3960.3.1 by Ian Clatworthy
add stop_rule to Branch.iter_merge_sorted_revisions()
585
        else:
586
            raise ValueError('invalid stop_rule %r' % stop_rule)
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
587
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
588
    def _filter_start_non_ancestors(self, rev_iter):
5097.1.5 by Vincent Ladeuil
First attempt at fixing the bug, fortunately the bug report exhibits an
589
        # If we started from a dotted revno, we want to consider it as a tip
590
        # and don't want to yield revisions that are not part of its
591
        # ancestry. Given the order guaranteed by the merge sort, we will see
592
        # uninteresting descendants of the first parent of our tip before the
593
        # tip itself.
6634.2.1 by Martin
Apply 2to3 next fixer and make compatible
594
        first = next(rev_iter)
5097.1.5 by Vincent Ladeuil
First attempt at fixing the bug, fortunately the bug report exhibits an
595
        (rev_id, merge_depth, revno, end_of_merge) = first
596
        yield first
597
        if not merge_depth:
598
            # We start at a mainline revision so by definition, all others
599
            # revisions in rev_iter are ancestors
600
            for node in rev_iter:
601
                yield node
602
5097.2.2 by Vincent Ladeuil
Fix performance.
603
        clean = False
5097.2.1 by Vincent Ladeuil
Fix bug #474807 but performance suffers.
604
        whitelist = set()
5097.2.3 by Vincent Ladeuil
Better performance than before the fix.
605
        pmap = self.repository.get_parent_map([rev_id])
606
        parents = pmap.get(rev_id, [])
607
        if parents:
608
            whitelist.update(parents)
5097.1.5 by Vincent Ladeuil
First attempt at fixing the bug, fortunately the bug report exhibits an
609
        else:
5097.1.8 by Vincent Ladeuil
Remove the comment about the missing test (it's not worth it at the
610
            # If there is no parents, there is nothing of interest left
611
612
            # FIXME: It's hard to test this scenario here as this code is never
613
            # called in that case. -- vila 20100322
614
            return
615
5097.1.5 by Vincent Ladeuil
First attempt at fixing the bug, fortunately the bug report exhibits an
616
        for (rev_id, merge_depth, revno, end_of_merge) in rev_iter:
5097.2.2 by Vincent Ladeuil
Fix performance.
617
            if not clean:
618
                if rev_id in whitelist:
5097.2.3 by Vincent Ladeuil
Better performance than before the fix.
619
                    pmap = self.repository.get_parent_map([rev_id])
620
                    parents = pmap.get(rev_id, [])
5097.2.2 by Vincent Ladeuil
Fix performance.
621
                    whitelist.remove(rev_id)
5097.2.3 by Vincent Ladeuil
Better performance than before the fix.
622
                    whitelist.update(parents)
5097.2.2 by Vincent Ladeuil
Fix performance.
623
                    if merge_depth == 0:
624
                        # We've reached the mainline, there is nothing left to
625
                        # filter
626
                        clean = True
627
                else:
628
                    # A revision that is not part of the ancestry of our
629
                    # starting revision.
630
                    continue
5097.1.5 by Vincent Ladeuil
First attempt at fixing the bug, fortunately the bug report exhibits an
631
            yield (rev_id, merge_depth, revno, end_of_merge)
632
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
633
    def leave_lock_in_place(self):
634
        """Tell this branch object not to release the physical lock when this
635
        object is unlocked.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
636
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
637
        If lock_write doesn't return a token, then this method is not supported.
638
        """
639
        self.control_files.leave_in_place()
640
641
    def dont_leave_lock_in_place(self):
642
        """Tell this branch object to release the physical lock when this
643
        object is unlocked, even if it didn't originally acquire it.
644
645
        If lock_write doesn't return a token, then this method is not supported.
646
        """
647
        self.control_files.dont_leave_in_place()
648
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
649
    def bind(self, other):
650
        """Bind the local branch the other branch.
651
652
        :param other: The branch to bind to
653
        :type other: Branch
654
        """
5158.6.3 by Martin Pool
Update some Branch calls to use ControlComponent style.
655
        raise errors.UpgradeRequired(self.user_url)
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
656
6123.9.11 by Jelmer Vernooij
Make get_append_revisions_only public.
657
    def get_append_revisions_only(self):
658
        """Whether it is only possible to append revisions to the history.
659
        """
6123.9.14 by Jelmer Vernooij
Fix RemoteBranch.get_append_revisions_only().
660
        if not self._format.supports_set_append_revisions_only():
661
            return False
6372.4.1 by Jelmer Vernooij
Convert 'append_revisions_only' over to config stacks.
662
        return self.get_config_stack().get('append_revisions_only')
6123.9.11 by Jelmer Vernooij
Make get_append_revisions_only public.
663
4301.3.3 by Andrew Bennetts
Move check onto base Branch class, and add a supports_set_append_revisions_only method to BranchFormat, as suggested by Robert.
664
    def set_append_revisions_only(self, enabled):
665
        if not self._format.supports_set_append_revisions_only():
5158.6.3 by Martin Pool
Update some Branch calls to use ControlComponent style.
666
            raise errors.UpgradeRequired(self.user_url)
6372.4.1 by Jelmer Vernooij
Convert 'append_revisions_only' over to config stacks.
667
        self.get_config_stack().set('append_revisions_only', enabled)
4301.3.3 by Andrew Bennetts
Move check onto base Branch class, and add a supports_set_append_revisions_only method to BranchFormat, as suggested by Robert.
668
6926.2.5 by Jelmer Vernooij
Swap order for nested tree functions.
669
    def set_reference_info(self, tree_path, branch_location, file_id=None):
4273.1.1 by Aaron Bentley
Implement branch format for tree references.
670
        """Set the branch location to use for a tree reference."""
671
        raise errors.UnsupportedOperation(self.set_reference_info, self)
672
6926.2.5 by Jelmer Vernooij
Swap order for nested tree functions.
673
    def get_reference_info(self, path):
4273.1.1 by Aaron Bentley
Implement branch format for tree references.
674
        """Get the tree_path and branch_location for a tree reference."""
675
        raise errors.UnsupportedOperation(self.get_reference_info, self)
676
5852.1.1 by Jelmer Vernooij
Add limit argument to Branch.fetch.
677
    def fetch(self, from_branch, last_revision=None, limit=None):
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
678
        """Copy revisions from from_branch into this branch.
679
680
        :param from_branch: Where to copy from.
681
        :param last_revision: What revision to stop at (None for at the end
682
                              of the branch.
5852.1.1 by Jelmer Vernooij
Add limit argument to Branch.fetch.
683
        :param limit: Optional rough limit of revisions to fetch
4065.1.1 by Robert Collins
Change the return value of fetch() to None.
684
        :return: None
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
685
        """
6754.8.13 by Jelmer Vernooij
Avoid needs_write_lock.
686
        with self.lock_write():
687
            return InterBranch.get(from_branch, self).fetch(
688
                    last_revision, limit=limit)
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
689
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
690
    def get_bound_location(self):
1558.7.6 by Aaron Bentley
Fixed typo (Olaf Conradi)
691
        """Return the URL of the branch we are bound to.
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
692
693
        Older format branches cannot bind, please be sure to use a metadir
694
        branch.
695
        """
696
        return None
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
697
2230.3.31 by Aaron Bentley
Implement re-binding previously-bound branches
698
    def get_old_bound_location(self):
699
        """Return the URL of the branch we used to be bound to
700
        """
5158.6.3 by Martin Pool
Update some Branch calls to use ControlComponent style.
701
        raise errors.UpgradeRequired(self.user_url)
2230.3.31 by Aaron Bentley
Implement re-binding previously-bound branches
702
6351.3.2 by Jelmer Vernooij
Convert some gpg options to config stacks.
703
    def get_commit_builder(self, parents, config_stack=None, timestamp=None,
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
704
                           timezone=None, committer=None, revprops=None,
5777.6.1 by Jelmer Vernooij
Add --lossy option to 'bzr commit'.
705
                           revision_id=None, lossy=False):
1740.3.7 by Jelmer Vernooij
Move committer, log, revprops, timestamp and timezone to CommitBuilder.
706
        """Obtain a CommitBuilder for this branch.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
707
1740.3.7 by Jelmer Vernooij
Move committer, log, revprops, timestamp and timezone to CommitBuilder.
708
        :param parents: Revision ids of the parents of the new revision.
709
        :param config: Optional configuration to use.
710
        :param timestamp: Optional timestamp recorded for commit.
711
        :param timezone: Optional timezone for timestamp.
712
        :param committer: Optional committer to set for commit.
713
        :param revprops: Optional dictionary of revision properties.
714
        :param revision_id: Optional revision id.
5777.6.1 by Jelmer Vernooij
Add --lossy option to 'bzr commit'.
715
        :param lossy: Whether to discard data that can not be natively
716
            represented, when pushing to a foreign VCS 
1740.3.7 by Jelmer Vernooij
Move committer, log, revprops, timestamp and timezone to CommitBuilder.
717
        """
718
6351.3.2 by Jelmer Vernooij
Convert some gpg options to config stacks.
719
        if config_stack is None:
720
            config_stack = self.get_config_stack()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
721
6351.3.2 by Jelmer Vernooij
Convert some gpg options to config stacks.
722
        return self.repository.get_commit_builder(self, parents, config_stack,
5777.6.1 by Jelmer Vernooij
Add --lossy option to 'bzr commit'.
723
            timestamp, timezone, committer, revprops, revision_id,
724
            lossy)
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
725
2810.2.1 by Martin Pool
merge vincent and cleanup
726
    def get_master_branch(self, possible_transports=None):
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
727
        """Return the branch we are bound to.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
728
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
729
        :return: Either a Branch, or None
730
        """
731
        return None
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
732
3537.3.1 by Martin Pool
Rename branch.get_stacked_on to get_stacked_on_url
733
    def get_stacked_on_url(self):
3221.11.2 by Robert Collins
Create basic stackable branch facility.
734
        """Get the URL this branch is stacked against.
735
736
        :raises NotStacked: If the branch is not stacked.
737
        :raises UnstackableBranchFormat: If the branch does not support
738
            stacking.
739
        """
3537.3.1 by Martin Pool
Rename branch.get_stacked_on to get_stacked_on_url
740
        raise NotImplementedError(self.get_stacked_on_url)
3221.11.2 by Robert Collins
Create basic stackable branch facility.
741
5718.8.2 by Jelmer Vernooij
Split out full history branch code.
742
    def set_last_revision_info(self, revno, revision_id):
5718.8.3 by Jelmer Vernooij
More branch restructuring.
743
        """Set the last revision of this branch.
744
745
        The caller is responsible for checking that the revno is correct
746
        for this revision id.
747
748
        It may be possible to set the branch last revision to an id not
749
        present in the repository.  However, branches can also be
750
        configured to check constraints on history, in which case this may not
751
        be permitted.
752
        """
5883.1.1 by Jelmer Vernooij
Fix NotImplementedError contents.
753
        raise NotImplementedError(self.set_last_revision_info)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
754
5718.8.6 by Jelmer Vernooij
Move generate_revision_history.
755
    def generate_revision_history(self, revision_id, last_rev=None,
756
                                  other_branch=None):
5718.8.18 by Jelmer Vernooij
Translate local set_rh calls to remote set_rh calls.
757
        """See Branch.generate_revision_history"""
6754.8.13 by Jelmer Vernooij
Avoid needs_write_lock.
758
        with self.lock_write():
759
            graph = self.repository.get_graph()
760
            (last_revno, last_revid) = self.last_revision_info()
761
            known_revision_ids = [
762
                (last_revid, last_revno),
763
                (_mod_revision.NULL_REVISION, 0),
764
                ]
765
            if last_rev is not None:
766
                if not graph.is_ancestor(last_rev, revision_id):
767
                    # our previous tip is not merged into stop_revision
768
                    raise errors.DivergedBranches(self, other_branch)
769
            revno = graph.find_distance_to_null(revision_id, known_revision_ids)
770
            self.set_last_revision_info(revno, revision_id)
5718.8.6 by Jelmer Vernooij
Move generate_revision_history.
771
4288.1.4 by Robert Collins
Remove the explicit set_parent method on RemoteBranch in favour of inheriting from Branch.
772
    def set_parent(self, url):
773
        """See Branch.set_parent."""
774
        # TODO: Maybe delete old location files?
775
        # URLs should never be unicode, even on the local fs,
776
        # FIXUP this and get_parent in a future branch format bump:
777
        # read and rewrite the file. RBC 20060125
778
        if url is not None:
6973.5.13 by Jelmer Vernooij
Add notes about cleanups.
779
            # TODO(jelmer): Clean this up for pad.lv/1696545
6973.5.10 by Jelmer Vernooij
Random bunch of python3 bee-improvements.
780
            if isinstance(url, text_type) and sys.version_info[0] == 2:
4288.1.4 by Robert Collins
Remove the explicit set_parent method on RemoteBranch in favour of inheriting from Branch.
781
                try:
782
                    url = url.encode('ascii')
783
                except UnicodeEncodeError:
6729.6.1 by Jelmer Vernooij
Move urlutils errors.
784
                    raise urlutils.InvalidURL(url,
4288.1.4 by Robert Collins
Remove the explicit set_parent method on RemoteBranch in favour of inheriting from Branch.
785
                        "Urls must be 7-bit ascii, "
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
786
                        "use breezy.urlutils.escape")
4288.1.4 by Robert Collins
Remove the explicit set_parent method on RemoteBranch in favour of inheriting from Branch.
787
            url = urlutils.relative_url(self.base, url)
6754.8.13 by Jelmer Vernooij
Avoid needs_write_lock.
788
        with self.lock_write():
789
            self._set_parent_location(url)
4288.1.4 by Robert Collins
Remove the explicit set_parent method on RemoteBranch in favour of inheriting from Branch.
790
3537.3.3 by Martin Pool
Rename Branch.set_stacked_on to set_stacked_on_url
791
    def set_stacked_on_url(self, url):
3221.18.1 by Ian Clatworthy
tweaks by ianc during review
792
        """Set the URL this branch is stacked against.
3221.11.2 by Robert Collins
Create basic stackable branch facility.
793
794
        :raises UnstackableBranchFormat: If the branch does not support
795
            stacking.
796
        :raises UnstackableRepositoryFormat: If the repository does not support
797
            stacking.
798
        """
4226.1.3 by Robert Collins
Lift Branch.set_stacked_on_url up from BzrBranch7.
799
        if not self._format.supports_stacking():
6734.1.11 by Jelmer Vernooij
Move UnstackableBranchFormat.
800
            raise UnstackableBranchFormat(self._format, self.user_url)
6754.8.13 by Jelmer Vernooij
Avoid needs_write_lock.
801
        with self.lock_write():
802
            # XXX: Changing from one fallback repository to another does not check
803
            # that all the data you need is present in the new fallback.
804
            # Possibly it should.
805
            self._check_stackable_repo()
806
            if not url:
807
                try:
808
                    old_url = self.get_stacked_on_url()
809
                except (errors.NotStacked, UnstackableBranchFormat,
810
                    errors.UnstackableRepositoryFormat):
811
                    return
812
                self._unstack()
813
            else:
814
                self._activate_fallback_location(url,
815
                    possible_transports=[self.controldir.root_transport])
816
            # write this out after the repository is stacked to avoid setting a
817
            # stacked config that doesn't work.
818
            self._set_config_location('stacked_on_location', url)
4226.1.3 by Robert Collins
Lift Branch.set_stacked_on_url up from BzrBranch7.
819
4509.3.9 by Martin Pool
Split out Branch._unstack
820
    def _unstack(self):
821
        """Change a branch to be unstacked, copying data as needed.
5697.2.1 by Jelmer Vernooij
Move weave branch to bzrlib.branch_weave.
822
4509.3.9 by Martin Pool
Split out Branch._unstack
823
        Don't call this directly, use set_stacked_on_url(None).
824
        """
6861.4.1 by Jelmer Vernooij
Make progress bars context managers.
825
        with ui.ui_factory.nested_progress_bar() as pb:
6138.4.1 by Jonathan Riddell
add gettext to progress bar strings
826
            pb.update(gettext("Unstacking"))
4509.3.16 by Martin Pool
Unstack by fetching from the stacked repository combination, not just the fallback.
827
            # The basic approach here is to fetch the tip of the branch,
828
            # including all available ghosts, from the existing stacked
829
            # repository into a new repository object without the fallbacks. 
830
            #
831
            # XXX: See <https://launchpad.net/bugs/397286> - this may not be
832
            # correct for CHKMap repostiories
833
            old_repository = self.repository
834
            if len(old_repository._fallback_repositories) != 1:
4509.3.9 by Martin Pool
Split out Branch._unstack
835
                raise AssertionError("can't cope with fallback repositories "
5536.1.1 by Andrew Bennetts
Avoid reopening (and relocking) the same branches/repositories in ControlDir.sprout. Still a few rough edges, but the tests I've run are passing.
836
                    "of %r (fallbacks: %r)" % (old_repository,
837
                        old_repository._fallback_repositories))
5325.1.3 by Andrew Bennetts
Try harder to preserve lock-count in _unstack, and add special-case to replace self._real_branch.repository as well as self.repository for remote branches.
838
            # Open the new repository object.
839
            # Repositories don't offer an interface to remove fallback
840
            # repositories today; take the conceptually simpler option and just
841
            # reopen it.  We reopen it starting from the URL so that we
842
            # get a separate connection for RemoteRepositories and can
843
            # stream from one of them to the other.  This does mean doing
844
            # separate SSH connection setup, but unstacking is not a
845
            # common operation so it's tolerable.
6207.3.3 by jelmer at samba
Fix tests and the like.
846
            new_bzrdir = controldir.ControlDir.open(
6653.6.1 by Jelmer Vernooij
Rename a number of attributes from bzrdir to controldir.
847
                self.controldir.root_transport.base)
5325.1.3 by Andrew Bennetts
Try harder to preserve lock-count in _unstack, and add special-case to replace self._real_branch.repository as well as self.repository for remote branches.
848
            new_repository = new_bzrdir.find_repository()
849
            if new_repository._fallback_repositories:
850
                raise AssertionError("didn't expect %r to have "
851
                    "fallback_repositories"
852
                    % (self.repository,))
5325.1.4 by Andrew Bennetts
Improve comments.
853
            # Replace self.repository with the new repository.
854
            # Do our best to transfer the lock state (i.e. lock-tokens and
5325.1.3 by Andrew Bennetts
Try harder to preserve lock-count in _unstack, and add special-case to replace self._real_branch.repository as well as self.repository for remote branches.
855
            # lock count) of self.repository to the new repository.
856
            lock_token = old_repository.lock_write().repository_token
857
            self.repository = new_repository
858
            if isinstance(self, remote.RemoteBranch):
5325.1.4 by Andrew Bennetts
Improve comments.
859
                # Remote branches can have a second reference to the old
860
                # repository that need to be replaced.
5325.1.3 by Andrew Bennetts
Try harder to preserve lock-count in _unstack, and add special-case to replace self._real_branch.repository as well as self.repository for remote branches.
861
                if self._real_branch is not None:
862
                    self._real_branch.repository = new_repository
863
            self.repository.lock_write(token=lock_token)
864
            if lock_token is not None:
865
                old_repository.leave_lock_in_place()
4509.3.16 by Martin Pool
Unstack by fetching from the stacked repository combination, not just the fallback.
866
            old_repository.unlock()
5325.1.3 by Andrew Bennetts
Try harder to preserve lock-count in _unstack, and add special-case to replace self._real_branch.repository as well as self.repository for remote branches.
867
            if lock_token is not None:
868
                # XXX: self.repository.leave_lock_in_place() before this
869
                # function will not be preserved.  Fortunately that doesn't
5325.1.4 by Andrew Bennetts
Improve comments.
870
                # affect the current default format (2a), and would be a
871
                # corner-case anyway.
5325.1.3 by Andrew Bennetts
Try harder to preserve lock-count in _unstack, and add special-case to replace self._real_branch.repository as well as self.repository for remote branches.
872
                #  - Andrew Bennetts, 2010/06/30
873
                self.repository.dont_leave_lock_in_place()
874
            old_lock_count = 0
875
            while True:
876
                try:
877
                    old_repository.unlock()
878
                except errors.LockNotHeld:
879
                    break
880
                old_lock_count += 1
881
            if old_lock_count == 0:
882
                raise AssertionError(
883
                    'old_repository should have been locked at least once.')
884
            for i in range(old_lock_count-1):
885
                self.repository.lock_write()
886
            # Fetch from the old repository into the new.
6754.8.4 by Jelmer Vernooij
Use new context stuff.
887
            with old_repository.lock_read():
4509.3.16 by Martin Pool
Unstack by fetching from the stacked repository combination, not just the fallback.
888
                # XXX: If you unstack a branch while it has a working tree
889
                # with a pending merge, the pending-merged revisions will no
890
                # longer be present.  You can (probably) revert and remerge.
5651.5.1 by Andrew Bennetts
Make 'bzr reconfigure --unstacked' fetch tagged revisions too. (#401646)
891
                try:
892
                    tags_to_fetch = set(self.tags.get_reverse_tag_dict())
893
                except errors.TagsNotSupported:
894
                    tags_to_fetch = set()
6341.1.4 by Jelmer Vernooij
Move more functionality to vf_search.
895
                fetch_spec = vf_search.NotInOtherForRevs(self.repository,
5651.5.1 by Andrew Bennetts
Make 'bzr reconfigure --unstacked' fetch tagged revisions too. (#401646)
896
                    old_repository, required_ids=[self.last_revision()],
897
                    if_present_ids=tags_to_fetch, find_ghosts=True).execute()
898
                self.repository.fetch(old_repository, fetch_spec=fetch_spec)
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
899
2375.1.3 by Andrew Bennetts
Don't use Branch.get_transaction to cache revision history.
900
    def _cache_revision_history(self, rev_history):
901
        """Set the cached revision history to rev_history.
902
903
        The revision_history method will use this cache to avoid regenerating
904
        the revision history.
905
906
        This API is semi-public; it only for use by subclasses, all other code
907
        should consider it to be private.
908
        """
909
        self._revision_history_cache = rev_history
910
2418.5.6 by John Arbash Meinel
Cache the revision_id => revno map as appropriate.
911
    def _cache_revision_id_to_revno(self, revision_id_to_revno):
912
        """Set the cached revision_id => revno map to revision_id_to_revno.
913
914
        This API is semi-public; it only for use by subclasses, all other code
915
        should consider it to be private.
916
        """
917
        self._revision_id_to_revno_cache = revision_id_to_revno
918
2375.1.6 by Andrew Bennetts
Rename _clear_cached_data to _clear_cached_state.
919
    def _clear_cached_state(self):
2375.1.5 by Andrew Bennetts
Deal with review comments from Robert:
920
        """Clear any cached data on this branch, e.g. cached revision history.
2375.1.3 by Andrew Bennetts
Don't use Branch.get_transaction to cache revision history.
921
922
        This means the next call to revision_history will need to call
923
        _gen_revision_history.
924
6499.2.1 by Vincent Ladeuil
Save branch config options only during the final unlock
925
        This API is semi-public; it is only for use by subclasses, all other
926
        code should consider it to be private.
2375.1.3 by Andrew Bennetts
Don't use Branch.get_transaction to cache revision history.
927
        """
928
        self._revision_history_cache = None
2418.5.6 by John Arbash Meinel
Cache the revision_id => revno map as appropriate.
929
        self._revision_id_to_revno_cache = None
3441.5.27 by Andrew Bennetts
Tweaks suggested by John's review: rename _check_if_descendant_or_diverged, move caching last_revision_info into base Branch, better use of lock decorators.
930
        self._last_revision_info_cache = None
5609.25.3 by Andrew Bennetts
Alternative fix: cache the result of get_master_branch for the lifetime of the branch lock.
931
        self._master_branch_cache = None
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
932
        self._merge_sorted_revisions_cache = None
4419.2.1 by Andrew Bennetts
Move _extend_partial_history into Branch base class, and use it in get_rev_id rather than self.revision_history().
933
        self._partial_revision_history_cache = []
934
        self._partial_revision_id_to_revno_cache = {}
2375.1.3 by Andrew Bennetts
Don't use Branch.get_transaction to cache revision history.
935
936
    def _gen_revision_history(self):
937
        """Return sequence of revision hashes on to this branch.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
938
2375.1.3 by Andrew Bennetts
Don't use Branch.get_transaction to cache revision history.
939
        Unlike revision_history, this method always regenerates or rereads the
940
        revision history, i.e. it does not cache the result, so repeated calls
941
        may be expensive.
942
2375.1.5 by Andrew Bennetts
Deal with review comments from Robert:
943
        Concrete subclasses should override this instead of revision_history so
944
        that subclasses do not need to deal with caching logic.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
945
2375.1.3 by Andrew Bennetts
Don't use Branch.get_transaction to cache revision history.
946
        This API is semi-public; it only for use by subclasses, all other code
947
        should consider it to be private.
948
        """
949
        raise NotImplementedError(self._gen_revision_history)
950
6165.4.2 by Jelmer Vernooij
Deprecate revision_history.
951
    def _revision_history(self):
2592.3.113 by Robert Collins
Various -Devil checks in branch.py.
952
        if 'evil' in debug.debug_flags:
953
            mutter_callsite(3, "revision_history scales with history.")
2375.1.3 by Andrew Bennetts
Don't use Branch.get_transaction to cache revision history.
954
        if self._revision_history_cache is not None:
2375.1.5 by Andrew Bennetts
Deal with review comments from Robert:
955
            history = self._revision_history_cache
956
        else:
957
            history = self._gen_revision_history()
958
            self._cache_revision_history(history)
2375.1.3 by Andrew Bennetts
Don't use Branch.get_transaction to cache revision history.
959
        return list(history)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
960
961
    def revno(self):
962
        """Return current revision number for this branch.
963
964
        That is equivalent to the number of revisions committed to
965
        this branch.
966
        """
3066.1.1 by John Arbash Meinel
Make the default Branch.revno() implementation just be a thunk to last_revision_info.
967
        return self.last_revision_info()[0]
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
968
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
969
    def unbind(self):
970
        """Older format branches cannot bind or unbind."""
5158.6.3 by Martin Pool
Update some Branch calls to use ControlComponent style.
971
        raise errors.UpgradeRequired(self.user_url)
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
972
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
973
    def last_revision(self):
3211.2.1 by Robert Collins
* Creating a new branch no longer tries to read the entire revision-history
974
        """Return last revision id, or NULL_REVISION."""
975
        return self.last_revision_info()[1]
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
976
2249.4.1 by Wouter van Heyst
New Branch.last_revision_info method, this is being done to allow
977
    def last_revision_info(self):
978
        """Return information about the last revision.
979
3441.5.27 by Andrew Bennetts
Tweaks suggested by John's review: rename _check_if_descendant_or_diverged, move caching last_revision_info into base Branch, better use of lock decorators.
980
        :return: A tuple (revno, revision_id).
2249.4.1 by Wouter van Heyst
New Branch.last_revision_info method, this is being done to allow
981
        """
6754.8.7 by Jelmer Vernooij
Fix syntax errors.
982
        with self.lock_read():
6754.8.5 by Jelmer Vernooij
Avoid decorators.
983
            if self._last_revision_info_cache is None:
984
                self._last_revision_info_cache = self._read_last_revision_info()
985
            return self._last_revision_info_cache
3441.5.27 by Andrew Bennetts
Tweaks suggested by John's review: rename _check_if_descendant_or_diverged, move caching last_revision_info into base Branch, better use of lock decorators.
986
5718.8.2 by Jelmer Vernooij
Split out full history branch code.
987
    def _read_last_revision_info(self):
5718.8.3 by Jelmer Vernooij
More branch restructuring.
988
        raise NotImplementedError(self._read_last_revision_info)
2249.4.1 by Wouter van Heyst
New Branch.last_revision_info method, this is being done to allow
989
5777.7.1 by Jelmer Vernooij
Add lossy argument to Branch.import_last_revision_info_and_tags.
990
    def import_last_revision_info_and_tags(self, source, revno, revid,
991
                                           lossy=False):
5535.3.31 by Andrew Bennetts
Cope with tags that reference missing revisions.
992
        """Set the last revision info, importing from another repo if necessary.
993
994
        This is used by the bound branch code to upload a revision to
995
        the master branch first before updating the tip of the local branch.
996
        Revisions referenced by source's tags are also transferred.
997
5535.3.35 by Andrew Bennetts
Fix deprecation warning from some tests, correct some docstrings.
998
        :param source: Source branch to optionally fetch from
5535.3.31 by Andrew Bennetts
Cope with tags that reference missing revisions.
999
        :param revno: Revision number of the new tip
1000
        :param revid: Revision id of the new tip
5777.7.1 by Jelmer Vernooij
Add lossy argument to Branch.import_last_revision_info_and_tags.
1001
        :param lossy: Whether to discard metadata that can not be
1002
            natively represented
1003
        :return: Tuple with the new revision number and revision id
1004
            (should only be different from the arguments when lossy=True)
5535.3.31 by Andrew Bennetts
Cope with tags that reference missing revisions.
1005
        """
1006
        if not self.repository.has_same_location(source.repository):
5741.1.8 by Jelmer Vernooij
Remove fetch_tags argument.
1007
            self.fetch(source, revid)
5535.3.31 by Andrew Bennetts
Cope with tags that reference missing revisions.
1008
        self.set_last_revision_info(revno, revid)
5777.7.1 by Jelmer Vernooij
Add lossy argument to Branch.import_last_revision_info_and_tags.
1009
        return (revno, revid)
5535.3.31 by Andrew Bennetts
Cope with tags that reference missing revisions.
1010
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1011
    def revision_id_to_revno(self, revision_id):
1012
        """Given a revision id, return its revno"""
2598.5.1 by Aaron Bentley
Start eliminating the use of None to indicate null revision
1013
        if _mod_revision.is_null(revision_id):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1014
            return 0
6165.4.2 by Jelmer Vernooij
Deprecate revision_history.
1015
        history = self._revision_history()
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1016
        try:
1017
            return history.index(revision_id) + 1
1018
        except ValueError:
2418.5.5 by John Arbash Meinel
Add some tests and an api for revision_id_to_dotted_revno
1019
            raise errors.NoSuchRevision(self, revision_id)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1020
1021
    def get_rev_id(self, revno, history=None):
1022
        """Find the revision id of the specified revno."""
6754.8.5 by Jelmer Vernooij
Avoid decorators.
1023
        with self.lock_read():
1024
            if revno == 0:
1025
                return _mod_revision.NULL_REVISION
1026
            last_revno, last_revid = self.last_revision_info()
1027
            if revno == last_revno:
1028
                return last_revid
1029
            if revno <= 0 or revno > last_revno:
1030
                raise errors.NoSuchRevision(self, revno)
1031
            distance_from_last = last_revno - revno
1032
            if len(self._partial_revision_history_cache) <= distance_from_last:
1033
                self._extend_partial_history(distance_from_last)
1034
            return self._partial_revision_history_cache[distance_from_last]
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1035
2817.4.3 by Vincent Ladeuil
Add tests for commit, reuse master branch transport.
1036
    def pull(self, source, overwrite=False, stop_revision=None,
4000.5.21 by Jelmer Vernooij
Merge bzr.dev.
1037
             possible_transports=None, *args, **kwargs):
2245.2.1 by Robert Collins
Split branch pushing out of branch pulling.
1038
        """Mirror source into this branch.
1039
1040
        This branch is considered to be 'local', having low latency.
2297.1.1 by Martin Pool
Pull now returns a PullResult rather than just an integer.
1041
1042
        :returns: PullResult instance
2245.2.1 by Robert Collins
Split branch pushing out of branch pulling.
1043
        """
4000.5.9 by Jelmer Vernooij
Add InterBranch.pull().
1044
        return InterBranch.get(source, self).pull(overwrite=overwrite,
1045
            stop_revision=stop_revision,
1046
            possible_transports=possible_transports, *args, **kwargs)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1047
5853.2.2 by Jelmer Vernooij
Make lossy_push an argument to InterBranch.push.
1048
    def push(self, target, overwrite=False, stop_revision=None, lossy=False,
1049
            *args, **kwargs):
2245.2.1 by Robert Collins
Split branch pushing out of branch pulling.
1050
        """Mirror this branch into target.
1051
1052
        This branch is considered to be 'local', having low latency.
1053
        """
4211.1.3 by Jelmer Vernooij
Fix trailing whitespace, add prototype for InterBranch.push().
1054
        return InterBranch.get(self, target).push(overwrite, stop_revision,
5853.2.2 by Jelmer Vernooij
Make lossy_push an argument to InterBranch.push.
1055
            lossy, *args, **kwargs)
4347.2.1 by Jelmer Vernooij
Move dpush onto an InterBranch object.
1056
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1057
    def basis_tree(self):
1852.5.1 by Robert Collins
Deprecate EmptyTree in favour of using Repository.revision_tree.
1058
        """Return `Tree` object for last revision."""
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
1059
        return self.repository.revision_tree(self.last_revision())
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1060
1061
    def get_parent(self):
1062
        """Return the parent location of the branch.
1063
4031.1.1 by Alexander Belchenko
Parent location is not used as default for push.
1064
        This is the default location for pull/missing.  The usual
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1065
        pattern is that the user can override it by specifying a
1066
        location.
1067
        """
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
1068
        parent = self._get_parent_location()
1069
        if parent is None:
1070
            return parent
1071
        # This is an old-format absolute path to a local branch
1072
        # turn it into a url
1073
        if parent.startswith('/'):
1074
            parent = urlutils.local_path_to_url(parent.decode('utf8'))
1075
        try:
1076
            return urlutils.join(self.base[:-1], parent)
6729.6.1 by Jelmer Vernooij
Move urlutils errors.
1077
        except urlutils.InvalidURLJoin as e:
5158.6.3 by Martin Pool
Update some Branch calls to use ControlComponent style.
1078
            raise errors.InaccessibleParent(parent, self.user_url)
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
1079
1080
    def _get_parent_location(self):
1081
        raise NotImplementedError(self._get_parent_location)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1082
1551.12.44 by Aaron Bentley
Add (set|get)_public_branch
1083
    def _set_config_location(self, name, url, config=None,
1084
                             make_relative=False):
1085
        if config is None:
6379.11.1 by Vincent Ladeuil
Migrate location options to config stacks.
1086
            config = self.get_config_stack()
1551.12.44 by Aaron Bentley
Add (set|get)_public_branch
1087
        if url is None:
1088
            url = ''
1089
        elif make_relative:
1090
            url = urlutils.relative_url(self.base, url)
6379.11.1 by Vincent Ladeuil
Migrate location options to config stacks.
1091
        config.set(name, url)
1551.12.44 by Aaron Bentley
Add (set|get)_public_branch
1092
1093
    def _get_config_location(self, name, config=None):
1094
        if config is None:
6379.11.1 by Vincent Ladeuil
Migrate location options to config stacks.
1095
            config = self.get_config_stack()
1096
        location = config.get(name)
6385.1.6 by Vincent Ladeuil
Remove the now useless hack
1097
        if location == '':
1551.12.44 by Aaron Bentley
Add (set|get)_public_branch
1098
            location = None
1099
        return location
1100
4382.3.1 by Jelmer Vernooij
Add Branch.get_child_submit_format(), so particular Branch implementations
1101
    def get_child_submit_format(self):
1102
        """Return the preferred format of submissions to this branch."""
6421.3.1 by Vincent Ladeuil
Migrate more branch options to config stacks.
1103
        return self.get_config_stack().get('child_submit_format')
4382.3.1 by Jelmer Vernooij
Add Branch.get_child_submit_format(), so particular Branch implementations
1104
1804.1.1 by Aaron Bentley
Add support for submit location to bundles
1105
    def get_submit_branch(self):
1106
        """Return the submit location of the branch.
1107
1108
        This is the default location for bundle.  The usual
1109
        pattern is that the user can override it by specifying a
1110
        location.
1111
        """
6421.3.1 by Vincent Ladeuil
Migrate more branch options to config stacks.
1112
        return self.get_config_stack().get('submit_branch')
1804.1.1 by Aaron Bentley
Add support for submit location to bundles
1113
1114
    def set_submit_branch(self, location):
1115
        """Return the submit location of the branch.
1116
1117
        This is the default location for bundle.  The usual
1118
        pattern is that the user can override it by specifying a
1119
        location.
1120
        """
6421.3.1 by Vincent Ladeuil
Migrate more branch options to config stacks.
1121
        self.get_config_stack().set('submit_branch', location)
1804.1.1 by Aaron Bentley
Add support for submit location to bundles
1122
1551.12.44 by Aaron Bentley
Add (set|get)_public_branch
1123
    def get_public_branch(self):
1124
        """Return the public location of the branch.
1125
4031.3.1 by Frank Aspell
Fixing various typos
1126
        This is used by merge directives.
1551.12.44 by Aaron Bentley
Add (set|get)_public_branch
1127
        """
1128
        return self._get_config_location('public_branch')
1129
1130
    def set_public_branch(self, location):
1131
        """Return the submit location of the branch.
1132
1133
        This is the default location for bundle.  The usual
1134
        pattern is that the user can override it by specifying a
1135
        location.
1136
        """
1137
        self._set_config_location('public_branch', location)
1138
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1139
    def get_push_location(self):
6421.3.1 by Vincent Ladeuil
Migrate more branch options to config stacks.
1140
        """Return None or the location to push this branch to."""
1141
        return self.get_config_stack().get('push_location')
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1142
1143
    def set_push_location(self, location):
1144
        """Set a new push location for this branch."""
1910.3.2 by Andrew Bennetts
Improve some NotImplementedErrors.
1145
        raise NotImplementedError(self.set_push_location)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1146
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
1147
    def _run_post_change_branch_tip_hooks(self, old_revno, old_revid):
1148
        """Run the post_change_branch_tip hooks."""
1149
        hooks = Branch.hooks['post_change_branch_tip']
1150
        if not hooks:
1151
            return
1152
        new_revno, new_revid = self.last_revision_info()
1153
        params = ChangeBranchTipParams(
1154
            self, old_revno, new_revno, old_revid, new_revid)
1155
        for hook in hooks:
1156
            hook(params)
1157
1158
    def _run_pre_change_branch_tip_hooks(self, new_revno, new_revid):
1159
        """Run the pre_change_branch_tip hooks."""
1160
        hooks = Branch.hooks['pre_change_branch_tip']
1161
        if not hooks:
1162
            return
1163
        old_revno, old_revid = self.last_revision_info()
1164
        params = ChangeBranchTipParams(
1165
            self, old_revno, new_revno, old_revid, new_revid)
1166
        for hook in hooks:
4943.1.1 by Robert Collins
Do not fiddle with exceptions in the pre_change_branch_tip hook running code.
1167
            hook(params)
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
1168
1587.1.10 by Robert Collins
update updates working tree and branch together.
1169
    def update(self):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1170
        """Synchronise this branch with the master branch if any.
1587.1.10 by Robert Collins
update updates working tree and branch together.
1171
1172
        :return: None or the last_revision pivoted out during the update.
1173
        """
1174
        return None
1175
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1176
    def check_revno(self, revno):
1177
        """\
1178
        Check whether a revno corresponds to any revision.
1179
        Zero (the NULL revision) is considered valid.
1180
        """
1181
        if revno != 0:
1182
            self.check_real_revno(revno)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1183
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1184
    def check_real_revno(self, revno):
1185
        """\
1186
        Check whether a revno corresponds to a real revision.
1187
        Zero (the NULL revision) is considered invalid
1188
        """
1189
        if revno < 1 or revno > self.revno():
3236.1.2 by Michael Hudson
clean up branch.py imports
1190
            raise errors.InvalidRevisionNumber(revno)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1191
6653.6.1 by Jelmer Vernooij
Rename a number of attributes from bzrdir to controldir.
1192
    def clone(self, to_controldir, revision_id=None, repository_policy=None):
1193
        """Clone this branch into to_controldir preserving all semantic values.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1194
4044.1.1 by Robert Collins
Create Branch.create_clone_on_transport helper method to combine bzr and branch creation for push.
1195
        Most API users will want 'create_clone_on_transport', which creates a
1196
        new bzrdir and branch on the fly.
1197
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1198
        revision_id: if not None, the revision history in the new branch will
1199
                     be truncated to end with revision_id.
1200
        """
6653.6.1 by Jelmer Vernooij
Rename a number of attributes from bzrdir to controldir.
1201
        result = to_controldir.create_branch()
6754.8.5 by Jelmer Vernooij
Avoid decorators.
1202
        with self.lock_read(), result.lock_write():
4288.1.8 by Robert Collins
Lock new branches while we configure them in clone and sprout for less lock churn.
1203
            if repository_policy is not None:
1204
                repository_policy.configure_branch(result)
1205
            self.copy_content_into(result, revision_id=revision_id)
1206
        return result
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1207
6653.6.1 by Jelmer Vernooij
Rename a number of attributes from bzrdir to controldir.
1208
    def sprout(self, to_controldir, revision_id=None, repository_policy=None,
6929.14.2 by Jelmer Vernooij
Support --lossy argument to 'brz push'.
1209
            repository=None, lossy=False):
6653.6.1 by Jelmer Vernooij
Rename a number of attributes from bzrdir to controldir.
1210
        """Create a new line of development from the branch, into to_controldir.
3650.2.1 by Aaron Bentley
Fix sprout to honour cloning format
1211
6653.6.1 by Jelmer Vernooij
Rename a number of attributes from bzrdir to controldir.
1212
        to_controldir controls the branch format.
3650.2.1 by Aaron Bentley
Fix sprout to honour cloning format
1213
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1214
        revision_id: if not None, the revision history in the new branch will
1215
                     be truncated to end with revision_id.
1216
        """
4617.3.1 by Robert Collins
Fix test_stacking tests for 2a as a default format. The change to 2a exposed some actual bugs, both in tests and bzrdir/branch code.
1217
        if (repository_policy is not None and
1218
            repository_policy.requires_stacking()):
6653.6.1 by Jelmer Vernooij
Rename a number of attributes from bzrdir to controldir.
1219
            to_controldir._format.require_stacking(_skip_repo=True)
1220
        result = to_controldir.create_branch(repository=repository)
6929.14.2 by Jelmer Vernooij
Support --lossy argument to 'brz push'.
1221
        if lossy:
1222
            raise errors.LossyPushToSameVCS(self, result)
6754.8.5 by Jelmer Vernooij
Avoid decorators.
1223
        with self.lock_read(), result.lock_write():
4288.1.8 by Robert Collins
Lock new branches while we configure them in clone and sprout for less lock churn.
1224
            if repository_policy is not None:
1225
                repository_policy.configure_branch(result)
1226
            self.copy_content_into(result, revision_id=revision_id)
6015.7.1 by John Arbash Meinel
No need to open the master branch just to get its URL.
1227
            master_url = self.get_bound_location()
1228
            if master_url is None:
6874.1.2 by Jelmer Vernooij
Consistently use Branch.user_url.
1229
                result.set_parent(self.user_url)
5816.6.13 by A. S. Budden
Set the parent location to the branch to which we were bound if this is a bound branch.
1230
            else:
6015.7.1 by John Arbash Meinel
No need to open the master branch just to get its URL.
1231
                result.set_parent(master_url)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1232
        return result
1233
2230.3.18 by Aaron Bentley
Handle history sync as a special operation
1234
    def _synchronize_history(self, destination, revision_id):
2230.3.35 by Aaron Bentley
Add documentation for synchonize_history
1235
        """Synchronize last revision and revision history between branches.
1236
1237
        This version is most efficient when the destination is also a
3834.3.1 by Andrew Bennetts
Get rid of revision_history() call during copy_content_into.
1238
        BzrBranch6, but works for BzrBranch5, as long as the destination's
1239
        repository contains all the lefthand ancestors of the intended
1240
        last_revision.  If not, set_last_revision_info will fail.
2230.3.35 by Aaron Bentley
Add documentation for synchonize_history
1241
1242
        :param destination: The branch to copy the history into
1243
        :param revision_id: The revision-id to truncate history at.  May
1244
          be None to copy complete history.
1245
        """
3834.3.1 by Andrew Bennetts
Get rid of revision_history() call during copy_content_into.
1246
        source_revno, source_revision_id = self.last_revision_info()
1247
        if revision_id is None:
1248
            revno, revision_id = source_revno, source_revision_id
3650.3.3 by Aaron Bentley
fix sprout
1249
        else:
4266.3.8 by Jelmer Vernooij
Consistently use find_distance_to_null.
1250
            graph = self.repository.get_graph()
4266.3.1 by Jelmer Vernooij
Support cloning of branches with ghosts in the left hand side history.
1251
            try:
4266.3.8 by Jelmer Vernooij
Consistently use find_distance_to_null.
1252
                revno = graph.find_distance_to_null(revision_id, 
1253
                    [(source_revision_id, source_revno)])
1254
            except errors.GhostRevisionsHaveNoRevno:
1255
                # Default to 1, if we can't find anything else
1256
                revno = 1
3834.3.1 by Andrew Bennetts
Get rid of revision_history() call during copy_content_into.
1257
        destination.set_last_revision_info(revno, revision_id)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1258
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1259
    def copy_content_into(self, destination, revision_id=None):
1260
        """Copy the content of self into destination.
1261
1262
        revision_id: if not None, the revision history in the new branch will
1263
                     be truncated to end with revision_id.
1264
        """
5284.4.2 by Robert Collins
* ``Branch.copy_content_into`` is now a convenience method dispatching to
1265
        return InterBranch.get(self, destination).copy_content_into(
1266
            revision_id=revision_id)
4273.1.6 by Aaron Bentley
Ensure references are rebased.
1267
1268
    def update_references(self, target):
4273.1.8 by Aaron Bentley
Handle references in push, pull, merge.
1269
        if not getattr(self._format, 'supports_reference_locations', False):
1270
            return
4273.1.11 by Aaron Bentley
Clean up naming and docstrings
1271
        reference_dict = self._get_all_reference_info()
4273.1.9 by Aaron Bentley
Cleanup
1272
        if len(reference_dict) == 0:
1273
            return
4273.1.6 by Aaron Bentley
Ensure references are rebased.
1274
        old_base = self.base
1275
        new_base = target.base
4273.1.11 by Aaron Bentley
Clean up naming and docstrings
1276
        target_reference_dict = target._get_all_reference_info()
6926.2.5 by Jelmer Vernooij
Swap order for nested tree functions.
1277
        for tree_path, (branch_location, file_id) in viewitems(reference_dict):
4273.1.6 by Aaron Bentley
Ensure references are rebased.
1278
            branch_location = urlutils.rebase_url(branch_location,
1279
                                                  old_base, new_base)
4273.1.7 by Aaron Bentley
Make update_references do a merge.
1280
            target_reference_dict.setdefault(
6926.2.5 by Jelmer Vernooij
Swap order for nested tree functions.
1281
                tree_path, (branch_location, file_id))
4273.1.11 by Aaron Bentley
Clean up naming and docstrings
1282
        target._set_all_reference_info(target_reference_dict)
1185.66.1 by Aaron Bentley
Merged from mainline
1283
4332.3.7 by Robert Collins
Convert Branch.check to take a refs dict as well.
1284
    def check(self, refs):
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
1285
        """Check consistency of the branch.
1286
1287
        In particular this checks that revisions given in the revision-history
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1288
        do actually match up in the revision graph, and that they're all
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
1289
        present in the repository.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1290
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
1291
        Callers will typically also want to check the repository.
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
1292
4332.3.7 by Robert Collins
Convert Branch.check to take a refs dict as well.
1293
        :param refs: Calculated refs for this branch as specified by
1294
            branch._get_check_refs()
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
1295
        :return: A BranchCheckResult.
1296
        """
6754.8.5 by Jelmer Vernooij
Avoid decorators.
1297
        with self.lock_read():
1298
            result = BranchCheckResult(self)
1299
            last_revno, last_revision_id = self.last_revision_info()
1300
            actual_revno = refs[('lefthand-distance', last_revision_id)]
1301
            if actual_revno != last_revno:
1302
                result.errors.append(errors.BzrCheckError(
1303
                    'revno does not match len(mainline) %s != %s' % (
1304
                    last_revno, actual_revno)))
1305
            # TODO: We should probably also check that self.revision_history
1306
            # matches the repository for older branch formats.
1307
            # If looking for the code that cross-checks repository parents against
1308
            # the Graph.iter_lefthand_ancestry output, that is now a repository
1309
            # specific check.
1310
            return result
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
1311
6127.1.9 by Jelmer Vernooij
Add lightweight option to _get_checkout_format().
1312
    def _get_checkout_format(self, lightweight=False):
1910.2.39 by Aaron Bentley
Fix checkout bug
1313
        """Return the most suitable metadir for a checkout of this branch.
2018.5.87 by Andrew Bennetts
Make make_branch_and_tree fall back to creating a local checkout if the transport doesn't support working trees, allowing several more Remote tests to pass.
1314
        Weaves are used if this branch's repository uses weaves.
1910.2.39 by Aaron Bentley
Fix checkout bug
1315
        """
6653.6.1 by Jelmer Vernooij
Rename a number of attributes from bzrdir to controldir.
1316
        format = self.repository.controldir.checkout_metadir()
5582.10.3 by Jelmer Vernooij
Remove custom code for presplitout.
1317
        format.set_branch_format(self._format)
1910.2.39 by Aaron Bentley
Fix checkout bug
1318
        return format
1319
4044.1.1 by Robert Collins
Create Branch.create_clone_on_transport helper method to combine bzr and branch creation for push.
1320
    def create_clone_on_transport(self, to_transport, revision_id=None,
5448.6.1 by Matthew Gordon
Added --no-tree option to pull. Needs testing and help text.
1321
        stacked_on=None, create_prefix=False, use_existing_dir=False,
1322
        no_tree=None):
4044.1.1 by Robert Collins
Create Branch.create_clone_on_transport helper method to combine bzr and branch creation for push.
1323
        """Create a clone of this branch and its bzrdir.
1324
1325
        :param to_transport: The transport to clone onto.
1326
        :param revision_id: The revision id to use as tip in the new branch.
1327
            If None the tip is obtained from this branch.
1328
        :param stacked_on: An optional URL to stack the clone on.
4294.2.1 by Robert Collins
Move directory checking for bzr push options into Branch.create_clone_on_transport.
1329
        :param create_prefix: Create any missing directories leading up to
1330
            to_transport.
1331
        :param use_existing_dir: Use an existing directory if one exists.
4044.1.1 by Robert Collins
Create Branch.create_clone_on_transport helper method to combine bzr and branch creation for push.
1332
        """
4044.1.2 by Robert Collins
Reinstate the TODO comment about bzrdir.clone_on_transport.
1333
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1334
        # clone call. Or something. 20090224 RBC/spiv.
5147.4.1 by Jelmer Vernooij
Pass branch names in more places.
1335
        # XXX: Should this perhaps clone colocated branches as well, 
1336
        # rather than just the default branch? 20100319 JRV
4294.2.1 by Robert Collins
Move directory checking for bzr push options into Branch.create_clone_on_transport.
1337
        if revision_id is None:
1338
            revision_id = self.last_revision()
6653.6.1 by Jelmer Vernooij
Rename a number of attributes from bzrdir to controldir.
1339
        dir_to = self.controldir.clone_on_transport(to_transport,
4634.105.1 by Andrew Bennetts
Fix traceback when doing 'bzr push --use-existing-dir' into a dir with an invalid .bzr directory.
1340
            revision_id=revision_id, stacked_on=stacked_on,
5448.6.1 by Matthew Gordon
Added --no-tree option to pull. Needs testing and help text.
1341
            create_prefix=create_prefix, use_existing_dir=use_existing_dir,
5448.6.2 by Matthew Gordon
Tested push --no-tree ang gor it working right.
1342
            no_tree=no_tree)
4044.1.1 by Robert Collins
Create Branch.create_clone_on_transport helper method to combine bzr and branch creation for push.
1343
        return dir_to.open_branch()
1344
2245.2.1 by Robert Collins
Split branch pushing out of branch pulling.
1345
    def create_checkout(self, to_location, revision_id=None,
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
1346
                        lightweight=False, accelerator_tree=None,
1347
                        hardlink=False):
1551.8.3 by Aaron Bentley
Make create_checkout_convenience a Branch method
1348
        """Create a checkout of a branch.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1349
1551.8.3 by Aaron Bentley
Make create_checkout_convenience a Branch method
1350
        :param to_location: The url to produce the checkout at
1351
        :param revision_id: The revision to check out
1551.8.5 by Aaron Bentley
Change name to create_checkout
1352
        :param lightweight: If True, produce a lightweight checkout, otherwise,
5891.1.3 by Andrew Bennetts
Move docstring formatting fixes.
1353
            produce a bound branch (heavyweight checkout)
3123.5.17 by Aaron Bentley
Update docs
1354
        :param accelerator_tree: A tree which can be used for retrieving file
1355
            contents more quickly than the revision tree, i.e. a workingtree.
1356
            The revision tree will be used for cases where accelerator_tree's
1357
            content is different.
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
1358
        :param hardlink: If true, hard-link files from accelerator_tree,
1359
            where possible.
1551.8.3 by Aaron Bentley
Make create_checkout_convenience a Branch method
1360
        :return: The tree of the created checkout
1361
        """
1910.2.39 by Aaron Bentley
Fix checkout bug
1362
        t = transport.get_transport(to_location)
2475.3.3 by John Arbash Meinel
Change calls to try/mkdir('.')/except FileExists to ensure_base()
1363
        t.ensure_base()
6127.1.9 by Jelmer Vernooij
Add lightweight option to _get_checkout_format().
1364
        format = self._get_checkout_format(lightweight=lightweight)
6437.10.3 by Jelmer Vernooij
Allow checkouts into empty target directories.
1365
        try:
1366
            checkout = format.initialize_on_transport(t)
1367
        except errors.AlreadyControlDirError:
1368
            # It's fine if the control directory already exists,
1369
            # as long as there is no existing branch and working tree.
1370
            checkout = controldir.ControlDir.open_from_transport(t)
1371
            try:
1372
                checkout.open_branch()
1373
            except errors.NotBranchError:
1374
                pass
1375
            else:
1376
                raise errors.AlreadyControlDirError(t.base)
6653.6.1 by Jelmer Vernooij
Rename a number of attributes from bzrdir to controldir.
1377
            if checkout.control_transport.base == self.controldir.control_transport.base:
6437.17.1 by Jelmer Vernooij
Checkouts of colocated branches are always lightweight.
1378
                # When checking out to the same control directory,
1379
                # always create a lightweight checkout
1380
                lightweight = True
6437.10.3 by Jelmer Vernooij
Allow checkouts into empty target directories.
1381
1551.8.3 by Aaron Bentley
Make create_checkout_convenience a Branch method
1382
        if lightweight:
6437.7.3 by Jelmer Vernooij
Use ControlDir.set_branch_reference.
1383
            from_branch = checkout.set_branch_reference(target_branch=self)
1551.8.3 by Aaron Bentley
Make create_checkout_convenience a Branch method
1384
        else:
6437.10.1 by Jelmer Vernooij
Simplify handling of checkouts in bzrlib.branch.Branch.create_checkout.
1385
            policy = checkout.determine_repository_policy()
1386
            repo = policy.acquire_repository()[0]
1387
            checkout_branch = checkout.create_branch()
1551.8.3 by Aaron Bentley
Make create_checkout_convenience a Branch method
1388
            checkout_branch.bind(self)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1389
            # pull up to the specified revision_id to set the initial
1997.1.5 by Robert Collins
``Branch.bind(other_branch)`` no longer takes a write lock on the
1390
            # branch tip correctly, and seed it with history.
1391
            checkout_branch.pull(self, stop_revision=revision_id)
6437.10.1 by Jelmer Vernooij
Simplify handling of checkouts in bzrlib.branch.Branch.create_checkout.
1392
            from_branch = None
2955.5.3 by Vincent Ladeuil
Fix second unwanted connection by providing the right branch to create_checkout.
1393
        tree = checkout.create_workingtree(revision_id,
3123.5.2 by Aaron Bentley
Allow checkout --files_from
1394
                                           from_branch=from_branch,
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
1395
                                           accelerator_tree=accelerator_tree,
1396
                                           hardlink=hardlink)
2255.2.226 by Robert Collins
Get merge_nested finally working: change nested tree iterators to take file_ids, and ensure the right branch is connected to in the merge logic. May not be suitable for shared repositories yet.
1397
        basis_tree = tree.basis_tree()
6754.8.4 by Jelmer Vernooij
Use new context stuff.
1398
        with basis_tree.lock_read():
2255.2.226 by Robert Collins
Get merge_nested finally working: change nested tree iterators to take file_ids, and ensure the right branch is connected to in the merge logic. May not be suitable for shared repositories yet.
1399
            for path, file_id in basis_tree.iter_references():
6926.2.5 by Jelmer Vernooij
Swap order for nested tree functions.
1400
                reference_parent = self.reference_parent(path, file_id)
2255.2.226 by Robert Collins
Get merge_nested finally working: change nested tree iterators to take file_ids, and ensure the right branch is connected to in the merge logic. May not be suitable for shared repositories yet.
1401
                reference_parent.create_checkout(tree.abspath(path),
6809.4.1 by Jelmer Vernooij
Swap file_id and path arguments for get_reference_revision and get_nested_tree.
1402
                    basis_tree.get_reference_revision(path, file_id),
2255.2.226 by Robert Collins
Get merge_nested finally working: change nested tree iterators to take file_ids, and ensure the right branch is connected to in the merge logic. May not be suitable for shared repositories yet.
1403
                    lightweight)
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
1404
        return tree
1551.8.3 by Aaron Bentley
Make create_checkout_convenience a Branch method
1405
3389.2.3 by John Arbash Meinel
Add Branch.reconcile() functionality.
1406
    def reconcile(self, thorough=True):
1407
        """Make sure the data stored in this branch is consistent."""
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1408
        from breezy.reconcile import BranchReconciler
6754.8.13 by Jelmer Vernooij
Avoid needs_write_lock.
1409
        with self.lock_write():
1410
            reconciler = BranchReconciler(self, thorough=thorough)
1411
            reconciler.reconcile()
1412
            return reconciler
3389.2.3 by John Arbash Meinel
Add Branch.reconcile() functionality.
1413
6926.2.5 by Jelmer Vernooij
Swap order for nested tree functions.
1414
    def reference_parent(self, path, file_id=None, possible_transports=None):
2100.3.29 by Aaron Bentley
Get merge working initially
1415
        """Return the parent branch for a tree-reference file_id
5891.1.2 by Andrew Bennetts
Fix a bunch of docstring formatting nits, making pydoctor a bit happier.
1416
2100.3.29 by Aaron Bentley
Get merge working initially
1417
        :param path: The path of the file_id in the tree
6926.2.5 by Jelmer Vernooij
Swap order for nested tree functions.
1418
        :param file_id: Optional file_id of the tree reference
2100.3.29 by Aaron Bentley
Get merge working initially
1419
        :return: A branch associated with the file_id
1420
        """
1421
        # FIXME should provide multiple branches, based on config
6653.6.1 by Jelmer Vernooij
Rename a number of attributes from bzrdir to controldir.
1422
        return Branch.open(self.controldir.root_transport.clone(path).base,
5158.6.8 by Martin Pool
Go back to opening branch using url, so it can use all possible transports
1423
                           possible_transports=possible_transports)
2100.3.23 by Aaron Bentley
Nested checkouts kinda work
1424
2220.2.30 by Martin Pool
split out tag-merging code and add some tests
1425
    def supports_tags(self):
1426
        return self._format.supports_tags()
1427
5086.4.7 by Jelmer Vernooij
Put automatic_tag_name on Branch.
1428
    def automatic_tag_name(self, revision_id):
1429
        """Try to automatically find the tag name for a revision.
1430
1431
        :param revision_id: Revision id of the revision.
5086.4.8 by Jelmer Vernooij
Review comments from Ian.
1432
        :return: A tag name or None if no tag name could be determined.
5086.4.7 by Jelmer Vernooij
Put automatic_tag_name on Branch.
1433
        """
1434
        for hook in Branch.hooks['automatic_tag_name']:
1435
            ret = hook(self, revision_id)
1436
            if ret is not None:
1437
                return ret
1438
        return None
1439
3441.5.27 by Andrew Bennetts
Tweaks suggested by John's review: rename _check_if_descendant_or_diverged, move caching last_revision_info into base Branch, better use of lock decorators.
1440
    def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
1441
                                         other_branch):
3441.5.18 by Andrew Bennetts
Fix some test failures.
1442
        """Ensure that revision_b is a descendant of revision_a.
1443
1444
        This is a helper function for update_revisions.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1445
3441.5.18 by Andrew Bennetts
Fix some test failures.
1446
        :raises: DivergedBranches if revision_b has diverged from revision_a.
1447
        :returns: True if revision_b is a descendant of revision_a.
1448
        """
1449
        relation = self._revision_relations(revision_a, revision_b, graph)
1450
        if relation == 'b_descends_from_a':
1451
            return True
1452
        elif relation == 'diverged':
1453
            raise errors.DivergedBranches(self, other_branch)
1454
        elif relation == 'a_descends_from_b':
1455
            return False
1456
        else:
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1457
            raise AssertionError("invalid relation: %r" % (relation,))
3441.5.18 by Andrew Bennetts
Fix some test failures.
1458
1459
    def _revision_relations(self, revision_a, revision_b, graph):
1460
        """Determine the relationship between two revisions.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1461
3441.5.18 by Andrew Bennetts
Fix some test failures.
1462
        :returns: One of: 'a_descends_from_b', 'b_descends_from_a', 'diverged'
1463
        """
1464
        heads = graph.heads([revision_a, revision_b])
6619.3.12 by Jelmer Vernooij
Use 2to3 set_literal fixer.
1465
        if heads == {revision_b}:
3441.5.18 by Andrew Bennetts
Fix some test failures.
1466
            return 'b_descends_from_a'
6619.3.12 by Jelmer Vernooij
Use 2to3 set_literal fixer.
1467
        elif heads == {revision_a, revision_b}:
3441.5.18 by Andrew Bennetts
Fix some test failures.
1468
            # These branches have diverged
1469
            return 'diverged'
6619.3.12 by Jelmer Vernooij
Use 2to3 set_literal fixer.
1470
        elif heads == {revision_a}:
3441.5.18 by Andrew Bennetts
Fix some test failures.
1471
            return 'a_descends_from_b'
1472
        else:
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1473
            raise AssertionError("invalid heads: %r" % (heads,))
3441.5.18 by Andrew Bennetts
Fix some test failures.
1474
5741.1.11 by Jelmer Vernooij
Don't make heads_to_fetch() take a stop_revision.
1475
    def heads_to_fetch(self):
5672.1.1 by Andrew Bennetts
Refactor some of FetchSpecFactory into new Branch.heads_to_fetch method so that branch implementations like looms can override it.
1476
        """Return the heads that must and that should be fetched to copy this
1477
        branch into another repo.
1478
1479
        :returns: a 2-tuple of (must_fetch, if_present_fetch).  must_fetch is a
1480
            set of heads that must be fetched.  if_present_fetch is a set of
1481
            heads that must be fetched if present, but no error is necessary if
1482
            they are not present.
1483
        """
6404.1.1 by Vincent Ladeuil
Migrate branch.fetch_tags
1484
        # For bzr native formats must_fetch is just the tip, and
1485
        # if_present_fetch are the tags.
6619.3.12 by Jelmer Vernooij
Use 2to3 set_literal fixer.
1486
        must_fetch = {self.last_revision()}
6015.15.1 by John Arbash Meinel
Start working on a config entry for testing whether we should fetch tags or not.
1487
        if_present_fetch = set()
6404.1.1 by Vincent Ladeuil
Migrate branch.fetch_tags
1488
        if self.get_config_stack().get('branch.fetch_tags'):
6015.15.1 by John Arbash Meinel
Start working on a config entry for testing whether we should fetch tags or not.
1489
            try:
1490
                if_present_fetch = set(self.tags.get_reverse_tag_dict())
1491
            except errors.TagsNotSupported:
1492
                pass
5672.1.1 by Andrew Bennetts
Refactor some of FetchSpecFactory into new Branch.heads_to_fetch method so that branch implementations like looms can override it.
1493
        must_fetch.discard(_mod_revision.NULL_REVISION)
1494
        if_present_fetch.discard(_mod_revision.NULL_REVISION)
1495
        return must_fetch, if_present_fetch
1496
6883.8.1 by Jelmer Vernooij
Add Branch.create_memorytree.
1497
    def create_memorytree(self):
1498
        """Create a memory tree for this branch.
1499
6883.8.3 by Jelmer Vernooij
Improve docstring for Branch.create_memorytree.
1500
        :return: An in-memory MutableTree instance
6883.8.1 by Jelmer Vernooij
Add Branch.create_memorytree.
1501
        """
1502
        return memorytree.MemoryTree.create_on_branch(self)
1503
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1504
5669.3.10 by Jelmer Vernooij
Use ControlComponentFormat.
1505
class BranchFormat(controldir.ControlComponentFormat):
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1506
    """An encapsulation of the initialization and open routines for a format.
1507
1508
    Formats provide three things:
1509
     * An initialization routine,
6213.1.32 by Jelmer Vernooij
Fix check support status.
1510
     * a format description
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1511
     * an open routine.
1512
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1513
    Formats are placed in an dict by their format string for reference
5448.2.1 by Martin
Fix some "its" vs. "it's" spelling confusion in bzrlib code... also, ahem, a name in the NEWS file
1514
    during branch opening. It's not required that these be instances, they
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1515
    can be classes themselves with class methods - it simply depends on
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1516
    whether state is needed for a given format or not.
1517
1518
    Once a format is deprecated, just deprecate the initialize and open
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1519
    methods on the format class. Do not deprecate the object, as the
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1520
    object will be created every time regardless.
1521
    """
1522
2363.5.5 by Aaron Bentley
add info.describe_format
1523
    def __eq__(self, other):
1524
        return self.__class__ is other.__class__
1525
1526
    def __ne__(self, other):
1527
        return not (self == other)
1528
6207.3.3 by jelmer at samba
Fix tests and the like.
1529
    def get_reference(self, controldir, name=None):
1530
        """Get the target reference of the branch in controldir.
2414.2.1 by Andrew Bennetts
Some miscellaneous new APIs, tests and other changes from the hpss branch.
1531
1532
        format probing must have been completed before calling
1533
        this method - it is assumed that the format of the branch
6207.3.3 by jelmer at samba
Fix tests and the like.
1534
        in controldir is correct.
2414.2.1 by Andrew Bennetts
Some miscellaneous new APIs, tests and other changes from the hpss branch.
1535
6207.3.3 by jelmer at samba
Fix tests and the like.
1536
        :param controldir: The controldir to get the branch data from.
5147.4.6 by Jelmer Vernooij
consistency in names
1537
        :param name: Name of the colocated branch to fetch
2414.2.1 by Andrew Bennetts
Some miscellaneous new APIs, tests and other changes from the hpss branch.
1538
        :return: None if the branch is not a reference branch.
1539
        """
1540
        return None
1541
3078.2.1 by Ian Clatworthy
Refactor switch to support heavyweight checkouts
1542
    @classmethod
6207.3.3 by jelmer at samba
Fix tests and the like.
1543
    def set_reference(self, controldir, name, to_branch):
1544
        """Set the target reference of the branch in controldir.
3078.2.1 by Ian Clatworthy
Refactor switch to support heavyweight checkouts
1545
1546
        format probing must have been completed before calling
1547
        this method - it is assumed that the format of the branch
6207.3.3 by jelmer at samba
Fix tests and the like.
1548
        in controldir is correct.
3078.2.1 by Ian Clatworthy
Refactor switch to support heavyweight checkouts
1549
6207.3.3 by jelmer at samba
Fix tests and the like.
1550
        :param controldir: The controldir to set the branch reference for.
5147.4.6 by Jelmer Vernooij
consistency in names
1551
        :param name: Name of colocated branch to set, None for default
3078.2.1 by Ian Clatworthy
Refactor switch to support heavyweight checkouts
1552
        :param to_branch: branch that the checkout is to reference
1553
        """
1554
        raise NotImplementedError(self.set_reference)
1555
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1556
    def get_format_description(self):
1557
        """Return the short format description for this format."""
2258.1.1 by Robert Collins
Move info branch statistics gathering into the repository to allow smart server optimisation (Robert Collins).
1558
        raise NotImplementedError(self.get_format_description)
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1559
6207.3.3 by jelmer at samba
Fix tests and the like.
1560
    def _run_post_branch_init_hooks(self, controldir, name, branch):
5107.3.2 by Marco Pantaleoni
Renamed 'post_branch' hook to 'post_branch_init', for more consistency,
1561
        hooks = Branch.hooks['post_branch_init']
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
1562
        if not hooks:
1563
            return
6207.3.3 by jelmer at samba
Fix tests and the like.
1564
        params = BranchInitHookParams(self, controldir, name, branch)
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
1565
        for hook in hooks:
1566
            hook(params)
1567
6207.3.3 by jelmer at samba
Fix tests and the like.
1568
    def initialize(self, controldir, name=None, repository=None,
6123.9.12 by Jelmer Vernooij
Add append_revisions_only argument to BranchFormat.initialize.
1569
                   append_revisions_only=None):
6207.3.3 by jelmer at samba
Fix tests and the like.
1570
        """Create a branch of this format in controldir.
1571
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
1572
        :param name: Name of the colocated branch to create.
1573
        """
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1574
        raise NotImplementedError(self.initialize)
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1575
1534.4.7 by Robert Collins
Move downlevel check up to the Branch.open logic, removing it from the Branch constructor and deprecating relax_version_check to the same.
1576
    def is_supported(self):
1577
        """Is this format supported?
1578
1579
        Supported formats can be initialized and opened.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1580
        Unsupported formats may not support initialization or committing or
1534.4.7 by Robert Collins
Move downlevel check up to the Branch.open logic, removing it from the Branch constructor and deprecating relax_version_check to the same.
1581
        some other features depending on the reason for not being supported.
1582
        """
1583
        return True
1584
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
1585
    def make_tags(self, branch):
1586
        """Create a tags object for branch.
1587
1588
        This method is on BranchFormat, because BranchFormats are reflected
1589
        over the wire via network_name(), whereas full Branch instances require
1590
        multiple VFS method calls to operate at all.
1591
1592
        The default implementation returns a disabled-tags instance.
1593
1594
        Note that it is normal for branch to be a RemoteBranch when using tags
1595
        on a RemoteBranch.
1596
        """
6105.1.1 by Jelmer Vernooij
Fix "pydoc bzrlib.branch" by importing modules, not objects, using lazy_import.
1597
        return _mod_tag.DisabledTags(branch)
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
1598
4032.3.1 by Robert Collins
Add a BranchFormat.network_name() method as preparation for creating branches via RPC calls.
1599
    def network_name(self):
1600
        """A simple byte string uniquely identifying this format for RPC calls.
1601
1602
        MetaDir branch formats use their disk format string to identify the
1603
        repository over the wire. All in one formats such as bzr < 0.8, and
1604
        foreign formats like svn/git and hg should use some marker which is
1605
        unique and immutable.
1606
        """
1607
        raise NotImplementedError(self.network_name)
1608
6207.3.3 by jelmer at samba
Fix tests and the like.
1609
    def open(self, controldir, name=None, _found=False, ignore_fallbacks=False,
6305.3.2 by Jelmer Vernooij
Only make a single connection.
1610
            found_repository=None, possible_transports=None):
6207.3.3 by jelmer at samba
Fix tests and the like.
1611
        """Return the branch object for controldir.
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1612
6207.3.3 by jelmer at samba
Fix tests and the like.
1613
        :param controldir: A ControlDir that contains a branch.
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
1614
        :param name: Name of colocated branch to open
4160.2.12 by Andrew Bennetts
Improve docstrings and remove a line of cruft.
1615
        :param _found: a private parameter, do not use it. It is used to
1616
            indicate if format probing has already be done.
1617
        :param ignore_fallbacks: when set, no fallback branches will be opened
1618
            (if there are any).  Default is to open fallbacks.
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1619
        """
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1620
        raise NotImplementedError(self.open)
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1621
4301.3.3 by Andrew Bennetts
Move check onto base Branch class, and add a supports_set_append_revisions_only method to BranchFormat, as suggested by Robert.
1622
    def supports_set_append_revisions_only(self):
1623
        """True if this format supports set_append_revisions_only."""
1624
        return False
1625
3575.2.2 by Martin Pool
branch --stacked should force a stacked format
1626
    def supports_stacking(self):
1627
        """True if this format records a stacked-on branch."""
1628
        return False
1629
5674.1.1 by Jelmer Vernooij
Add supports_leave_lock flag to BranchFormat and RepositoryFormat.
1630
    def supports_leaving_lock(self):
1631
        """True if this format supports leaving locks in place."""
1632
        return False # by default
1633
1553.4.8 by Michael Ellerman
Define __str__ for BranchFormat, just return the format string with the
1634
    def __str__(self):
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
1635
        return self.get_format_description().rstrip()
1553.4.8 by Michael Ellerman
Define __str__ for BranchFormat, just return the format string with the
1636
2220.2.10 by Martin Pool
(broken) start moving things to branches
1637
    def supports_tags(self):
1638
        """True if this format supports tags stored in the branch"""
1639
        return False  # by default
1640
6123.4.6 by Jelmer Vernooij
Move flags to BranchFormat.
1641
    def tags_are_versioned(self):
1642
        """Whether the tag container for this branch versions tags."""
1643
        return False
1644
1645
    def supports_tags_referencing_ghosts(self):
1646
        """True if tags can reference ghost revisions."""
1647
        return True
1648
6772.3.1 by Jelmer Vernooij
Add supports_store_uncommitted.
1649
    def supports_store_uncommitted(self):
1650
        """True if uncommitted changes can be stored in this branch."""
1651
        return True
1652
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1653
2370.4.1 by Robert Collins
New SmartServer hooks facility. There are two initial hooks documented
1654
class BranchHooks(Hooks):
2245.1.3 by Robert Collins
Add install_hook to the BranchHooks class as the official means for installing a hook.
1655
    """A dictionary mapping hook name to a list of callables for branch hooks.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1656
6498.3.4 by Jelmer Vernooij
Remove more .set_revision_history / .revision_history references.
1657
    e.g. ['post_push'] Is the list of items to be called when the
1658
    push function is invoked.
2245.1.3 by Robert Collins
Add install_hook to the BranchHooks class as the official means for installing a hook.
1659
    """
1660
5622.3.10 by Jelmer Vernooij
Don't require arguments to hooks.
1661
    def __init__(self):
2245.1.3 by Robert Collins
Add install_hook to the BranchHooks class as the official means for installing a hook.
1662
        """Create the default hooks.
1663
1664
        These are all empty initially, because by default nothing should get
1665
        notified.
1666
        """
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1667
        Hooks.__init__(self, "breezy.branch", "Branch.hooks")
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
1668
        self.add_hook('open',
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
1669
            "Called with the Branch object that has been opened after a "
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
1670
            "branch is opened.", (1, 8))
1671
        self.add_hook('post_push',
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
1672
            "Called after a push operation completes. post_push is called "
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1673
            "with a breezy.branch.BranchPushResult object and only runs in the "
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
1674
            "bzr client.", (0, 15))
1675
        self.add_hook('post_pull',
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
1676
            "Called after a pull operation completes. post_pull is called "
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1677
            "with a breezy.branch.PullResult object and only runs in the "
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
1678
            "bzr client.", (0, 15))
1679
        self.add_hook('pre_commit',
5430.4.2 by Vincent Ladeuil
Fix typo in Branch.pre_commit HookPoint docstring.
1680
            "Called after a commit is calculated but before it is "
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
1681
            "completed. pre_commit is called with (local, master, old_revno, "
1682
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
1683
            "). old_revid is NULL_REVISION for the first commit to a branch, "
1684
            "tree_delta is a TreeDelta object describing changes from the "
1685
            "basis revision. hooks MUST NOT modify this delta. "
1686
            " future_tree is an in-memory tree obtained from "
1687
            "CommitBuilder.revision_tree() and hooks MUST NOT modify this "
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
1688
            "tree.", (0, 91))
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
1689
        self.add_hook('post_commit',
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
1690
            "Called in the bzr client after a commit has completed. "
1691
            "post_commit is called with (local, master, old_revno, old_revid, "
1692
            "new_revno, new_revid). old_revid is NULL_REVISION for the first "
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
1693
            "commit to a branch.", (0, 15))
1694
        self.add_hook('post_uncommit',
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
1695
            "Called in the bzr client after an uncommit completes. "
1696
            "post_uncommit is called with (local, master, old_revno, "
1697
            "old_revid, new_revno, new_revid) where local is the local branch "
1698
            "or None, master is the target branch, and an empty branch "
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
1699
            "receives new_revno of 0, new_revid of None.", (0, 15))
1700
        self.add_hook('pre_change_branch_tip',
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
1701
            "Called in bzr client and server before a change to the tip of a "
1702
            "branch is made. pre_change_branch_tip is called with a "
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1703
            "breezy.branch.ChangeBranchTipParams. Note that push, pull, "
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
1704
            "commit, uncommit will all trigger this hook.", (1, 6))
1705
        self.add_hook('post_change_branch_tip',
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
1706
            "Called in bzr client and server after a change to the tip of a "
1707
            "branch is made. post_change_branch_tip is called with a "
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1708
            "breezy.branch.ChangeBranchTipParams. Note that push, pull, "
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
1709
            "commit, uncommit will all trigger this hook.", (1, 4))
1710
        self.add_hook('transform_fallback_location',
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
1711
            "Called when a stacked branch is activating its fallback "
1712
            "locations. transform_fallback_location is called with (branch, "
1713
            "url), and should return a new url. Returning the same url "
1714
            "allows it to be used as-is, returning a different one can be "
1715
            "used to cause the branch to stack on a closer copy of that "
1716
            "fallback_location. Note that the branch cannot have history "
1717
            "accessing methods called on it during this hook because the "
1718
            "fallback locations have not been activated. When there are "
1719
            "multiple hooks installed for transform_fallback_location, "
1720
            "all are called with the url returned from the previous hook."
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
1721
            "The order is however undefined.", (1, 9))
1722
        self.add_hook('automatic_tag_name',
5050.20.1 by Alexander Belchenko
trivial doc change to provide better docs in html format (space between two sentences needed)
1723
            "Called to determine an automatic tag name for a revision. "
5086.4.5 by Jelmer Vernooij
Make automatic_tag_name a hook on Branch.
1724
            "automatic_tag_name is called with (branch, revision_id) and "
1725
            "should return a tag name or None if no tag name could be "
5086.4.9 by Jelmer Vernooij
Update documentation.
1726
            "determined. The first non-None tag name returned will be used.",
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
1727
            (2, 2))
1728
        self.add_hook('post_branch_init',
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
1729
            "Called after new branch initialization completes. "
5107.3.6 by Marco Pantaleoni
Documented behaviour of 'post_branch_init' for lightweight checkouts.
1730
            "post_branch_init is called with a "
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1731
            "breezy.branch.BranchInitHookParams. "
5107.3.6 by Marco Pantaleoni
Documented behaviour of 'post_branch_init' for lightweight checkouts.
1732
            "Note that init, branch and checkout (both heavyweight and "
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
1733
            "lightweight) will all trigger this hook.", (2, 2))
1734
        self.add_hook('post_switch',
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
1735
            "Called after a checkout switches branch. "
1736
            "post_switch is called with a "
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1737
            "breezy.branch.SwitchHookParams.", (2, 2))
5086.4.5 by Jelmer Vernooij
Make automatic_tag_name a hook on Branch.
1738
2245.1.3 by Robert Collins
Add install_hook to the BranchHooks class as the official means for installing a hook.
1739
1740
1741
# install the default hooks into the Branch class.
5622.3.10 by Jelmer Vernooij
Don't require arguments to hooks.
1742
Branch.hooks = BranchHooks()
2245.1.3 by Robert Collins
Add install_hook to the BranchHooks class as the official means for installing a hook.
1743
1744
3323.2.1 by Ian Clatworthy
first cut at post_change_branch_tip hook
1745
class ChangeBranchTipParams(object):
5891.1.2 by Andrew Bennetts
Fix a bunch of docstring formatting nits, making pydoctor a bit happier.
1746
    """Object holding parameters passed to `*_change_branch_tip` hooks.
3331.1.5 by James Henstridge
Put revno before revid in method arguments to match last_revision_info()
1747
3331.1.7 by James Henstridge
Make the branch a member of the ChangeBranchTipParams object.
1748
    There are 5 fields that hooks may wish to access:
3331.1.5 by James Henstridge
Put revno before revid in method arguments to match last_revision_info()
1749
3331.1.13 by James Henstridge
Use last_revision_info() to retrieve the new revision number and ID.
1750
    :ivar branch: the branch being changed
1751
    :ivar old_revno: revision number before the change
1752
    :ivar new_revno: revision number after the change
1753
    :ivar old_revid: revision id before the change
1754
    :ivar new_revid: revision id after the change
3331.1.5 by James Henstridge
Put revno before revid in method arguments to match last_revision_info()
1755
3323.2.1 by Ian Clatworthy
first cut at post_change_branch_tip hook
1756
    The revid fields are strings. The revno fields are integers.
1757
    """
1758
3331.1.7 by James Henstridge
Make the branch a member of the ChangeBranchTipParams object.
1759
    def __init__(self, branch, old_revno, new_revno, old_revid, new_revid):
3323.2.1 by Ian Clatworthy
first cut at post_change_branch_tip hook
1760
        """Create a group of ChangeBranchTip parameters.
1761
3331.1.7 by James Henstridge
Make the branch a member of the ChangeBranchTipParams object.
1762
        :param branch: The branch being changed.
3331.1.5 by James Henstridge
Put revno before revid in method arguments to match last_revision_info()
1763
        :param old_revno: Revision number before the change.
1764
        :param new_revno: Revision number after the change.
3323.2.1 by Ian Clatworthy
first cut at post_change_branch_tip hook
1765
        :param old_revid: Tip revision id before the change.
1766
        :param new_revid: Tip revision id after the change.
1767
        """
3331.1.7 by James Henstridge
Make the branch a member of the ChangeBranchTipParams object.
1768
        self.branch = branch
3331.1.5 by James Henstridge
Put revno before revid in method arguments to match last_revision_info()
1769
        self.old_revno = old_revno
1770
        self.new_revno = new_revno
3323.2.1 by Ian Clatworthy
first cut at post_change_branch_tip hook
1771
        self.old_revid = old_revid
1772
        self.new_revid = new_revid
1773
3517.2.3 by Andrew Bennetts
Better tests for {pre,post}_change_branch_tip hooks.
1774
    def __eq__(self, other):
1775
        return self.__dict__ == other.__dict__
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1776
3517.2.3 by Andrew Bennetts
Better tests for {pre,post}_change_branch_tip hooks.
1777
    def __repr__(self):
1778
        return "<%s of %s from (%s, %s) to (%s, %s)>" % (
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1779
            self.__class__.__name__, self.branch,
3517.2.3 by Andrew Bennetts
Better tests for {pre,post}_change_branch_tip hooks.
1780
            self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1781
5107.3.4 by Marco Pantaleoni
Applied suggestions from merge reviewer (John A Meinel):
1782
5107.3.2 by Marco Pantaleoni
Renamed 'post_branch' hook to 'post_branch_init', for more consistency,
1783
class BranchInitHookParams(object):
5891.1.2 by Andrew Bennetts
Fix a bunch of docstring formatting nits, making pydoctor a bit happier.
1784
    """Object holding parameters passed to `*_branch_init` hooks.
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
1785
1786
    There are 4 fields that hooks may wish to access:
1787
1788
    :ivar format: the branch format
6207.3.3 by jelmer at samba
Fix tests and the like.
1789
    :ivar bzrdir: the ControlDir where the branch will be/has been initialized
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
1790
    :ivar name: name of colocated branch, if any (or None)
5107.3.6 by Marco Pantaleoni
Documented behaviour of 'post_branch_init' for lightweight checkouts.
1791
    :ivar branch: the branch created
1792
1793
    Note that for lightweight checkouts, the bzrdir and format fields refer to
1794
    the checkout, hence they are different from the corresponding fields in
1795
    branch, which refer to the original branch.
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
1796
    """
1797
6207.3.3 by jelmer at samba
Fix tests and the like.
1798
    def __init__(self, format, controldir, name, branch):
5107.3.2 by Marco Pantaleoni
Renamed 'post_branch' hook to 'post_branch_init', for more consistency,
1799
        """Create a group of BranchInitHook parameters.
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
1800
1801
        :param format: the branch format
6207.3.3 by jelmer at samba
Fix tests and the like.
1802
        :param controldir: the ControlDir where the branch will be/has been
5107.3.6 by Marco Pantaleoni
Documented behaviour of 'post_branch_init' for lightweight checkouts.
1803
            initialized
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
1804
        :param name: name of colocated branch, if any (or None)
5107.3.6 by Marco Pantaleoni
Documented behaviour of 'post_branch_init' for lightweight checkouts.
1805
        :param branch: the branch created
1806
1807
        Note that for lightweight checkouts, the bzrdir and format fields refer
1808
        to the checkout, hence they are different from the corresponding fields
1809
        in branch, which refer to the original branch.
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
1810
        """
1811
        self.format = format
6653.6.1 by Jelmer Vernooij
Rename a number of attributes from bzrdir to controldir.
1812
        self.controldir = controldir
5107.3.4 by Marco Pantaleoni
Applied suggestions from merge reviewer (John A Meinel):
1813
        self.name = name
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
1814
        self.branch = branch
1815
1816
    def __eq__(self, other):
1817
        return self.__dict__ == other.__dict__
1818
1819
    def __repr__(self):
5050.21.1 by Andrew Bennetts
Remove broken and apparently unused code path from BranchInitHookParams.__repr__.
1820
        return "<%s of %s>" % (self.__class__.__name__, self.branch)
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
1821
5107.3.4 by Marco Pantaleoni
Applied suggestions from merge reviewer (John A Meinel):
1822
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
1823
class SwitchHookParams(object):
5891.1.2 by Andrew Bennetts
Fix a bunch of docstring formatting nits, making pydoctor a bit happier.
1824
    """Object holding parameters passed to `*_switch` hooks.
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
1825
1826
    There are 4 fields that hooks may wish to access:
1827
6207.3.3 by jelmer at samba
Fix tests and the like.
1828
    :ivar control_dir: ControlDir of the checkout to change
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
1829
    :ivar to_branch: branch that the checkout is to reference
1830
    :ivar force: skip the check for local commits in a heavy checkout
1831
    :ivar revision_id: revision ID to switch to (or None)
1832
    """
1833
1834
    def __init__(self, control_dir, to_branch, force, revision_id):
1835
        """Create a group of SwitchHook parameters.
1836
6207.3.3 by jelmer at samba
Fix tests and the like.
1837
        :param control_dir: ControlDir of the checkout to change
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
1838
        :param to_branch: branch that the checkout is to reference
1839
        :param force: skip the check for local commits in a heavy checkout
1840
        :param revision_id: revision ID to switch to (or None)
1841
        """
1842
        self.control_dir = control_dir
5107.3.4 by Marco Pantaleoni
Applied suggestions from merge reviewer (John A Meinel):
1843
        self.to_branch = to_branch
1844
        self.force = force
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
1845
        self.revision_id = revision_id
1846
1847
    def __eq__(self, other):
1848
        return self.__dict__ == other.__dict__
1849
1850
    def __repr__(self):
1851
        return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
1852
            self.control_dir, self.to_branch,
1853
            self.revision_id)
3323.2.1 by Ian Clatworthy
first cut at post_change_branch_tip hook
1854
5107.3.4 by Marco Pantaleoni
Applied suggestions from merge reviewer (John A Meinel):
1855
5669.3.9 by Jelmer Vernooij
Consistent naming.
1856
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
5662.2.1 by Jelmer Vernooij
Add BranchFormatRegistry.
1857
    """Branch format registry."""
1858
1859
    def __init__(self, other_registry=None):
1860
        super(BranchFormatRegistry, self).__init__(other_registry)
6653.1.9 by Jelmer Vernooij
Fix set_default.
1861
        self._default_format = None
6653.1.1 by Jelmer Vernooij
Split bzr branch code out into breezy.bzrbranch.
1862
        self._default_format_key = None
5662.2.2 by Jelmer Vernooij
Move most format registration functions to BranchFormatRegistry.
1863
1864
    def get_default(self):
6653.1.9 by Jelmer Vernooij
Fix set_default.
1865
        """Return the current default format."""
1866
        if (self._default_format_key is not None and
1867
            self._default_format is None):
1868
            self._default_format = self.get(self._default_format_key)
1869
        return self._default_format
1870
1871
    def set_default(self, format):
1872
        """Set the default format."""
1873
        self._default_format = format
1874
        self._default_format_key = None
1875
1876
    def set_default_key(self, format_string):
1877
        """Set the default format by its format string."""
1878
        self._default_format_key = format_string
1879
        self._default_format = None
5662.2.2 by Jelmer Vernooij
Move most format registration functions to BranchFormatRegistry.
1880
5662.2.1 by Jelmer Vernooij
Add BranchFormatRegistry.
1881
4032.3.1 by Robert Collins
Add a BranchFormat.network_name() method as preparation for creating branches via RPC calls.
1882
network_format_registry = registry.FormatRegistry()
1883
"""Registry of formats indexed by their network name.
1884
4070.2.1 by Robert Collins
Add a BzrDirFormat.network_name.
1885
The network name for a branch format is an identifier that can be used when
4032.3.1 by Robert Collins
Add a BranchFormat.network_name() method as preparation for creating branches via RPC calls.
1886
referring to formats with smart server operations. See
1887
BranchFormat.network_name() for more detail.
1888
"""
1889
5662.2.1 by Jelmer Vernooij
Add BranchFormatRegistry.
1890
format_registry = BranchFormatRegistry(network_format_registry)
1891
4032.3.1 by Robert Collins
Add a BranchFormat.network_name() method as preparation for creating branches via RPC calls.
1892
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1893
# formats which have no format string are not discoverable
1894
# and not independently creatable, so are not registered.
6653.1.1 by Jelmer Vernooij
Split bzr branch code out into breezy.bzrbranch.
1895
format_registry.register_lazy(
6855.2.2 by Jelmer Vernooij
Format strings are bytes.
1896
    b"Bazaar-NG branch format 5\n", "breezy.bzr.fullhistory",
6653.1.1 by Jelmer Vernooij
Split bzr branch code out into breezy.bzrbranch.
1897
    "BzrBranchFormat5")
1898
format_registry.register_lazy(
6855.2.2 by Jelmer Vernooij
Format strings are bytes.
1899
    b"Bazaar Branch Format 6 (bzr 0.15)\n",
6670.4.1 by Jelmer Vernooij
Update imports.
1900
    "breezy.bzr.branch", "BzrBranchFormat6")
6653.1.1 by Jelmer Vernooij
Split bzr branch code out into breezy.bzrbranch.
1901
format_registry.register_lazy(
6855.2.2 by Jelmer Vernooij
Format strings are bytes.
1902
    b"Bazaar Branch Format 7 (needs bzr 1.6)\n",
6670.4.1 by Jelmer Vernooij
Update imports.
1903
    "breezy.bzr.branch", "BzrBranchFormat7")
6653.1.1 by Jelmer Vernooij
Split bzr branch code out into breezy.bzrbranch.
1904
format_registry.register_lazy(
6855.2.2 by Jelmer Vernooij
Format strings are bytes.
1905
    b"Bazaar Branch Format 8 (needs bzr 1.15)\n",
6670.4.1 by Jelmer Vernooij
Update imports.
1906
    "breezy.bzr.branch", "BzrBranchFormat8")
6653.1.1 by Jelmer Vernooij
Split bzr branch code out into breezy.bzrbranch.
1907
format_registry.register_lazy(
6855.2.2 by Jelmer Vernooij
Format strings are bytes.
1908
    b"Bazaar-NG Branch Reference Format 1\n",
6670.4.1 by Jelmer Vernooij
Update imports.
1909
    "breezy.bzr.branch", "BranchReferenceFormat")
6653.1.1 by Jelmer Vernooij
Split bzr branch code out into breezy.bzrbranch.
1910
6855.2.2 by Jelmer Vernooij
Format strings are bytes.
1911
format_registry.set_default_key(b"Bazaar Branch Format 7 (needs bzr 1.6)\n")
4032.3.1 by Robert Collins
Add a BranchFormat.network_name() method as preparation for creating branches via RPC calls.
1912
1534.4.5 by Robert Collins
Turn branch format.open into a factory.
1913
5200.3.6 by Robert Collins
Make all lock methods return Result objects, rather than lock_read returning self, as per John's review.
1914
class BranchWriteLockResult(LogicalLockResult):
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1915
    """The result of write locking a branch.
1916
6754.8.4 by Jelmer Vernooij
Use new context stuff.
1917
    :ivar token: The token obtained from the underlying branch lock, or
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1918
        None.
1919
    :ivar unlock: A callable which will unlock the lock.
1920
    """
1921
5200.3.6 by Robert Collins
Make all lock methods return Result objects, rather than lock_read returning self, as per John's review.
1922
    def __repr__(self):
6754.8.4 by Jelmer Vernooij
Use new context stuff.
1923
        return "BranchWriteLockResult(%r, %r)" % (self.unlock, self.token)
5200.3.5 by Robert Collins
Add __str__ to the new helper classes.
1924
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1925
2297.1.1 by Martin Pool
Pull now returns a PullResult rather than just an integer.
1926
######################################################################
1927
# results of operations
1928
2220.2.37 by Martin Pool
Report conflicting tags from push.
1929
1930
class _Result(object):
1931
1932
    def _show_tag_conficts(self, to_file):
1933
        if not getattr(self, 'tag_conflicts', None):
1934
            return
1935
        to_file.write('Conflicting tags:\n')
1936
        for name, value1, value2 in self.tag_conflicts:
1937
            to_file.write('    %s\n' % (name, ))
1938
1939
1940
class PullResult(_Result):
2297.1.6 by Martin Pool
Add docs for Results, give some members cleaner names
1941
    """Result of a Branch.pull operation.
1942
1943
    :ivar old_revno: Revision number before pull.
1944
    :ivar new_revno: Revision number after pull.
1945
    :ivar old_revid: Tip revision id before pull.
1946
    :ivar new_revid: Tip revision id after pull.
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
1947
    :ivar source_branch: Source (local) branch object. (read locked)
3482.1.1 by John Arbash Meinel
Fix bug #238149, RemoteBranch.pull needs to return the _real_branch's pull result.
1948
    :ivar master_branch: Master branch of the target, or the target if no
1949
        Master
1950
    :ivar local_branch: target branch if there is a Master, else None
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
1951
    :ivar target_branch: Target/destination branch object. (write locked)
3482.1.1 by John Arbash Meinel
Fix bug #238149, RemoteBranch.pull needs to return the _real_branch's pull result.
1952
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
6112.4.1 by Jelmer Vernooij
Show how many tags have been updated in bzr pull.
1953
    :ivar tag_updates: A dict with new tags, see BasicTags.merge_to
2297.1.6 by Martin Pool
Add docs for Results, give some members cleaner names
1954
    """
2297.1.1 by Martin Pool
Pull now returns a PullResult rather than just an integer.
1955
2220.2.39 by Martin Pool
Pull also merges tags and warns if they conflict
1956
    def report(self, to_file):
6112.4.3 by Jelmer Vernooij
Fix push tests.
1957
        tag_conflicts = getattr(self, "tag_conflicts", None)
1958
        tag_updates = getattr(self, "tag_updates", None)
3200.1.1 by James Westby
Make pull --quiet more quiet. Fixes #185907.
1959
        if not is_quiet():
6112.4.1 by Jelmer Vernooij
Show how many tags have been updated in bzr pull.
1960
            if self.old_revid != self.new_revid:
3200.1.1 by James Westby
Make pull --quiet more quiet. Fixes #185907.
1961
                to_file.write('Now on revision %d.\n' % self.new_revno)
6112.4.3 by Jelmer Vernooij
Fix push tests.
1962
            if tag_updates:
1963
                to_file.write('%d tag(s) updated.\n' % len(tag_updates))
1964
            if self.old_revid == self.new_revid and not tag_updates:
1965
                if not tag_conflicts:
6112.4.1 by Jelmer Vernooij
Show how many tags have been updated in bzr pull.
1966
                    to_file.write('No revisions or tags to pull.\n')
1967
                else:
1968
                    to_file.write('No revisions to pull.\n')
2220.2.39 by Martin Pool
Pull also merges tags and warns if they conflict
1969
        self._show_tag_conficts(to_file)
1970
2297.1.4 by Martin Pool
Push now returns a PushResult rather than just an integer.
1971
4053.3.1 by Jelmer Vernooij
Rename PushResult to BranchPushResult.
1972
class BranchPushResult(_Result):
2297.1.6 by Martin Pool
Add docs for Results, give some members cleaner names
1973
    """Result of a Branch.push operation.
1974
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
1975
    :ivar old_revno: Revision number (eg 10) of the target before push.
1976
    :ivar new_revno: Revision number (eg 12) of the target after push.
1977
    :ivar old_revid: Tip revision id (eg joe@foo.com-1234234-aoeua34) of target
1978
        before the push.
1979
    :ivar new_revid: Tip revision id (eg joe@foo.com-5676566-boa234a) of target
1980
        after the push.
1981
    :ivar source_branch: Source branch object that the push was from. This is
1982
        read locked, and generally is a local (and thus low latency) branch.
1983
    :ivar master_branch: If target is a bound branch, the master branch of
1984
        target, or target itself. Always write locked.
1985
    :ivar target_branch: The direct Branch where data is being sent (write
1986
        locked).
1987
    :ivar local_branch: If the target is a bound branch this will be the
1988
        target, otherwise it will be None.
2297.1.6 by Martin Pool
Add docs for Results, give some members cleaner names
1989
    """
2297.1.4 by Martin Pool
Push now returns a PushResult rather than just an integer.
1990
2220.2.37 by Martin Pool
Report conflicting tags from push.
1991
    def report(self, to_file):
6112.4.5 by Jelmer Vernooij
Add note about bzr pull / bzr push output inconsistency.
1992
        # TODO: This function gets passed a to_file, but then
1993
        # ignores it and calls note() instead. This is also
1994
        # inconsistent with PullResult(), which writes to stdout.
1995
        # -- JRV20110901, bug #838853
6112.4.3 by Jelmer Vernooij
Fix push tests.
1996
        tag_conflicts = getattr(self, "tag_conflicts", None)
1997
        tag_updates = getattr(self, "tag_updates", None)
6112.4.2 by Jelmer Vernooij
Fix tag tests.
1998
        if not is_quiet():
1999
            if self.old_revid != self.new_revid:
6138.3.1 by Jonathan Riddell
use gettext() in more files
2000
                note(gettext('Pushed up to revision %d.') % self.new_revno)
6112.4.3 by Jelmer Vernooij
Fix push tests.
2001
            if tag_updates:
6143.1.1 by Jonathan Riddell
use ngettext for plurals
2002
                note(ngettext('%d tag updated.', '%d tags updated.', len(tag_updates)) % len(tag_updates))
6112.4.3 by Jelmer Vernooij
Fix push tests.
2003
            if self.old_revid == self.new_revid and not tag_updates:
2004
                if not tag_conflicts:
6138.3.1 by Jonathan Riddell
use gettext() in more files
2005
                    note(gettext('No new revisions or tags to push.'))
6112.4.2 by Jelmer Vernooij
Fix tag tests.
2006
                else:
6138.3.1 by Jonathan Riddell
use gettext() in more files
2007
                    note(gettext('No new revisions to push.'))
2220.2.37 by Martin Pool
Report conflicting tags from push.
2008
        self._show_tag_conficts(to_file)
2009
2297.1.1 by Martin Pool
Pull now returns a PullResult rather than just an integer.
2010
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
2011
class BranchCheckResult(object):
2012
    """Results of checking branch consistency.
2013
2014
    :see: Branch.check
2015
    """
2016
2017
    def __init__(self, branch):
2018
        self.branch = branch
4332.3.3 by Robert Collins
Alter Branch.check to log errors rather than raising.
2019
        self.errors = []
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
2020
2021
    def report_results(self, verbose):
2022
        """Report the check results via trace.note.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2023
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
2024
        :param verbose: Requests more detailed display of what was checked,
2025
            if any.
2026
        """
6147.1.1 by Jonathan Riddell
use .format() instead of % for string formatting where there are multiple formats in one string to allow for translations
2027
        note(gettext('checked branch {0} format {1}').format(
2028
                                self.branch.user_url, self.branch._format))
4332.3.3 by Robert Collins
Alter Branch.check to log errors rather than raising.
2029
        for error in self.errors:
6138.3.1 by Jonathan Riddell
use gettext() in more files
2030
            note(gettext('found error:%s'), error)
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
2031
2032
4000.5.1 by Jelmer Vernooij
Add InterBranch.
2033
class InterBranch(InterObject):
2034
    """This class represents operations taking place between two branches.
2035
2036
    Its instances have methods like pull() and push() and contain
2037
    references to the source and target repositories these operations
2038
    can be carried out on.
2039
    """
2040
2041
    _optimisers = []
3978.3.11 by Jelmer Vernooij
Move InterBranchBzrDir to bzrlib.push.
2042
    """The available optimised InterBranch types."""
2043
5297.2.1 by Robert Collins
``bzrlib.branch.InterBranch._get_branch_formats_to_test`` now returns
2044
    @classmethod
2045
    def _get_branch_formats_to_test(klass):
2046
        """Return an iterable of format tuples for testing.
2047
        
2048
        :return: An iterable of (from_format, to_format) to use when testing
2049
            this InterBranch class. Each InterBranch class should define this
2050
            method itself.
2051
        """
2052
        raise NotImplementedError(klass._get_branch_formats_to_test)
3978.3.11 by Jelmer Vernooij
Move InterBranchBzrDir to bzrlib.push.
2053
4000.5.9 by Jelmer Vernooij
Add InterBranch.pull().
2054
    def pull(self, overwrite=False, stop_revision=None,
4000.5.21 by Jelmer Vernooij
Merge bzr.dev.
2055
             possible_transports=None, local=False):
4000.5.10 by Jelmer Vernooij
Fix comment for InterBranch.pull.
2056
        """Mirror source into target branch.
2057
2058
        The target branch is considered to be 'local', having low latency.
2059
2060
        :returns: PullResult instance
4000.5.9 by Jelmer Vernooij
Add InterBranch.pull().
2061
        """
2062
        raise NotImplementedError(self.pull)
2063
5853.2.2 by Jelmer Vernooij
Make lossy_push an argument to InterBranch.push.
2064
    def push(self, overwrite=False, stop_revision=None, lossy=False,
4211.1.3 by Jelmer Vernooij
Fix trailing whitespace, add prototype for InterBranch.push().
2065
             _override_hook_source_branch=None):
2066
        """Mirror the source branch into the target branch.
2067
2068
        The source branch is considered to be 'local', having low latency.
2069
        """
2070
        raise NotImplementedError(self.push)
2071
5358.1.1 by Jelmer Vernooij
Add stub for InterBranch.copy_content_into.
2072
    def copy_content_into(self, revision_id=None):
2073
        """Copy the content of source into target
2074
2075
        revision_id: if not None, the revision history in the new branch will
2076
                     be truncated to end with revision_id.
2077
        """
2078
        raise NotImplementedError(self.copy_content_into)
2079
5852.1.1 by Jelmer Vernooij
Add limit argument to Branch.fetch.
2080
    def fetch(self, stop_revision=None, limit=None):
5741.1.1 by Jelmer Vernooij
Move fetch implementation to InterBranch.
2081
        """Fetch revisions.
2082
2083
        :param stop_revision: Last revision to fetch
5852.1.1 by Jelmer Vernooij
Add limit argument to Branch.fetch.
2084
        :param limit: Optional rough limit of revisions to fetch
5741.1.1 by Jelmer Vernooij
Move fetch implementation to InterBranch.
2085
        """
2086
        raise NotImplementedError(self.fetch)
2087
3978.3.11 by Jelmer Vernooij
Move InterBranchBzrDir to bzrlib.push.
2088
6159.2.4 by Jelmer Vernooij
Add --overwrite-tags flag.
2089
def _fix_overwrite_type(overwrite):
2090
    if isinstance(overwrite, bool):
2091
        if overwrite:
2092
            return ["history", "tags"]
2093
        else:
2094
            return []
2095
    return overwrite
2096
2097
3978.3.11 by Jelmer Vernooij
Move InterBranchBzrDir to bzrlib.push.
2098
class GenericInterBranch(InterBranch):
5284.4.1 by Robert Collins
* Fetching was slightly confused about the best code to use and was
2099
    """InterBranch implementation that uses public Branch functions."""
2100
2101
    @classmethod
2102
    def is_compatible(klass, source, target):
2103
        # GenericBranch uses the public API, so always compatible
2104
        return True
4000.5.1 by Jelmer Vernooij
Add InterBranch.
2105
5297.2.1 by Robert Collins
``bzrlib.branch.InterBranch._get_branch_formats_to_test`` now returns
2106
    @classmethod
2107
    def _get_branch_formats_to_test(klass):
5662.2.2 by Jelmer Vernooij
Move most format registration functions to BranchFormatRegistry.
2108
        return [(format_registry.get_default(), format_registry.get_default())]
4000.5.3 by Jelmer Vernooij
Add tests for InterBranch.
2109
5284.4.1 by Robert Collins
* Fetching was slightly confused about the best code to use and was
2110
    @classmethod
2111
    def unwrap_format(klass, format):
2112
        if isinstance(format, remote.RemoteBranchFormat):
2113
            format._ensure_real()
2114
            return format._custom_format
5050.53.4 by Andrew Bennetts
Don't propagate tags to the master branch during cmd_merge.
2115
        return format
5284.4.1 by Robert Collins
* Fetching was slightly confused about the best code to use and was
2116
5284.4.2 by Robert Collins
* ``Branch.copy_content_into`` is now a convenience method dispatching to
2117
    def copy_content_into(self, revision_id=None):
2118
        """Copy the content of source into target
2119
2120
        revision_id: if not None, the revision history in the new branch will
2121
                     be truncated to end with revision_id.
2122
        """
6754.8.13 by Jelmer Vernooij
Avoid needs_write_lock.
2123
        with self.source.lock_read(), self.target.lock_write():
2124
            self.source.update_references(self.target)
2125
            self.source._synchronize_history(self.target, revision_id)
2126
            try:
2127
                parent = self.source.get_parent()
2128
            except errors.InaccessibleParent as e:
6973.6.2 by Jelmer Vernooij
Fix more tests.
2129
                mutter('parent was not accessible to copy: %s', str(e))
6754.8.13 by Jelmer Vernooij
Avoid needs_write_lock.
2130
            else:
2131
                if parent:
2132
                    self.target.set_parent(parent)
2133
            if self.source._push_should_merge_tags():
2134
                self.source.tags.merge_to(self.target.tags)
5284.4.2 by Robert Collins
* ``Branch.copy_content_into`` is now a convenience method dispatching to
2135
5852.1.1 by Jelmer Vernooij
Add limit argument to Branch.fetch.
2136
    def fetch(self, stop_revision=None, limit=None):
5741.1.1 by Jelmer Vernooij
Move fetch implementation to InterBranch.
2137
        if self.target.base == self.source.base:
2138
            return (0, [])
6754.8.13 by Jelmer Vernooij
Avoid needs_write_lock.
2139
        with self.source.lock_read(), self.target.lock_write():
5741.1.6 by Jelmer Vernooij
Add stop_revision argument to Branch.heads_to_fetch.
2140
            fetch_spec_factory = fetch.FetchSpecFactory()
2141
            fetch_spec_factory.source_branch = self.source
2142
            fetch_spec_factory.source_branch_stop_revision_id = stop_revision
2143
            fetch_spec_factory.source_repo = self.source.repository
2144
            fetch_spec_factory.target_repo = self.target.repository
2145
            fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
5852.1.5 by Andrew Bennetts, Jelmer Vernooij
Support limit= for fetching between Bazaar branches.
2146
            fetch_spec_factory.limit = limit
5741.1.6 by Jelmer Vernooij
Add stop_revision argument to Branch.heads_to_fetch.
2147
            fetch_spec = fetch_spec_factory.make_fetch_spec()
6754.8.4 by Jelmer Vernooij
Use new context stuff.
2148
            return self.target.repository.fetch(
2149
                    self.source.repository,
2150
                    fetch_spec=fetch_spec)
5741.1.1 by Jelmer Vernooij
Move fetch implementation to InterBranch.
2151
5809.2.1 by Jelmer Vernooij
Deprecate Branch.update_revisions.
2152
    def _update_revisions(self, stop_revision=None, overwrite=False,
5809.2.4 by Jelmer Vernooij
remove unused argument.
2153
            graph=None):
6754.8.13 by Jelmer Vernooij
Avoid needs_write_lock.
2154
        with self.source.lock_read(), self.target.lock_write():
2155
            other_revno, other_last_revision = self.source.last_revision_info()
2156
            stop_revno = None # unknown
2157
            if stop_revision is None:
2158
                stop_revision = other_last_revision
2159
                if _mod_revision.is_null(stop_revision):
2160
                    # if there are no commits, we're done.
2161
                    return
2162
                stop_revno = other_revno
2163
2164
            # what's the current last revision, before we fetch [and change it
2165
            # possibly]
2166
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
2167
            # we fetch here so that we don't process data twice in the common
2168
            # case of having something to pull, and so that the check for
2169
            # already merged can operate on the just fetched graph, which will
2170
            # be cached in memory.
2171
            self.fetch(stop_revision=stop_revision)
2172
            # Check to see if one is an ancestor of the other
2173
            if not overwrite:
2174
                if graph is None:
2175
                    graph = self.target.repository.get_graph()
2176
                if self.target._check_if_descendant_or_diverged(
2177
                        stop_revision, last_rev, graph, self.source):
2178
                    # stop_revision is a descendant of last_rev, but we aren't
2179
                    # overwriting, so we're done.
2180
                    return
2181
            if stop_revno is None:
2182
                if graph is None:
2183
                    graph = self.target.repository.get_graph()
2184
                this_revno, this_last_revision = \
2185
                        self.target.last_revision_info()
2186
                stop_revno = graph.find_distance_to_null(stop_revision,
2187
                                [(other_last_revision, other_revno),
2188
                                 (this_last_revision, this_revno)])
2189
            self.target.set_last_revision_info(stop_revno, stop_revision)
2190
4000.5.9 by Jelmer Vernooij
Add InterBranch.pull().
2191
    def pull(self, overwrite=False, stop_revision=None,
5284.4.1 by Robert Collins
* Fetching was slightly confused about the best code to use and was
2192
             possible_transports=None, run_hooks=True,
4000.5.21 by Jelmer Vernooij
Merge bzr.dev.
2193
             _override_hook_target=None, local=False):
5284.4.1 by Robert Collins
* Fetching was slightly confused about the best code to use and was
2194
        """Pull from source into self, updating my master if any.
4000.5.9 by Jelmer Vernooij
Add InterBranch.pull().
2195
2196
        :param run_hooks: Private parameter - if false, this branch
2197
            is being called because it's the master of the primary branch,
2198
            so it should not run its hooks.
2199
        """
6754.8.13 by Jelmer Vernooij
Avoid needs_write_lock.
2200
        with self.target.lock_write():
2201
            bound_location = self.target.get_bound_location()
2202
            if local and not bound_location:
2203
                raise errors.LocalRequiresBoundBranch()
2204
            master_branch = None
2205
            source_is_master = False
2206
            if bound_location:
2207
                # bound_location comes from a config file, some care has to be
2208
                # taken to relate it to source.user_url
2209
                normalized = urlutils.normalize_url(bound_location)
2210
                try:
2211
                    relpath = self.source.user_transport.relpath(normalized)
2212
                    source_is_master = (relpath == '')
2213
                except (errors.PathNotChild, urlutils.InvalidURL):
2214
                    source_is_master = False
2215
            if not local and bound_location and not source_is_master:
2216
                # not pulling from master, so we need to update master.
2217
                master_branch = self.target.get_master_branch(possible_transports)
2218
                master_branch.lock_write()
5609.50.1 by Vincent Ladeuil
Be more tolerant about ``bound_location`` from config files
2219
            try:
6754.8.13 by Jelmer Vernooij
Avoid needs_write_lock.
2220
                if master_branch:
2221
                    # pull from source into master.
2222
                    master_branch.pull(self.source, overwrite, stop_revision,
2223
                        run_hooks=False)
2224
                return self._pull(overwrite,
2225
                    stop_revision, _hook_master=master_branch,
2226
                    run_hooks=run_hooks,
2227
                    _override_hook_target=_override_hook_target,
2228
                    merge_tags_to_master=not source_is_master)
2229
            finally:
2230
                if master_branch:
2231
                    master_branch.unlock()
4000.5.9 by Jelmer Vernooij
Add InterBranch.pull().
2232
5853.2.2 by Jelmer Vernooij
Make lossy_push an argument to InterBranch.push.
2233
    def push(self, overwrite=False, stop_revision=None, lossy=False,
4211.1.1 by Jelmer Vernooij
Move Branch.push to InterBranch.push.
2234
             _override_hook_source_branch=None):
2235
        """See InterBranch.push.
2236
2237
        This is the basic concrete implementation of push()
2238
5891.1.2 by Andrew Bennetts
Fix a bunch of docstring formatting nits, making pydoctor a bit happier.
2239
        :param _override_hook_source_branch: If specified, run the hooks
2240
            passing this Branch as the source, rather than self.  This is for
2241
            use of RemoteBranch, where push is delegated to the underlying
2242
            vfs-based Branch.
4211.1.1 by Jelmer Vernooij
Move Branch.push to InterBranch.push.
2243
        """
5853.2.2 by Jelmer Vernooij
Make lossy_push an argument to InterBranch.push.
2244
        if lossy:
2245
            raise errors.LossyPushToSameVCS(self.source, self.target)
4211.1.1 by Jelmer Vernooij
Move Branch.push to InterBranch.push.
2246
        # TODO: Public option to disable running hooks - should be trivial but
2247
        # needs tests.
6969.3.1 by Jelmer Vernooij
Use context managers.
2248
        def _run_hooks():
2249
            if _override_hook_source_branch:
2250
                result.source_branch = _override_hook_source_branch
2251
            for hook in Branch.hooks['post_push']:
2252
                hook(result)
5915.1.1 by Andrew Bennetts
Removed bzrlib.branch._run_with_write_locked_target. Use bzrlib.cleanup instead.
2253
6969.3.1 by Jelmer Vernooij
Use context managers.
2254
        with self.source.lock_read(), self.target.lock_write():
2255
            bound_location = self.target.get_bound_location()
2256
            if bound_location and self.target.base != bound_location:
2257
                # there is a master branch.
2258
                #
2259
                # XXX: Why the second check?  Is it even supported for a branch to
2260
                # be bound to itself? -- mbp 20070507
2261
                master_branch = self.target.get_master_branch()
2262
                with master_branch.lock_write():
2263
                    # push into the master from the source branch.
2264
                    master_inter = InterBranch.get(self.source, master_branch)
2265
                    master_inter._basic_push(overwrite, stop_revision)
2266
                    # and push into the target branch from the source. Note that
2267
                    # we push from the source branch again, because it's considered
2268
                    # the highest bandwidth repository.
2269
                    result = self._basic_push(overwrite, stop_revision)
2270
                    result.master_branch = master_branch
2271
                    result.local_branch = self.target
2272
                    _run_hooks()
2273
            else:
2274
                master_branch = None
2275
                # no master branch
2276
                result = self._basic_push(overwrite, stop_revision)
2277
                # TODO: Why set master_branch and local_branch if there's no
2278
                # binding?  Maybe cleaner to just leave them unset? -- mbp
2279
                # 20070504
2280
                result.master_branch = self.target
2281
                result.local_branch = None
2282
                _run_hooks()
2283
            return result
4211.1.1 by Jelmer Vernooij
Move Branch.push to InterBranch.push.
2284
5809.2.3 by Jelmer Vernooij
Kill update_revisions private implementation.
2285
    def _basic_push(self, overwrite, stop_revision):
2286
        """Basic implementation of push without bound branches or hooks.
2287
2288
        Must be called with source read locked and target write locked.
2289
        """
2290
        result = BranchPushResult()
2291
        result.source_branch = self.source
2292
        result.target_branch = self.target
2293
        result.old_revno, result.old_revid = self.target.last_revision_info()
2294
        self.source.update_references(self.target)
6159.2.4 by Jelmer Vernooij
Add --overwrite-tags flag.
2295
        overwrite = _fix_overwrite_type(overwrite)
5809.2.3 by Jelmer Vernooij
Kill update_revisions private implementation.
2296
        if result.old_revid != stop_revision:
2297
            # We assume that during 'push' this repository is closer than
2298
            # the target.
2299
            graph = self.source.repository.get_graph(self.target.repository)
6159.2.4 by Jelmer Vernooij
Add --overwrite-tags flag.
2300
            self._update_revisions(stop_revision,
2301
                overwrite=("history" in overwrite),
2302
                graph=graph)
5809.2.3 by Jelmer Vernooij
Kill update_revisions private implementation.
2303
        if self.source._push_should_merge_tags():
6112.4.4 by Jelmer Vernooij
Fix long lines.
2304
            result.tag_updates, result.tag_conflicts = (
6159.2.4 by Jelmer Vernooij
Add --overwrite-tags flag.
2305
                self.source.tags.merge_to(
2306
                self.target.tags, "tags" in overwrite))
5809.2.3 by Jelmer Vernooij
Kill update_revisions private implementation.
2307
        result.new_revno, result.new_revid = self.target.last_revision_info()
2308
        return result
2309
5284.4.1 by Robert Collins
* Fetching was slightly confused about the best code to use and was
2310
    def _pull(self, overwrite=False, stop_revision=None,
2311
             possible_transports=None, _hook_master=None, run_hooks=True,
5582.5.1 by John Arbash Meinel
Fix bug 701212. Don't set the tags for a master branch during update.
2312
             _override_hook_target=None, local=False,
2313
             merge_tags_to_master=True):
5284.4.1 by Robert Collins
* Fetching was slightly confused about the best code to use and was
2314
        """See Branch.pull.
2315
2316
        This function is the core worker, used by GenericInterBranch.pull to
2317
        avoid duplication when pulling source->master and source->local.
2318
2319
        :param _hook_master: Private parameter - set the branch to
2320
            be supplied as the master to pull hooks.
4000.5.9 by Jelmer Vernooij
Add InterBranch.pull().
2321
        :param run_hooks: Private parameter - if false, this branch
2322
            is being called because it's the master of the primary branch,
2323
            so it should not run its hooks.
5662.2.6 by Jelmer Vernooij
add more tests.
2324
            is being called because it's the master of the primary branch,
2325
            so it should not run its hooks.
5284.4.1 by Robert Collins
* Fetching was slightly confused about the best code to use and was
2326
        :param _override_hook_target: Private parameter - set the branch to be
2327
            supplied as the target_branch to pull hooks.
2328
        :param local: Only update the local branch, and not the bound branch.
4000.5.9 by Jelmer Vernooij
Add InterBranch.pull().
2329
        """
5284.4.1 by Robert Collins
* Fetching was slightly confused about the best code to use and was
2330
        # This type of branch can't be bound.
2331
        if local:
4000.5.21 by Jelmer Vernooij
Merge bzr.dev.
2332
            raise errors.LocalRequiresBoundBranch()
5284.4.1 by Robert Collins
* Fetching was slightly confused about the best code to use and was
2333
        result = PullResult()
2334
        result.source_branch = self.source
2335
        if _override_hook_target is None:
2336
            result.target_branch = self.target
2337
        else:
2338
            result.target_branch = _override_hook_target
6754.8.4 by Jelmer Vernooij
Use new context stuff.
2339
        with self.source.lock_read():
5284.4.1 by Robert Collins
* Fetching was slightly confused about the best code to use and was
2340
            # We assume that during 'pull' the target repository is closer than
2341
            # the source one.
2342
            self.source.update_references(self.target)
2343
            graph = self.target.repository.get_graph(self.source.repository)
2344
            # TODO: Branch formats should have a flag that indicates 
2345
            # that revno's are expensive, and pull() should honor that flag.
2346
            # -- JRV20090506
2347
            result.old_revno, result.old_revid = \
2348
                self.target.last_revision_info()
6159.2.4 by Jelmer Vernooij
Add --overwrite-tags flag.
2349
            overwrite = _fix_overwrite_type(overwrite)
2350
            self._update_revisions(stop_revision,
2351
                overwrite=("history" in overwrite),
5809.2.1 by Jelmer Vernooij
Deprecate Branch.update_revisions.
2352
                graph=graph)
5284.4.1 by Robert Collins
* Fetching was slightly confused about the best code to use and was
2353
            # TODO: The old revid should be specified when merging tags, 
2354
            # so a tags implementation that versions tags can only 
2355
            # pull in the most recent changes. -- JRV20090506
6112.4.4 by Jelmer Vernooij
Fix long lines.
2356
            result.tag_updates, result.tag_conflicts = (
6159.2.4 by Jelmer Vernooij
Add --overwrite-tags flag.
2357
                self.source.tags.merge_to(self.target.tags,
2358
                    "tags" in overwrite,
6112.4.4 by Jelmer Vernooij
Fix long lines.
2359
                    ignore_master=not merge_tags_to_master))
5284.4.1 by Robert Collins
* Fetching was slightly confused about the best code to use and was
2360
            result.new_revno, result.new_revid = self.target.last_revision_info()
2361
            if _hook_master:
2362
                result.master_branch = _hook_master
2363
                result.local_branch = result.target_branch
2364
            else:
2365
                result.master_branch = result.target_branch
2366
                result.local_branch = None
2367
            if run_hooks:
2368
                for hook in Branch.hooks['post_pull']:
2369
                    hook(result)
6754.8.4 by Jelmer Vernooij
Use new context stuff.
2370
            return result
4000.5.9 by Jelmer Vernooij
Add InterBranch.pull().
2371
2372
4000.5.1 by Jelmer Vernooij
Add InterBranch.
2373
InterBranch.register_optimiser(GenericInterBranch)