/brz/remove-bazaar

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