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