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