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