/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5582.5.1 by John Arbash Meinel
Fix bug 701212. Don't set the tags for a master branch during update.
1
# Copyright (C) 2005-2011 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
17
4273.1.1 by Aaron Bentley
Implement branch format for tree references.
18
from cStringIO import StringIO
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
19
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
20
from bzrlib.lazy_import import lazy_import
21
lazy_import(globals(), """
6105.1.1 by Jelmer Vernooij
Fix "pydoc bzrlib.branch" by importing modules, not objects, using lazy_import.
22
import itertools
1551.8.4 by Aaron Bentley
Tweak import style
23
from bzrlib import (
1911.2.7 by John Arbash Meinel
[merge] bzr.dev 1924
24
        bzrdir,
25
        cache_utf8,
5915.1.1 by Andrew Bennetts
Removed bzrlib.branch._run_with_write_locked_target. Use bzrlib.cleanup instead.
26
        cleanup,
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
27
        config as _mod_config,
2592.3.113 by Robert Collins
Various -Devil checks in branch.py.
28
        debug,
1911.2.7 by John Arbash Meinel
[merge] bzr.dev 1924
29
        errors,
5535.3.45 by Andrew Bennetts
Merge fetch-all-tags-309682.
30
        fetch,
5535.3.28 by Andrew Bennetts
Implement fetching tags during branch pull. Needs more tests.
31
        graph as _mod_graph,
1911.2.7 by John Arbash Meinel
[merge] bzr.dev 1924
32
        lockdir,
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
33
        lockable_files,
5284.4.1 by Robert Collins
* Fetching was slightly confused about the best code to use and was
34
        remote,
3287.6.8 by Robert Collins
Reduce code duplication as per review.
35
        repository,
1996.3.12 by John Arbash Meinel
Change how 'revision' is imported to avoid problems later
36
        revision as _mod_revision,
4273.1.1 by Aaron Bentley
Implement branch format for tree references.
37
        rio,
6105.1.1 by Jelmer Vernooij
Fix "pydoc bzrlib.branch" by importing modules, not objects, using lazy_import.
38
        tag as _mod_tag,
1911.2.9 by John Arbash Meinel
Fix accidental import removal
39
        transport,
4509.3.6 by Martin Pool
Show progress bar while unstacking
40
        ui,
1911.2.7 by John Arbash Meinel
[merge] bzr.dev 1924
41
        urlutils,
1551.8.4 by Aaron Bentley
Tweak import style
42
        )
1996.3.3 by John Arbash Meinel
Shave off another 40ms by demand loading branch and bzrdir
43
""")
44
5697.2.1 by Jelmer Vernooij
Move weave branch to bzrlib.branch_weave.
45
from bzrlib import (
46
    controldir,
47
    )
48
from bzrlib.decorators import (
49
    needs_read_lock,
50
    needs_write_lock,
51
    only_raises,
52
    )
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
53
from bzrlib.hooks import Hooks
3978.3.2 by Jelmer Vernooij
Move most of push to IterGenericBranchBzrDir.
54
from bzrlib.inter import InterObject
5200.3.6 by Robert Collins
Make all lock methods return Result objects, rather than lock_read returning self, as per John's review.
55
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
4032.3.1 by Robert Collins
Add a BranchFormat.network_name() method as preparation for creating branches via RPC calls.
56
from bzrlib import registry
3407.2.11 by Martin Pool
Deprecate Branch.abspath
57
from bzrlib.symbol_versioning import (
58
    deprecated_in,
59
    deprecated_method,
60
    )
3200.1.1 by James Westby
Make pull --quiet more quiet. Fixes #185907.
61
from bzrlib.trace import mutter, mutter_callsite, note, is_quiet
1104 by Martin Pool
- Add a simple UIFactory
62
1094 by Martin Pool
- merge aaron's merge improvements 999..1008
63
5363.2.10 by Jelmer Vernooij
base ControlDir on ControlComponent.
64
class Branch(controldir.ControlComponent):
1 by mbp at sourcefrog
import from baz patch-364
65
    """Branch holding a history of revisions.
66
5158.6.2 by Martin Pool
Branch provides user_url etc
67
    :ivar base:
68
        Base directory/url of the branch; using control_url and
69
        control_transport is more standardized.
5609.25.6 by Andrew Bennetts
Docstring tweaks.
70
    :ivar hooks: An instance of BranchHooks.
71
    :ivar _master_branch_cache: cached result of get_master_branch, see
72
        _clear_cached_state.
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
73
    """
1534.4.1 by Robert Collins
Allow parameterisation of the branch initialisation for bzrlib.
74
    # this is really an instance variable - FIXME move it there
75
    # - RBC 20060112
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
76
    base = None
77
5158.6.2 by Martin Pool
Branch provides user_url etc
78
    @property
79
    def control_transport(self):
80
        return self._transport
81
82
    @property
83
    def user_transport(self):
84
        return self.bzrdir.user_transport
85
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
86
    def __init__(self, *ignored, **ignored_too):
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.
87
        self.tags = self._format.make_tags(self)
2375.1.3 by Andrew Bennetts
Don't use Branch.get_transaction to cache revision history.
88
        self._revision_history_cache = None
2418.5.6 by John Arbash Meinel
Cache the revision_id => revno map as appropriate.
89
        self._revision_id_to_revno_cache = None
3949.2.6 by Ian Clatworthy
review feedback from jam
90
        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().
91
        self._partial_revision_history_cache = []
5535.2.1 by Andrew Bennetts
Cache a branch's tags during a read-lock.
92
        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.
93
        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.
94
        self._master_branch_cache = None
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
95
        self._merge_sorted_revisions_cache = None
3221.11.11 by Robert Collins
Ensure opening a stacked branch gives a ready to use repository.
96
        self._open_hook()
3681.1.1 by Robert Collins
Create a new hook Branch.open. (Robert Collins)
97
        hooks = Branch.hooks['open']
98
        for hook in hooks:
99
            hook(self)
3221.11.11 by Robert Collins
Ensure opening a stacked branch gives a ready to use repository.
100
101
    def _open_hook(self):
102
        """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.
103
4379.2.2 by John Arbash Meinel
Change the Repository.add_fallback_repository() contract slightly.
104
    def _activate_fallback_location(self, url):
4226.1.3 by Robert Collins
Lift Branch.set_stacked_on_url up from BzrBranch7.
105
        """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.
106
        for existing_fallback_repo in self.repository._fallback_repositories:
107
            if existing_fallback_repo.user_url == url:
108
                # This fallback is already configured.  This probably only
109
                # happens because BzrDir.sprout is a horrible mess.  To avoid
110
                # 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.
111
                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.
112
                return
4288.1.10 by Robert Collins
Fix up lock correctness to deal with adding fallback repositories to locked branch objects.
113
        repo = self._get_fallback_repository(url)
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.
114
        if repo.has_same_location(self.repository):
5158.6.3 by Martin Pool
Update some Branch calls to use ControlComponent style.
115
            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.
116
        self.repository.add_fallback_repository(repo)
4226.1.3 by Robert Collins
Lift Branch.set_stacked_on_url up from BzrBranch7.
117
1687.1.8 by Robert Collins
Teach Branch about break_lock.
118
    def break_lock(self):
119
        """Break a lock if one is present from another instance.
120
121
        Uses the ui factory to ask for confirmation if the lock may be from
122
        an active process.
123
124
        This will probe the repository for its lock as well.
125
        """
126
        self.control_files.break_lock()
127
        self.repository.break_lock()
1687.1.10 by Robert Collins
Branch.break_lock should handle bound branches too
128
        master = self.get_master_branch()
129
        if master is not None:
130
            master.break_lock()
1687.1.8 by Robert Collins
Teach Branch about break_lock.
131
4226.1.3 by Robert Collins
Lift Branch.set_stacked_on_url up from BzrBranch7.
132
    def _check_stackable_repo(self):
133
        if not self.repository._format.supports_external_lookups:
134
            raise errors.UnstackableRepositoryFormat(self.repository._format,
135
                self.repository.base)
136
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().
137
    def _extend_partial_history(self, stop_index=None, stop_revision=None):
138
        """Extend the partial history to include a given index
139
140
        If a stop_index is supplied, stop when that index has been reached.
141
        If a stop_revision is supplied, stop when that revision is
142
        encountered.  Otherwise, stop when the beginning of history is
143
        reached.
144
145
        :param stop_index: The index which should be present.  When it is
146
            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.
147
        :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().
148
            it is encountered, history extension will stop.
149
        """
150
        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.
151
            self._partial_revision_history_cache = [self.last_revision()]
152
        repository._iter_for_revno(
153
            self.repository, self._partial_revision_history_cache,
154
            stop_index=stop_index, stop_revision=stop_revision)
155
        if self._partial_revision_history_cache[-1] == _mod_revision.NULL_REVISION:
156
            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().
157
4332.3.5 by Robert Collins
Add Branch._get_check_refs.
158
    def _get_check_refs(self):
159
        """Get the references needed for check().
160
161
        See bzrlib.check.
162
        """
163
        revid = self.last_revision()
164
        return [('revision-existence', revid), ('lefthand-distance', revid)]
165
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
166
    @staticmethod
2806.2.2 by Vincent Ladeuil
Fix #128076 and #131396 by reusing bound branch transport.
167
    def open(base, _unsupported=False, possible_transports=None):
1815.1.1 by Jelmer Vernooij
Fix copy-pasted comment.
168
        """Open the branch rooted at base.
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
169
1815.1.1 by Jelmer Vernooij
Fix copy-pasted comment.
170
        For instance, if the branch is at URL/.bzr/branch,
171
        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.
172
        """
2806.2.2 by Vincent Ladeuil
Fix #128076 and #131396 by reusing bound branch transport.
173
        control = bzrdir.BzrDir.open(base, _unsupported,
174
                                     possible_transports=possible_transports)
5051.3.4 by Jelmer Vernooij
Support name to BzrDir.open_branch.
175
        return control.open_branch(unsupported=_unsupported)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
176
177
    @staticmethod
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
178
    def open_from_transport(transport, name=None, _unsupported=False):
2485.8.35 by Vincent Ladeuil
Fix pull multiple connections.
179
        """Open the branch rooted at transport"""
180
        control = bzrdir.BzrDir.open_from_transport(transport, _unsupported)
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
181
        return control.open_branch(name=name, unsupported=_unsupported)
2485.8.35 by Vincent Ladeuil
Fix pull multiple connections.
182
183
    @staticmethod
2485.8.37 by Vincent Ladeuil
Fix merge multiple connections. Test suite *not* passing (sftp
184
    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
185
        """Open an existing branch which contains url.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
186
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
187
        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
188
189
        Basically we keep looking up until we find the control directory or
190
        run into the root.  If there isn't one, raises NotBranchError.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
191
        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.
192
        format, UnknownFormatError or UnsupportedFormatError are raised.
1442.1.64 by Robert Collins
Branch.open_containing now returns a tuple (Branch, relative-path).
193
        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.
194
        """
2485.8.37 by Vincent Ladeuil
Fix merge multiple connections. Test suite *not* passing (sftp
195
        control, relpath = bzrdir.BzrDir.open_containing(url,
196
                                                         possible_transports)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
197
        return control.open_branch(), relpath
1534.4.1 by Robert Collins
Allow parameterisation of the branch initialisation for bzrlib.
198
4032.3.5 by Robert Collins
Move BzrBranch._push_should_merge_tags to Branch.
199
    def _push_should_merge_tags(self):
200
        """Should _basic_push merge this branch's tags into the target?
201
202
        The default implementation returns False if this branch has no tags,
203
        and True the rest of the time.  Subclasses may override this.
204
        """
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.
205
        return self.supports_tags() and self.tags.get_tag_dict()
4032.3.5 by Robert Collins
Move BzrBranch._push_should_merge_tags to Branch.
206
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
207
    def get_config(self):
5284.3.1 by Robert Collins
Document bzrlib.branch.Branch.get_config.
208
        """Get a bzrlib.config.BranchConfig for this Branch.
209
210
        This can then be used to get and set configuration options for the
211
        branch.
212
213
        :return: A bzrlib.config.BranchConfig.
214
        """
6105.1.1 by Jelmer Vernooij
Fix "pydoc bzrlib.branch" by importing modules, not objects, using lazy_import.
215
        return _mod_config.BranchConfig(self)
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
216
4226.1.5 by Robert Collins
Reinstate the use of the Branch.get_config_file verb.
217
    def _get_config(self):
218
        """Get the concrete config for just the config in this branch.
219
220
        This is not intended for client use; see Branch.get_config for the
221
        public API.
222
223
        Added in 1.14.
224
225
        :return: An object supporting get_option and set_option.
226
        """
227
        raise NotImplementedError(self._get_config)
228
4226.1.3 by Robert Collins
Lift Branch.set_stacked_on_url up from BzrBranch7.
229
    def _get_fallback_repository(self, url):
230
        """Get the repository we fallback to at url."""
231
        url = urlutils.join(self.base, url)
5051.3.14 by Jelmer Vernooij
Remove use of BzrDir.open_branch() without arguments.
232
        a_branch = Branch.open(url,
4226.1.4 by Robert Collins
Simplify code in RemoteBranch to use helpers from Branch.
233
            possible_transports=[self.bzrdir.root_transport])
5051.3.14 by Jelmer Vernooij
Remove use of BzrDir.open_branch() without arguments.
234
        return a_branch.repository
4226.1.3 by Robert Collins
Lift Branch.set_stacked_on_url up from BzrBranch7.
235
5535.2.1 by Andrew Bennetts
Cache a branch's tags during a read-lock.
236
    @needs_read_lock
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.
237
    def _get_tags_bytes(self):
238
        """Get the bytes of a serialised tags dict.
239
240
        Note that not all branches support tags, nor do all use the same tags
241
        logic: this method is specific to BasicTags. Other tag implementations
242
        may use the same method name and behave differently, safely, because
243
        of the double-dispatch via
244
        format.make_tags->tags_instance->get_tags_dict.
245
246
        :return: The bytes of the tags file.
247
        :seealso: Branch._set_tags_bytes.
248
        """
5535.2.1 by Andrew Bennetts
Cache a branch's tags during a read-lock.
249
        if self._tags_bytes is None:
250
            self._tags_bytes = self._transport.get_bytes('tags')
251
        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.
252
3815.3.4 by Marius Kruger
When doing a `commit --local`, don't try to connect to the master branch.
253
    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.
254
        config = self.get_config()
3815.3.4 by Marius Kruger
When doing a `commit --local`, don't try to connect to the master branch.
255
        # explicit overrides master, but don't look for master if local is True
256
        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
257
            try:
258
                master = self.get_master_branch(possible_transports)
5050.7.4 by Parth Malwankar
fixed recursion detection to handle shared repos
259
                if master and self.user_url == master.user_url:
5050.7.5 by Parth Malwankar
better error message for RecursiveBind
260
                    raise errors.RecursiveBind(self.user_url)
3565.6.10 by Marius Kruger
Silently fall back to local implicit nick if the master is unavailable
261
                if master is not None:
262
                    # return the master branch value
3815.3.3 by Marius Kruger
apply Martin's fix for #293440
263
                    return master.nick
5050.7.2 by Parth Malwankar
recursive binding now shows a clear error
264
            except errors.RecursiveBind, e:
265
                raise e
3565.6.10 by Marius Kruger
Silently fall back to local implicit nick if the master is unavailable
266
            except errors.BzrError, e:
267
                # Silently fall back to local implicit nick if the master is
268
                # unavailable
269
                mutter("Could not connect to bound branch, "
270
                    "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.
271
        return config.get_nickname()
1185.35.11 by Aaron Bentley
Added support for branch nicks
272
273
    def _set_nick(self, nick):
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
274
        self.get_config().set_user_option('nickname', nick, warn_masked=True)
1185.35.11 by Aaron Bentley
Added support for branch nicks
275
276
    nick = property(_get_nick, _set_nick)
1694.2.6 by Martin Pool
[merge] bzr.dev
277
278
    def is_locked(self):
1910.3.2 by Andrew Bennetts
Improve some NotImplementedErrors.
279
        raise NotImplementedError(self.is_locked)
1694.2.6 by Martin Pool
[merge] bzr.dev
280
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.
281
    def _lefthand_history(self, revision_id, last_rev=None,
282
                          other_branch=None):
283
        if 'evil' in debug.debug_flags:
284
            mutter_callsite(4, "_lefthand_history scales with history.")
285
        # stop_revision must be a descendant of last_revision
286
        graph = self.repository.get_graph()
287
        if last_rev is not None:
288
            if not graph.is_ancestor(last_rev, revision_id):
289
                # our previous tip is not merged into stop_revision
290
                raise errors.DivergedBranches(self, other_branch)
291
        # make a new revision history from the graph
292
        parents_map = graph.get_parent_map([revision_id])
293
        if revision_id not in parents_map:
294
            raise errors.NoSuchRevision(self, revision_id)
295
        current_rev_id = revision_id
296
        new_history = []
297
        check_not_reserved_id = _mod_revision.check_not_reserved_id
298
        # Do not include ghosts or graph origin in revision_history
299
        while (current_rev_id in parents_map and
300
               len(parents_map[current_rev_id]) > 0):
301
            check_not_reserved_id(current_rev_id)
302
            new_history.append(current_rev_id)
303
            current_rev_id = parents_map[current_rev_id][0]
304
            parents_map = graph.get_parent_map([current_rev_id])
305
        new_history.reverse()
306
        return new_history
307
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
308
    def lock_write(self, token=None):
309
        """Lock the branch for write operations.
310
311
        :param token: A token to permit reacquiring a previously held and
312
            preserved lock.
313
        :return: A BranchWriteLockResult.
314
        """
1910.3.2 by Andrew Bennetts
Improve some NotImplementedErrors.
315
        raise NotImplementedError(self.lock_write)
1694.2.6 by Martin Pool
[merge] bzr.dev
316
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
317
    def lock_read(self):
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
318
        """Lock the branch for read operations.
319
5200.3.6 by Robert Collins
Make all lock methods return Result objects, rather than lock_read returning self, as per John's review.
320
        :return: A bzrlib.lock.LogicalLockResult.
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
321
        """
1910.3.2 by Andrew Bennetts
Improve some NotImplementedErrors.
322
        raise NotImplementedError(self.lock_read)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
323
324
    def unlock(self):
1910.3.2 by Andrew Bennetts
Improve some NotImplementedErrors.
325
        raise NotImplementedError(self.unlock)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
326
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
327
    def peek_lock_mode(self):
328
        """Return lock mode for the Branch: 'r', 'w' or None"""
1185.70.6 by Martin Pool
review fixups from John
329
        raise NotImplementedError(self.peek_lock_mode)
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
330
1694.2.6 by Martin Pool
[merge] bzr.dev
331
    def get_physical_lock_status(self):
1910.3.2 by Andrew Bennetts
Improve some NotImplementedErrors.
332
        raise NotImplementedError(self.get_physical_lock_status)
1694.2.6 by Martin Pool
[merge] bzr.dev
333
2418.5.12 by John Arbash Meinel
Move functions from BzrBranch to base Branch object.
334
    @needs_read_lock
3949.2.6 by Ian Clatworthy
review feedback from jam
335
    def dotted_revno_to_revision_id(self, revno, _cache_reverse=False):
3949.2.1 by Ian Clatworthy
Branch.dotted_revno_to_revision_id API
336
        """Return the revision_id for a dotted revno.
337
338
        :param revno: a tuple like (1,) or (1,1,2)
3949.2.4 by Ian Clatworthy
add top level revno cache
339
        :param _cache_reverse: a private parameter enabling storage
340
           of the reverse mapping in a top level cache. (This should
341
           only be done in selective circumstances as we want to
342
           avoid having the mapping cached multiple times.)
3949.2.1 by Ian Clatworthy
Branch.dotted_revno_to_revision_id API
343
        :return: the revision_id
344
        :raises errors.NoSuchRevision: if the revno doesn't exist
345
        """
3949.2.6 by Ian Clatworthy
review feedback from jam
346
        rev_id = self._do_dotted_revno_to_revision_id(revno)
347
        if _cache_reverse:
348
            self._partial_revision_id_to_revno_cache[rev_id] = revno
3949.2.4 by Ian Clatworthy
add top level revno cache
349
        return rev_id
3949.2.1 by Ian Clatworthy
Branch.dotted_revno_to_revision_id API
350
3949.2.6 by Ian Clatworthy
review feedback from jam
351
    def _do_dotted_revno_to_revision_id(self, revno):
3949.2.1 by Ian Clatworthy
Branch.dotted_revno_to_revision_id API
352
        """Worker function for dotted_revno_to_revision_id.
353
354
        Subclasses should override this if they wish to
355
        provide a more efficient implementation.
356
        """
357
        if len(revno) == 1:
358
            return self.get_rev_id(revno[0])
359
        revision_id_to_revno = self.get_revision_id_to_revno_map()
3949.2.6 by Ian Clatworthy
review feedback from jam
360
        revision_ids = [revision_id for revision_id, this_revno
361
                        in revision_id_to_revno.iteritems()
362
                        if revno == this_revno]
363
        if len(revision_ids) == 1:
364
            return revision_ids[0]
3949.2.1 by Ian Clatworthy
Branch.dotted_revno_to_revision_id API
365
        else:
366
            revno_str = '.'.join(map(str, revno))
367
            raise errors.NoSuchRevision(self, revno_str)
368
369
    @needs_read_lock
3949.2.3 by Ian Clatworthy
add Branch.revision_id_to_dotted_revno()
370
    def revision_id_to_dotted_revno(self, revision_id):
371
        """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.
372
3949.2.3 by Ian Clatworthy
add Branch.revision_id_to_dotted_revno()
373
        :return: a tuple like (1,) or (400,1,3).
374
        """
3949.2.6 by Ian Clatworthy
review feedback from jam
375
        return self._do_revision_id_to_dotted_revno(revision_id)
3949.2.3 by Ian Clatworthy
add Branch.revision_id_to_dotted_revno()
376
3949.2.6 by Ian Clatworthy
review feedback from jam
377
    def _do_revision_id_to_dotted_revno(self, revision_id):
3949.2.3 by Ian Clatworthy
add Branch.revision_id_to_dotted_revno()
378
        """Worker function for revision_id_to_revno."""
3949.2.4 by Ian Clatworthy
add top level revno cache
379
        # Try the caches if they are loaded
3949.2.6 by Ian Clatworthy
review feedback from jam
380
        result = self._partial_revision_id_to_revno_cache.get(revision_id)
381
        if result is not None:
382
            return result
383
        if self._revision_id_to_revno_cache:
3949.2.3 by Ian Clatworthy
add Branch.revision_id_to_dotted_revno()
384
            result = self._revision_id_to_revno_cache.get(revision_id)
3949.2.6 by Ian Clatworthy
review feedback from jam
385
            if result is None:
386
                raise errors.NoSuchRevision(self, revision_id)
387
        # Try the mainline as it's optimised
388
        try:
389
            revno = self.revision_id_to_revno(revision_id)
390
            return (revno,)
391
        except errors.NoSuchRevision:
392
            # We need to load and use the full revno map after all
393
            result = self.get_revision_id_to_revno_map().get(revision_id)
394
            if result is None:
395
                raise errors.NoSuchRevision(self, revision_id)
3949.2.3 by Ian Clatworthy
add Branch.revision_id_to_dotted_revno()
396
        return result
397
3949.2.7 by Ian Clatworthy
fix accidental needs_read_lock removal
398
    @needs_read_lock
2418.5.12 by John Arbash Meinel
Move functions from BzrBranch to base Branch object.
399
    def get_revision_id_to_revno_map(self):
400
        """Return the revision_id => dotted revno map.
401
402
        This will be regenerated on demand, but will be cached.
403
404
        :return: A dictionary mapping revision_id => dotted revno.
405
            This dictionary should not be modified by the caller.
406
        """
407
        if self._revision_id_to_revno_cache is not None:
408
            mapping = self._revision_id_to_revno_cache
409
        else:
410
            mapping = self._gen_revno_map()
411
            self._cache_revision_id_to_revno(mapping)
412
        # TODO: jam 20070417 Since this is being cached, should we be returning
413
        #       a copy?
414
        # I would rather not, and instead just declare that users should not
415
        # modify the return value.
416
        return mapping
417
418
    def _gen_revno_map(self):
419
        """Create a new mapping from revision ids to dotted revnos.
420
421
        Dotted revnos are generated based on the current tip in the revision
422
        history.
423
        This is the worker function for get_revision_id_to_revno_map, which
424
        just caches the return value.
425
426
        :return: A dictionary mapping revision_id => dotted revno.
427
        """
3949.3.1 by Ian Clatworthy
introduce Branch.merge_sorted_revisions API
428
        revision_id_to_revno = dict((rev_id, revno)
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
429
            for rev_id, depth, revno, end_of_merge
430
             in self.iter_merge_sorted_revisions())
3949.3.1 by Ian Clatworthy
introduce Branch.merge_sorted_revisions API
431
        return revision_id_to_revno
432
433
    @needs_read_lock
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
434
    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()
435
            stop_revision_id=None, stop_rule='exclude', direction='reverse'):
3949.3.2 by Ian Clatworthy
feedback from jam
436
        """Walk the revisions for a branch in merge sorted order.
3949.3.1 by Ian Clatworthy
introduce Branch.merge_sorted_revisions API
437
3949.3.8 by Ian Clatworthy
feedback from poolie
438
        Merge sorted order is the output from a merge-aware,
439
        topological sort, i.e. all parents come before their
440
        children going forward; the opposite for reverse.
441
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
442
        :param start_revision_id: the revision_id to begin walking from.
443
            If None, the branch tip is used.
444
        :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()
445
            after. If None, the rest of history is included.
446
        :param stop_rule: if stop_revision_id is not None, the precise rule
447
            to use for termination:
5891.1.3 by Andrew Bennetts
Move docstring formatting fixes.
448
3960.3.1 by Ian Clatworthy
add stop_rule to Branch.iter_merge_sorted_revisions()
449
            * 'exclude' - leave the stop revision out of the result (default)
450
            * 'include' - the stop revision is the last item in the result
451
            * 'with-merges' - include the stop revision and all of its
452
              merged revisions in the result
5155.1.5 by Vincent Ladeuil
Fixed as per Andrew's review.
453
            * 'with-merges-without-common-ancestry' - filter out revisions 
454
              that are in both ancestries
3949.3.3 by Ian Clatworthy
simplify the meaning of forward to be appropriate to this layer
455
        :param direction: either 'reverse' or 'forward':
5891.1.3 by Andrew Bennetts
Move docstring formatting fixes.
456
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
457
            * reverse means return the start_revision_id first, i.e.
458
              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
459
            * forward returns tuples in the opposite order to reverse.
460
              Note in particular that forward does *not* do any intelligent
461
              ordering w.r.t. depth as some clients of this API may like.
3949.3.8 by Ian Clatworthy
feedback from poolie
462
              (If required, that ought to be done at higher layers.)
463
464
        :return: an iterator over (revision_id, depth, revno, end_of_merge)
465
            tuples where:
466
467
            * revision_id: the unique id of the revision
468
            * depth: How many levels of merging deep this node has been
469
              found.
470
            * revno_sequence: This field provides a sequence of
471
              revision numbers for all revisions. The format is:
472
              (REVNO, BRANCHNUM, BRANCHREVNO). BRANCHNUM is the number of the
473
              branch that the revno is on. From left to right the REVNO numbers
474
              are the sequence numbers within that branch of the revision.
475
            * end_of_merge: When True the next node (earlier in history) is
476
              part of a different merge.
3949.3.1 by Ian Clatworthy
introduce Branch.merge_sorted_revisions API
477
        """
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
478
        # Note: depth and revno values are in the context of the branch so
479
        # we need the full graph to get stable numbers, regardless of the
480
        # start_revision_id.
481
        if self._merge_sorted_revisions_cache is None:
482
            last_revision = self.last_revision()
4913.4.2 by Jelmer Vernooij
Add Repository.get_known_graph_ancestry.
483
            known_graph = self.repository.get_known_graph_ancestry(
484
                [last_revision])
4593.5.34 by John Arbash Meinel
Change the KnownGraph.merge_sort api.
485
            self._merge_sorted_revisions_cache = known_graph.merge_sort(
4913.4.2 by Jelmer Vernooij
Add Repository.get_known_graph_ancestry.
486
                last_revision)
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
487
        filtered = self._filter_merge_sorted_revisions(
488
            self._merge_sorted_revisions_cache, start_revision_id,
3960.3.1 by Ian Clatworthy
add stop_rule to Branch.iter_merge_sorted_revisions()
489
            stop_revision_id, stop_rule)
5097.1.5 by Vincent Ladeuil
First attempt at fixing the bug, fortunately the bug report exhibits an
490
        # Make sure we don't return revisions that are not part of the
491
        # start_revision_id ancestry.
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
492
        filtered = self._filter_start_non_ancestors(filtered)
3949.3.2 by Ian Clatworthy
feedback from jam
493
        if direction == 'reverse':
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
494
            return filtered
3949.3.2 by Ian Clatworthy
feedback from jam
495
        if direction == 'forward':
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
496
            return reversed(list(filtered))
3949.3.2 by Ian Clatworthy
feedback from jam
497
        else:
498
            raise ValueError('invalid direction %r' % direction)
2418.5.12 by John Arbash Meinel
Move functions from BzrBranch to base Branch object.
499
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
500
    def _filter_merge_sorted_revisions(self, merge_sorted_revisions,
3960.3.1 by Ian Clatworthy
add stop_rule to Branch.iter_merge_sorted_revisions()
501
        start_revision_id, stop_revision_id, stop_rule):
3949.3.7 by Ian Clatworthy
drop seqnum from in-memory cache
502
        """Iterate over an inclusive range of sorted revisions."""
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
503
        rev_iter = iter(merge_sorted_revisions)
504
        if start_revision_id is not None:
4593.5.34 by John Arbash Meinel
Change the KnownGraph.merge_sort api.
505
            for node in rev_iter:
5988.1.2 by Jelmer Vernooij
Fix log.
506
                rev_id = node.key
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
507
                if rev_id != start_revision_id:
508
                    continue
509
                else:
3936.3.30 by Ian Clatworthy
use iter_merge_sorted_revisions() with stop_range feature
510
                    # The decision to include the start or not
511
                    # depends on the stop_rule if a stop is provided
4593.5.34 by John Arbash Meinel
Change the KnownGraph.merge_sort api.
512
                    # 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.
513
                    rev_iter = itertools.chain(iter([node]), rev_iter)
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
514
                    break
3960.3.1 by Ian Clatworthy
add stop_rule to Branch.iter_merge_sorted_revisions()
515
        if stop_revision_id is None:
4593.5.34 by John Arbash Meinel
Change the KnownGraph.merge_sort api.
516
            # Yield everything
517
            for node in rev_iter:
5988.1.2 by Jelmer Vernooij
Fix log.
518
                rev_id = node.key
4593.5.34 by John Arbash Meinel
Change the KnownGraph.merge_sort api.
519
                yield (rev_id, node.merge_depth, node.revno,
520
                       node.end_of_merge)
3960.3.1 by Ian Clatworthy
add stop_rule to Branch.iter_merge_sorted_revisions()
521
        elif stop_rule == 'exclude':
4593.5.34 by John Arbash Meinel
Change the KnownGraph.merge_sort api.
522
            for node in rev_iter:
5988.1.2 by Jelmer Vernooij
Fix log.
523
                rev_id = node.key
3960.3.1 by Ian Clatworthy
add stop_rule to Branch.iter_merge_sorted_revisions()
524
                if rev_id == stop_revision_id:
525
                    return
4593.5.34 by John Arbash Meinel
Change the KnownGraph.merge_sort api.
526
                yield (rev_id, node.merge_depth, node.revno,
527
                       node.end_of_merge)
3960.3.1 by Ian Clatworthy
add stop_rule to Branch.iter_merge_sorted_revisions()
528
        elif stop_rule == 'include':
4593.5.34 by John Arbash Meinel
Change the KnownGraph.merge_sort api.
529
            for node in rev_iter:
5988.1.2 by Jelmer Vernooij
Fix log.
530
                rev_id = node.key
4593.5.34 by John Arbash Meinel
Change the KnownGraph.merge_sort api.
531
                yield (rev_id, node.merge_depth, node.revno,
532
                       node.end_of_merge)
3960.3.1 by Ian Clatworthy
add stop_rule to Branch.iter_merge_sorted_revisions()
533
                if rev_id == stop_revision_id:
534
                    return
5097.1.11 by Vincent Ladeuil
Fix bug #320119 in a crude way.
535
        elif stop_rule == 'with-merges-without-common-ancestry':
536
            # We want to exclude all revisions that are already part of the
537
            # stop_revision_id ancestry.
538
            graph = self.repository.get_graph()
5155.1.3 by Vincent Ladeuil
Fix the performance by finding the relevant subgraph once.
539
            ancestors = graph.find_unique_ancestors(start_revision_id,
540
                                                    [stop_revision_id])
5097.1.11 by Vincent Ladeuil
Fix bug #320119 in a crude way.
541
            for node in rev_iter:
5988.1.2 by Jelmer Vernooij
Fix log.
542
                rev_id = node.key
5155.1.3 by Vincent Ladeuil
Fix the performance by finding the relevant subgraph once.
543
                if rev_id not in ancestors:
5097.1.11 by Vincent Ladeuil
Fix bug #320119 in a crude way.
544
                    continue
545
                yield (rev_id, node.merge_depth, node.revno,
546
                       node.end_of_merge)
3960.3.1 by Ian Clatworthy
add stop_rule to Branch.iter_merge_sorted_revisions()
547
        elif stop_rule == 'with-merges':
3960.3.4 by Ian Clatworthy
implement with-merges by checking for left-hand parent, not depth
548
            stop_rev = self.repository.get_revision(stop_revision_id)
549
            if stop_rev.parent_ids:
4511.3.15 by Marius Kruger
mainline_stop_rev -> left_parent
550
                left_parent = stop_rev.parent_ids[0]
3960.3.4 by Ian Clatworthy
implement with-merges by checking for left-hand parent, not depth
551
            else:
4511.3.15 by Marius Kruger
mainline_stop_rev -> left_parent
552
                left_parent = _mod_revision.NULL_REVISION
553
            # left_parent is the actual revision we want to stop logging at,
554
            # 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.
555
            reached_stop_revision_id = False
4511.3.12 by Marius Kruger
ununinvert logic and improve some variable names.
556
            revision_id_whitelist = []
4593.5.34 by John Arbash Meinel
Change the KnownGraph.merge_sort api.
557
            for node in rev_iter:
5988.1.2 by Jelmer Vernooij
Fix log.
558
                rev_id = node.key
4511.3.15 by Marius Kruger
mainline_stop_rev -> left_parent
559
                if rev_id == left_parent:
560
                    # reached the left parent after the stop_revision
3960.3.1 by Ian Clatworthy
add stop_rule to Branch.iter_merge_sorted_revisions()
561
                    return
4511.3.12 by Marius Kruger
ununinvert logic and improve some variable names.
562
                if (not reached_stop_revision_id or
563
                        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.
564
                    yield (rev_id, node.merge_depth, node.revno,
4593.5.34 by John Arbash Meinel
Change the KnownGraph.merge_sort api.
565
                       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.
566
                    if reached_stop_revision_id or rev_id == stop_revision_id:
567
                        # only do the merged revs of rev_id from now on
568
                        rev = self.repository.get_revision(rev_id)
569
                        if rev.parent_ids:
570
                            reached_stop_revision_id = True
4511.3.12 by Marius Kruger
ununinvert logic and improve some variable names.
571
                            revision_id_whitelist.extend(rev.parent_ids)
3960.3.1 by Ian Clatworthy
add stop_rule to Branch.iter_merge_sorted_revisions()
572
        else:
573
            raise ValueError('invalid stop_rule %r' % stop_rule)
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
574
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
575
    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
576
        # If we started from a dotted revno, we want to consider it as a tip
577
        # and don't want to yield revisions that are not part of its
578
        # ancestry. Given the order guaranteed by the merge sort, we will see
579
        # uninteresting descendants of the first parent of our tip before the
580
        # tip itself.
581
        first = rev_iter.next()
582
        (rev_id, merge_depth, revno, end_of_merge) = first
583
        yield first
584
        if not merge_depth:
585
            # We start at a mainline revision so by definition, all others
586
            # revisions in rev_iter are ancestors
587
            for node in rev_iter:
588
                yield node
589
5097.2.2 by Vincent Ladeuil
Fix performance.
590
        clean = False
5097.2.1 by Vincent Ladeuil
Fix bug #474807 but performance suffers.
591
        whitelist = set()
5097.2.3 by Vincent Ladeuil
Better performance than before the fix.
592
        pmap = self.repository.get_parent_map([rev_id])
593
        parents = pmap.get(rev_id, [])
594
        if parents:
595
            whitelist.update(parents)
5097.1.5 by Vincent Ladeuil
First attempt at fixing the bug, fortunately the bug report exhibits an
596
        else:
5097.1.8 by Vincent Ladeuil
Remove the comment about the missing test (it's not worth it at the
597
            # If there is no parents, there is nothing of interest left
598
599
            # FIXME: It's hard to test this scenario here as this code is never
600
            # called in that case. -- vila 20100322
601
            return
602
5097.1.5 by Vincent Ladeuil
First attempt at fixing the bug, fortunately the bug report exhibits an
603
        for (rev_id, merge_depth, revno, end_of_merge) in rev_iter:
5097.2.2 by Vincent Ladeuil
Fix performance.
604
            if not clean:
605
                if rev_id in whitelist:
5097.2.3 by Vincent Ladeuil
Better performance than before the fix.
606
                    pmap = self.repository.get_parent_map([rev_id])
607
                    parents = pmap.get(rev_id, [])
5097.2.2 by Vincent Ladeuil
Fix performance.
608
                    whitelist.remove(rev_id)
5097.2.3 by Vincent Ladeuil
Better performance than before the fix.
609
                    whitelist.update(parents)
5097.2.2 by Vincent Ladeuil
Fix performance.
610
                    if merge_depth == 0:
611
                        # We've reached the mainline, there is nothing left to
612
                        # filter
613
                        clean = True
614
                else:
615
                    # A revision that is not part of the ancestry of our
616
                    # starting revision.
617
                    continue
5097.1.5 by Vincent Ladeuil
First attempt at fixing the bug, fortunately the bug report exhibits an
618
            yield (rev_id, merge_depth, revno, end_of_merge)
619
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
620
    def leave_lock_in_place(self):
621
        """Tell this branch object not to release the physical lock when this
622
        object is unlocked.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
623
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
624
        If lock_write doesn't return a token, then this method is not supported.
625
        """
626
        self.control_files.leave_in_place()
627
628
    def dont_leave_lock_in_place(self):
629
        """Tell this branch object to release the physical lock when this
630
        object is unlocked, even if it didn't originally acquire it.
631
632
        If lock_write doesn't return a token, then this method is not supported.
633
        """
634
        self.control_files.dont_leave_in_place()
635
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
636
    def bind(self, other):
637
        """Bind the local branch the other branch.
638
639
        :param other: The branch to bind to
640
        :type other: Branch
641
        """
5158.6.3 by Martin Pool
Update some Branch calls to use ControlComponent style.
642
        raise errors.UpgradeRequired(self.user_url)
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
643
6123.9.11 by Jelmer Vernooij
Make get_append_revisions_only public.
644
    def get_append_revisions_only(self):
645
        """Whether it is only possible to append revisions to the history.
646
        """
6123.9.14 by Jelmer Vernooij
Fix RemoteBranch.get_append_revisions_only().
647
        if not self._format.supports_set_append_revisions_only():
648
            return False
649
        return self.get_config(
650
            ).get_user_option_as_bool('append_revisions_only')
6123.9.11 by Jelmer Vernooij
Make get_append_revisions_only public.
651
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.
652
    def set_append_revisions_only(self, enabled):
653
        if not self._format.supports_set_append_revisions_only():
5158.6.3 by Martin Pool
Update some Branch calls to use ControlComponent style.
654
            raise errors.UpgradeRequired(self.user_url)
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.
655
        if enabled:
656
            value = 'True'
657
        else:
658
            value = 'False'
659
        self.get_config().set_user_option('append_revisions_only', value,
660
            warn_masked=True)
661
4273.1.1 by Aaron Bentley
Implement branch format for tree references.
662
    def set_reference_info(self, file_id, tree_path, branch_location):
663
        """Set the branch location to use for a tree reference."""
664
        raise errors.UnsupportedOperation(self.set_reference_info, self)
665
666
    def get_reference_info(self, file_id):
667
        """Get the tree_path and branch_location for a tree reference."""
668
        raise errors.UnsupportedOperation(self.get_reference_info, self)
669
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.
670
    @needs_write_lock
5852.1.1 by Jelmer Vernooij
Add limit argument to Branch.fetch.
671
    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.
672
        """Copy revisions from from_branch into this branch.
673
674
        :param from_branch: Where to copy from.
675
        :param last_revision: What revision to stop at (None for at the end
676
                              of the branch.
5852.1.1 by Jelmer Vernooij
Add limit argument to Branch.fetch.
677
        :param limit: Optional rough limit of revisions to fetch
4065.1.1 by Robert Collins
Change the return value of fetch() to None.
678
        :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.
679
        """
5852.1.4 by Jelmer Vernooij
Pass along limit=.
680
        return InterBranch.get(from_branch, self).fetch(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.
681
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
682
    def get_bound_location(self):
1558.7.6 by Aaron Bentley
Fixed typo (Olaf Conradi)
683
        """Return the URL of the branch we are bound to.
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
684
685
        Older format branches cannot bind, please be sure to use a metadir
686
        branch.
687
        """
688
        return None
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
689
2230.3.31 by Aaron Bentley
Implement re-binding previously-bound branches
690
    def get_old_bound_location(self):
691
        """Return the URL of the branch we used to be bound to
692
        """
5158.6.3 by Martin Pool
Update some Branch calls to use ControlComponent style.
693
        raise errors.UpgradeRequired(self.user_url)
2230.3.31 by Aaron Bentley
Implement re-binding previously-bound branches
694
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
695
    def get_commit_builder(self, parents, config=None, timestamp=None,
696
                           timezone=None, committer=None, revprops=None,
5777.6.1 by Jelmer Vernooij
Add --lossy option to 'bzr commit'.
697
                           revision_id=None, lossy=False):
1740.3.7 by Jelmer Vernooij
Move committer, log, revprops, timestamp and timezone to CommitBuilder.
698
        """Obtain a CommitBuilder for this branch.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
699
1740.3.7 by Jelmer Vernooij
Move committer, log, revprops, timestamp and timezone to CommitBuilder.
700
        :param parents: Revision ids of the parents of the new revision.
701
        :param config: Optional configuration to use.
702
        :param timestamp: Optional timestamp recorded for commit.
703
        :param timezone: Optional timezone for timestamp.
704
        :param committer: Optional committer to set for commit.
705
        :param revprops: Optional dictionary of revision properties.
706
        :param revision_id: Optional revision id.
5777.6.1 by Jelmer Vernooij
Add --lossy option to 'bzr commit'.
707
        :param lossy: Whether to discard data that can not be natively
708
            represented, when pushing to a foreign VCS 
1740.3.7 by Jelmer Vernooij
Move committer, log, revprops, timestamp and timezone to CommitBuilder.
709
        """
710
711
        if config is None:
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
712
            config = self.get_config()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
713
2246.1.3 by Robert Collins
New branch hooks: post_push, post_pull, post_commit, post_uncommit. These
714
        return self.repository.get_commit_builder(self, parents, config,
5777.6.1 by Jelmer Vernooij
Add --lossy option to 'bzr commit'.
715
            timestamp, timezone, committer, revprops, revision_id,
716
            lossy)
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
717
2810.2.1 by Martin Pool
merge vincent and cleanup
718
    def get_master_branch(self, possible_transports=None):
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
719
        """Return the branch we are bound to.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
720
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
721
        :return: Either a Branch, or None
722
        """
723
        return None
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
724
1770.3.2 by Jelmer Vernooij
Move BzrBranch.get_revision_delta() to Branch.get_revision_delta() as it is generic.
725
    def get_revision_delta(self, revno):
726
        """Return the delta for one revision.
727
728
        The delta is relative to its mainline predecessor, or the
729
        empty tree for revision 1.
730
        """
731
        rh = self.revision_history()
732
        if not (1 <= revno <= len(rh)):
3236.1.2 by Michael Hudson
clean up branch.py imports
733
            raise errors.InvalidRevisionNumber(revno)
1770.3.2 by Jelmer Vernooij
Move BzrBranch.get_revision_delta() to Branch.get_revision_delta() as it is generic.
734
        return self.repository.get_revision_delta(rh[revno-1])
735
3537.3.1 by Martin Pool
Rename branch.get_stacked_on to get_stacked_on_url
736
    def get_stacked_on_url(self):
3221.11.2 by Robert Collins
Create basic stackable branch facility.
737
        """Get the URL this branch is stacked against.
738
739
        :raises NotStacked: If the branch is not stacked.
740
        :raises UnstackableBranchFormat: If the branch does not support
741
            stacking.
742
        """
3537.3.1 by Martin Pool
Rename branch.get_stacked_on to get_stacked_on_url
743
        raise NotImplementedError(self.get_stacked_on_url)
3221.11.2 by Robert Collins
Create basic stackable branch facility.
744
1185.50.9 by John Arbash Meinel
[bug 3632] Matthieu Moy- bzr cat should default to last revision
745
    def print_file(self, file, revision_id):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
746
        """Print `file` to stdout."""
1910.3.2 by Andrew Bennetts
Improve some NotImplementedErrors.
747
        raise NotImplementedError(self.print_file)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
748
5718.8.2 by Jelmer Vernooij
Split out full history branch code.
749
    @deprecated_method(deprecated_in((2, 4, 0)))
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
750
    def set_revision_history(self, rev_history):
5718.8.2 by Jelmer Vernooij
Split out full history branch code.
751
        """See Branch.set_revision_history."""
5718.8.18 by Jelmer Vernooij
Translate local set_rh calls to remote set_rh calls.
752
        self._set_revision_history(rev_history)
753
754
    @needs_write_lock
755
    def _set_revision_history(self, rev_history):
5718.8.2 by Jelmer Vernooij
Split out full history branch code.
756
        if len(rev_history) == 0:
757
            revid = _mod_revision.NULL_REVISION
758
        else:
759
            revid = rev_history[-1]
5718.8.15 by Jelmer Vernooij
Check left hand history in Branch.set_revision_history.
760
        if rev_history != self._lefthand_history(revid):
761
            raise errors.NotLefthandHistory(rev_history)
5718.8.2 by Jelmer Vernooij
Split out full history branch code.
762
        self.set_last_revision_info(len(rev_history), revid)
763
        self._cache_revision_history(rev_history)
5718.8.18 by Jelmer Vernooij
Translate local set_rh calls to remote set_rh calls.
764
        for hook in Branch.hooks['set_rh']:
765
            hook(self, rev_history)
5718.8.2 by Jelmer Vernooij
Split out full history branch code.
766
767
    @needs_write_lock
768
    def set_last_revision_info(self, revno, revision_id):
5718.8.3 by Jelmer Vernooij
More branch restructuring.
769
        """Set the last revision of this branch.
770
771
        The caller is responsible for checking that the revno is correct
772
        for this revision id.
773
774
        It may be possible to set the branch last revision to an id not
775
        present in the repository.  However, branches can also be
776
        configured to check constraints on history, in which case this may not
777
        be permitted.
778
        """
5883.1.1 by Jelmer Vernooij
Fix NotImplementedError contents.
779
        raise NotImplementedError(self.set_last_revision_info)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
780
4288.1.4 by Robert Collins
Remove the explicit set_parent method on RemoteBranch in favour of inheriting from Branch.
781
    @needs_write_lock
5718.8.6 by Jelmer Vernooij
Move generate_revision_history.
782
    def generate_revision_history(self, revision_id, last_rev=None,
783
                                  other_branch=None):
5718.8.18 by Jelmer Vernooij
Translate local set_rh calls to remote set_rh calls.
784
        """See Branch.generate_revision_history"""
5718.8.24 by Jelmer Vernooij
Implement generate_revision_history using graph.
785
        graph = self.repository.get_graph()
6015.18.1 by Jelmer Vernooij
Fix entry in known_revnos for generate_revision_history.
786
        (last_revno, last_revid) = self.last_revision_info()
5718.8.24 by Jelmer Vernooij
Implement generate_revision_history using graph.
787
        known_revision_ids = [
6015.18.1 by Jelmer Vernooij
Fix entry in known_revnos for generate_revision_history.
788
            (last_revid, last_revno),
5718.8.24 by Jelmer Vernooij
Implement generate_revision_history using graph.
789
            (_mod_revision.NULL_REVISION, 0),
790
            ]
791
        if last_rev is not None:
792
            if not graph.is_ancestor(last_rev, revision_id):
793
                # our previous tip is not merged into stop_revision
794
                raise errors.DivergedBranches(self, other_branch)
795
        revno = graph.find_distance_to_null(revision_id, known_revision_ids)
5718.8.6 by Jelmer Vernooij
Move generate_revision_history.
796
        self.set_last_revision_info(revno, revision_id)
797
798
    @needs_write_lock
4288.1.4 by Robert Collins
Remove the explicit set_parent method on RemoteBranch in favour of inheriting from Branch.
799
    def set_parent(self, url):
800
        """See Branch.set_parent."""
801
        # TODO: Maybe delete old location files?
802
        # URLs should never be unicode, even on the local fs,
803
        # FIXUP this and get_parent in a future branch format bump:
804
        # read and rewrite the file. RBC 20060125
805
        if url is not None:
806
            if isinstance(url, unicode):
807
                try:
808
                    url = url.encode('ascii')
809
                except UnicodeEncodeError:
810
                    raise errors.InvalidURL(url,
811
                        "Urls must be 7-bit ascii, "
812
                        "use bzrlib.urlutils.escape")
813
            url = urlutils.relative_url(self.base, url)
814
        self._set_parent_location(url)
815
4288.1.10 by Robert Collins
Fix up lock correctness to deal with adding fallback repositories to locked branch objects.
816
    @needs_write_lock
3537.3.3 by Martin Pool
Rename Branch.set_stacked_on to set_stacked_on_url
817
    def set_stacked_on_url(self, url):
3221.18.1 by Ian Clatworthy
tweaks by ianc during review
818
        """Set the URL this branch is stacked against.
3221.11.2 by Robert Collins
Create basic stackable branch facility.
819
820
        :raises UnstackableBranchFormat: If the branch does not support
821
            stacking.
822
        :raises UnstackableRepositoryFormat: If the repository does not support
823
            stacking.
824
        """
4226.1.3 by Robert Collins
Lift Branch.set_stacked_on_url up from BzrBranch7.
825
        if not self._format.supports_stacking():
5158.6.3 by Martin Pool
Update some Branch calls to use ControlComponent style.
826
            raise errors.UnstackableBranchFormat(self._format, self.user_url)
4509.3.30 by Martin Pool
doc
827
        # XXX: Changing from one fallback repository to another does not check
828
        # that all the data you need is present in the new fallback.
829
        # Possibly it should.
4226.1.3 by Robert Collins
Lift Branch.set_stacked_on_url up from BzrBranch7.
830
        self._check_stackable_repo()
831
        if not url:
832
            try:
4509.3.9 by Martin Pool
Split out Branch._unstack
833
                old_url = self.get_stacked_on_url()
834
            except (errors.NotStacked, errors.UnstackableBranchFormat,
835
                errors.UnstackableRepositoryFormat):
836
                return
837
            self._unstack()
4226.1.3 by Robert Collins
Lift Branch.set_stacked_on_url up from BzrBranch7.
838
        else:
4379.2.2 by John Arbash Meinel
Change the Repository.add_fallback_repository() contract slightly.
839
            self._activate_fallback_location(url)
4226.1.3 by Robert Collins
Lift Branch.set_stacked_on_url up from BzrBranch7.
840
        # write this out after the repository is stacked to avoid setting a
841
        # stacked config that doesn't work.
842
        self._set_config_location('stacked_on_location', url)
843
4509.3.9 by Martin Pool
Split out Branch._unstack
844
    def _unstack(self):
845
        """Change a branch to be unstacked, copying data as needed.
5697.2.1 by Jelmer Vernooij
Move weave branch to bzrlib.branch_weave.
846
4509.3.9 by Martin Pool
Split out Branch._unstack
847
        Don't call this directly, use set_stacked_on_url(None).
848
        """
849
        pb = ui.ui_factory.nested_progress_bar()
850
        try:
4509.3.33 by Martin Pool
Display progress task for the overall unstacking operation
851
            pb.update("Unstacking")
4509.3.16 by Martin Pool
Unstack by fetching from the stacked repository combination, not just the fallback.
852
            # The basic approach here is to fetch the tip of the branch,
853
            # including all available ghosts, from the existing stacked
854
            # repository into a new repository object without the fallbacks. 
855
            #
856
            # XXX: See <https://launchpad.net/bugs/397286> - this may not be
857
            # correct for CHKMap repostiories
858
            old_repository = self.repository
859
            if len(old_repository._fallback_repositories) != 1:
4509.3.9 by Martin Pool
Split out Branch._unstack
860
                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.
861
                    "of %r (fallbacks: %r)" % (old_repository,
862
                        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.
863
            # Open the new repository object.
864
            # Repositories don't offer an interface to remove fallback
865
            # repositories today; take the conceptually simpler option and just
866
            # reopen it.  We reopen it starting from the URL so that we
867
            # get a separate connection for RemoteRepositories and can
868
            # stream from one of them to the other.  This does mean doing
869
            # separate SSH connection setup, but unstacking is not a
870
            # common operation so it's tolerable.
871
            new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
872
            new_repository = new_bzrdir.find_repository()
873
            if new_repository._fallback_repositories:
874
                raise AssertionError("didn't expect %r to have "
875
                    "fallback_repositories"
876
                    % (self.repository,))
5325.1.4 by Andrew Bennetts
Improve comments.
877
            # Replace self.repository with the new repository.
878
            # 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.
879
            # lock count) of self.repository to the new repository.
880
            lock_token = old_repository.lock_write().repository_token
881
            self.repository = new_repository
882
            if isinstance(self, remote.RemoteBranch):
5325.1.4 by Andrew Bennetts
Improve comments.
883
                # Remote branches can have a second reference to the old
884
                # 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.
885
                if self._real_branch is not None:
886
                    self._real_branch.repository = new_repository
887
            self.repository.lock_write(token=lock_token)
888
            if lock_token is not None:
889
                old_repository.leave_lock_in_place()
4509.3.16 by Martin Pool
Unstack by fetching from the stacked repository combination, not just the fallback.
890
            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.
891
            if lock_token is not None:
892
                # XXX: self.repository.leave_lock_in_place() before this
893
                # function will not be preserved.  Fortunately that doesn't
5325.1.4 by Andrew Bennetts
Improve comments.
894
                # affect the current default format (2a), and would be a
895
                # 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.
896
                #  - Andrew Bennetts, 2010/06/30
897
                self.repository.dont_leave_lock_in_place()
898
            old_lock_count = 0
899
            while True:
900
                try:
901
                    old_repository.unlock()
902
                except errors.LockNotHeld:
903
                    break
904
                old_lock_count += 1
905
            if old_lock_count == 0:
906
                raise AssertionError(
907
                    'old_repository should have been locked at least once.')
908
            for i in range(old_lock_count-1):
909
                self.repository.lock_write()
910
            # Fetch from the old repository into the new.
4509.3.16 by Martin Pool
Unstack by fetching from the stacked repository combination, not just the fallback.
911
            old_repository.lock_read()
912
            try:
913
                # XXX: If you unstack a branch while it has a working tree
914
                # with a pending merge, the pending-merged revisions will no
915
                # longer be present.  You can (probably) revert and remerge.
5651.5.1 by Andrew Bennetts
Make 'bzr reconfigure --unstacked' fetch tagged revisions too. (#401646)
916
                try:
917
                    tags_to_fetch = set(self.tags.get_reverse_tag_dict())
918
                except errors.TagsNotSupported:
919
                    tags_to_fetch = set()
920
                fetch_spec = _mod_graph.NotInOtherForRevs(self.repository,
921
                    old_repository, required_ids=[self.last_revision()],
922
                    if_present_ids=tags_to_fetch, find_ghosts=True).execute()
923
                self.repository.fetch(old_repository, fetch_spec=fetch_spec)
4509.3.16 by Martin Pool
Unstack by fetching from the stacked repository combination, not just the fallback.
924
            finally:
925
                old_repository.unlock()
4509.3.9 by Martin Pool
Split out Branch._unstack
926
        finally:
927
            pb.finished()
3221.11.2 by Robert Collins
Create basic stackable branch facility.
928
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.
929
    def _set_tags_bytes(self, bytes):
930
        """Mirror method for _get_tags_bytes.
931
932
        :seealso: Branch._get_tags_bytes.
933
        """
5915.1.1 by Andrew Bennetts
Removed bzrlib.branch._run_with_write_locked_target. Use bzrlib.cleanup instead.
934
        op = cleanup.OperationWithCleanups(self._set_tags_bytes_locked)
935
        op.add_cleanup(self.lock_write().unlock)
936
        return op.run_simple(bytes)
5535.2.3 by Andrew Bennetts
Reset cached tags when mutating tags.
937
938
    def _set_tags_bytes_locked(self, bytes):
939
        self._tags_bytes = bytes
940
        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.
941
2375.1.3 by Andrew Bennetts
Don't use Branch.get_transaction to cache revision history.
942
    def _cache_revision_history(self, rev_history):
943
        """Set the cached revision history to rev_history.
944
945
        The revision_history method will use this cache to avoid regenerating
946
        the revision history.
947
948
        This API is semi-public; it only for use by subclasses, all other code
949
        should consider it to be private.
950
        """
951
        self._revision_history_cache = rev_history
952
2418.5.6 by John Arbash Meinel
Cache the revision_id => revno map as appropriate.
953
    def _cache_revision_id_to_revno(self, revision_id_to_revno):
954
        """Set the cached revision_id => revno map to revision_id_to_revno.
955
956
        This API is semi-public; it only for use by subclasses, all other code
957
        should consider it to be private.
958
        """
959
        self._revision_id_to_revno_cache = revision_id_to_revno
960
2375.1.6 by Andrew Bennetts
Rename _clear_cached_data to _clear_cached_state.
961
    def _clear_cached_state(self):
2375.1.5 by Andrew Bennetts
Deal with review comments from Robert:
962
        """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.
963
964
        This means the next call to revision_history will need to call
965
        _gen_revision_history.
966
967
        This API is semi-public; it only for use by subclasses, all other code
968
        should consider it to be private.
969
        """
970
        self._revision_history_cache = None
2418.5.6 by John Arbash Meinel
Cache the revision_id => revno map as appropriate.
971
        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.
972
        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.
973
        self._master_branch_cache = None
3949.3.4 by Ian Clatworthy
jam feedback: start & stop limits; simple caching
974
        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().
975
        self._partial_revision_history_cache = []
976
        self._partial_revision_id_to_revno_cache = {}
5535.2.1 by Andrew Bennetts
Cache a branch's tags during a read-lock.
977
        self._tags_bytes = None
2375.1.3 by Andrew Bennetts
Don't use Branch.get_transaction to cache revision history.
978
979
    def _gen_revision_history(self):
980
        """Return sequence of revision hashes on to this branch.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
981
2375.1.3 by Andrew Bennetts
Don't use Branch.get_transaction to cache revision history.
982
        Unlike revision_history, this method always regenerates or rereads the
983
        revision history, i.e. it does not cache the result, so repeated calls
984
        may be expensive.
985
2375.1.5 by Andrew Bennetts
Deal with review comments from Robert:
986
        Concrete subclasses should override this instead of revision_history so
987
        that subclasses do not need to deal with caching logic.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
988
2375.1.3 by Andrew Bennetts
Don't use Branch.get_transaction to cache revision history.
989
        This API is semi-public; it only for use by subclasses, all other code
990
        should consider it to be private.
991
        """
992
        raise NotImplementedError(self._gen_revision_history)
993
994
    @needs_read_lock
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
995
    def revision_history(self):
2592.3.113 by Robert Collins
Various -Devil checks in branch.py.
996
        """Return sequence of revision ids on this branch.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
997
2375.1.3 by Andrew Bennetts
Don't use Branch.get_transaction to cache revision history.
998
        This method will cache the revision history for as long as it is safe to
999
        do so.
1000
        """
2592.3.113 by Robert Collins
Various -Devil checks in branch.py.
1001
        if 'evil' in debug.debug_flags:
1002
            mutter_callsite(3, "revision_history scales with history.")
2375.1.3 by Andrew Bennetts
Don't use Branch.get_transaction to cache revision history.
1003
        if self._revision_history_cache is not None:
2375.1.5 by Andrew Bennetts
Deal with review comments from Robert:
1004
            history = self._revision_history_cache
1005
        else:
1006
            history = self._gen_revision_history()
1007
            self._cache_revision_history(history)
2375.1.3 by Andrew Bennetts
Don't use Branch.get_transaction to cache revision history.
1008
        return list(history)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1009
1010
    def revno(self):
1011
        """Return current revision number for this branch.
1012
1013
        That is equivalent to the number of revisions committed to
1014
        this branch.
1015
        """
3066.1.1 by John Arbash Meinel
Make the default Branch.revno() implementation just be a thunk to last_revision_info.
1016
        return self.last_revision_info()[0]
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1017
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
1018
    def unbind(self):
1019
        """Older format branches cannot bind or unbind."""
5158.6.3 by Martin Pool
Update some Branch calls to use ControlComponent style.
1020
        raise errors.UpgradeRequired(self.user_url)
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
1021
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1022
    def last_revision(self):
3211.2.1 by Robert Collins
* Creating a new branch no longer tries to read the entire revision-history
1023
        """Return last revision id, or NULL_REVISION."""
1024
        return self.last_revision_info()[1]
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1025
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.
1026
    @needs_read_lock
2249.4.1 by Wouter van Heyst
New Branch.last_revision_info method, this is being done to allow
1027
    def last_revision_info(self):
1028
        """Return information about the last revision.
1029
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.
1030
        :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
1031
        """
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.
1032
        if self._last_revision_info_cache is None:
5718.8.2 by Jelmer Vernooij
Split out full history branch code.
1033
            self._last_revision_info_cache = self._read_last_revision_info()
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.
1034
        return self._last_revision_info_cache
1035
5718.8.2 by Jelmer Vernooij
Split out full history branch code.
1036
    def _read_last_revision_info(self):
5718.8.3 by Jelmer Vernooij
More branch restructuring.
1037
        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
1038
5809.2.1 by Jelmer Vernooij
Deprecate Branch.update_revisions.
1039
    @deprecated_method(deprecated_in((2, 4, 0)))
4048.2.2 by Jelmer Vernooij
New Branch.import_last_Revision_info() function used to pull revisions into the master branch during commit.
1040
    def import_last_revision_info(self, source_repo, revno, revid):
1041
        """Set the last revision info, importing from another repo if necessary.
1042
1043
        :param source_repo: Source repository to optionally fetch from
1044
        :param revno: Revision number of the new tip
1045
        :param revid: Revision id of the new tip
1046
        """
1047
        if not self.repository.has_same_location(source_repo):
1048
            self.repository.fetch(source_repo, revision_id=revid)
1049
        self.set_last_revision_info(revno, revid)
1050
5777.7.1 by Jelmer Vernooij
Add lossy argument to Branch.import_last_revision_info_and_tags.
1051
    def import_last_revision_info_and_tags(self, source, revno, revid,
1052
                                           lossy=False):
5535.3.31 by Andrew Bennetts
Cope with tags that reference missing revisions.
1053
        """Set the last revision info, importing from another repo if necessary.
1054
1055
        This is used by the bound branch code to upload a revision to
1056
        the master branch first before updating the tip of the local branch.
1057
        Revisions referenced by source's tags are also transferred.
1058
5535.3.35 by Andrew Bennetts
Fix deprecation warning from some tests, correct some docstrings.
1059
        :param source: Source branch to optionally fetch from
5535.3.31 by Andrew Bennetts
Cope with tags that reference missing revisions.
1060
        :param revno: Revision number of the new tip
1061
        :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.
1062
        :param lossy: Whether to discard metadata that can not be
1063
            natively represented
1064
        :return: Tuple with the new revision number and revision id
1065
            (should only be different from the arguments when lossy=True)
5535.3.31 by Andrew Bennetts
Cope with tags that reference missing revisions.
1066
        """
1067
        if not self.repository.has_same_location(source.repository):
5741.1.8 by Jelmer Vernooij
Remove fetch_tags argument.
1068
            self.fetch(source, revid)
5535.3.31 by Andrew Bennetts
Cope with tags that reference missing revisions.
1069
        self.set_last_revision_info(revno, revid)
5777.7.1 by Jelmer Vernooij
Add lossy argument to Branch.import_last_revision_info_and_tags.
1070
        return (revno, revid)
5535.3.31 by Andrew Bennetts
Cope with tags that reference missing revisions.
1071
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1072
    def revision_id_to_revno(self, revision_id):
1073
        """Given a revision id, return its revno"""
2598.5.1 by Aaron Bentley
Start eliminating the use of None to indicate null revision
1074
        if _mod_revision.is_null(revision_id):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1075
            return 0
1076
        history = self.revision_history()
1077
        try:
1078
            return history.index(revision_id) + 1
1079
        except ValueError:
2418.5.5 by John Arbash Meinel
Add some tests and an api for revision_id_to_dotted_revno
1080
            raise errors.NoSuchRevision(self, revision_id)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1081
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().
1082
    @needs_read_lock
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1083
    def get_rev_id(self, revno, history=None):
1084
        """Find the revision id of the specified revno."""
1085
        if revno == 0:
2598.5.10 by Aaron Bentley
Return NULL_REVISION instead of None for the null revision
1086
            return _mod_revision.NULL_REVISION
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().
1087
        last_revno, last_revid = self.last_revision_info()
1088
        if revno == last_revno:
1089
            return last_revid
1090
        if revno <= 0 or revno > last_revno:
2418.5.5 by John Arbash Meinel
Add some tests and an api for revision_id_to_dotted_revno
1091
            raise errors.NoSuchRevision(self, revno)
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().
1092
        distance_from_last = last_revno - revno
1093
        if len(self._partial_revision_history_cache) <= distance_from_last:
4419.2.17 by Andrew Bennetts
Fix test failures in test_lookup_revision_id_by_dotted.
1094
            self._extend_partial_history(distance_from_last)
1095
        return self._partial_revision_history_cache[distance_from_last]
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1096
2817.4.3 by Vincent Ladeuil
Add tests for commit, reuse master branch transport.
1097
    def pull(self, source, overwrite=False, stop_revision=None,
4000.5.21 by Jelmer Vernooij
Merge bzr.dev.
1098
             possible_transports=None, *args, **kwargs):
2245.2.1 by Robert Collins
Split branch pushing out of branch pulling.
1099
        """Mirror source into this branch.
1100
1101
        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.
1102
1103
        :returns: PullResult instance
2245.2.1 by Robert Collins
Split branch pushing out of branch pulling.
1104
        """
4000.5.9 by Jelmer Vernooij
Add InterBranch.pull().
1105
        return InterBranch.get(source, self).pull(overwrite=overwrite,
1106
            stop_revision=stop_revision,
1107
            possible_transports=possible_transports, *args, **kwargs)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1108
5853.2.2 by Jelmer Vernooij
Make lossy_push an argument to InterBranch.push.
1109
    def push(self, target, overwrite=False, stop_revision=None, lossy=False,
1110
            *args, **kwargs):
2245.2.1 by Robert Collins
Split branch pushing out of branch pulling.
1111
        """Mirror this branch into target.
1112
1113
        This branch is considered to be 'local', having low latency.
1114
        """
4211.1.3 by Jelmer Vernooij
Fix trailing whitespace, add prototype for InterBranch.push().
1115
        return InterBranch.get(self, target).push(overwrite, stop_revision,
5853.2.2 by Jelmer Vernooij
Make lossy_push an argument to InterBranch.push.
1116
            lossy, *args, **kwargs)
4347.2.1 by Jelmer Vernooij
Move dpush onto an InterBranch object.
1117
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1118
    def basis_tree(self):
1852.5.1 by Robert Collins
Deprecate EmptyTree in favour of using Repository.revision_tree.
1119
        """Return `Tree` object for last revision."""
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
1120
        return self.repository.revision_tree(self.last_revision())
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1121
1122
    def get_parent(self):
1123
        """Return the parent location of the branch.
1124
4031.1.1 by Alexander Belchenko
Parent location is not used as default for push.
1125
        This is the default location for pull/missing.  The usual
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1126
        pattern is that the user can override it by specifying a
1127
        location.
1128
        """
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
1129
        parent = self._get_parent_location()
1130
        if parent is None:
1131
            return parent
1132
        # This is an old-format absolute path to a local branch
1133
        # turn it into a url
1134
        if parent.startswith('/'):
1135
            parent = urlutils.local_path_to_url(parent.decode('utf8'))
1136
        try:
1137
            return urlutils.join(self.base[:-1], parent)
1138
        except errors.InvalidURLJoin, e:
5158.6.3 by Martin Pool
Update some Branch calls to use ControlComponent style.
1139
            raise errors.InaccessibleParent(parent, self.user_url)
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
1140
1141
    def _get_parent_location(self):
1142
        raise NotImplementedError(self._get_parent_location)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1143
1551.12.44 by Aaron Bentley
Add (set|get)_public_branch
1144
    def _set_config_location(self, name, url, config=None,
1145
                             make_relative=False):
1146
        if config is None:
1147
            config = self.get_config()
1148
        if url is None:
1149
            url = ''
1150
        elif make_relative:
1151
            url = urlutils.relative_url(self.base, url)
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
1152
        config.set_user_option(name, url, warn_masked=True)
1551.12.44 by Aaron Bentley
Add (set|get)_public_branch
1153
1154
    def _get_config_location(self, name, config=None):
1155
        if config is None:
1156
            config = self.get_config()
1157
        location = config.get_user_option(name)
1158
        if location == '':
1159
            location = None
1160
        return location
1161
4382.3.1 by Jelmer Vernooij
Add Branch.get_child_submit_format(), so particular Branch implementations
1162
    def get_child_submit_format(self):
1163
        """Return the preferred format of submissions to this branch."""
1164
        return self.get_config().get_user_option("child_submit_format")
1165
1804.1.1 by Aaron Bentley
Add support for submit location to bundles
1166
    def get_submit_branch(self):
1167
        """Return the submit location of the branch.
1168
1169
        This is the default location for bundle.  The usual
1170
        pattern is that the user can override it by specifying a
1171
        location.
1172
        """
1173
        return self.get_config().get_user_option('submit_branch')
1174
1175
    def set_submit_branch(self, location):
1176
        """Return the submit location of the branch.
1177
1178
        This is the default location for bundle.  The usual
1179
        pattern is that the user can override it by specifying a
1180
        location.
1181
        """
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
1182
        self.get_config().set_user_option('submit_branch', location,
1183
            warn_masked=True)
1804.1.1 by Aaron Bentley
Add support for submit location to bundles
1184
1551.12.44 by Aaron Bentley
Add (set|get)_public_branch
1185
    def get_public_branch(self):
1186
        """Return the public location of the branch.
1187
4031.3.1 by Frank Aspell
Fixing various typos
1188
        This is used by merge directives.
1551.12.44 by Aaron Bentley
Add (set|get)_public_branch
1189
        """
1190
        return self._get_config_location('public_branch')
1191
1192
    def set_public_branch(self, location):
1193
        """Return the submit location of the branch.
1194
1195
        This is the default location for bundle.  The usual
1196
        pattern is that the user can override it by specifying a
1197
        location.
1198
        """
1199
        self._set_config_location('public_branch', location)
1200
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1201
    def get_push_location(self):
1202
        """Return the None or the location to push this branch to."""
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1203
        push_loc = self.get_config().get_user_option('push_location')
1204
        return push_loc
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1205
1206
    def set_push_location(self, location):
1207
        """Set a new push location for this branch."""
1910.3.2 by Andrew Bennetts
Improve some NotImplementedErrors.
1208
        raise NotImplementedError(self.set_push_location)
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1209
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.
1210
    def _run_post_change_branch_tip_hooks(self, old_revno, old_revid):
1211
        """Run the post_change_branch_tip hooks."""
1212
        hooks = Branch.hooks['post_change_branch_tip']
1213
        if not hooks:
1214
            return
1215
        new_revno, new_revid = self.last_revision_info()
1216
        params = ChangeBranchTipParams(
1217
            self, old_revno, new_revno, old_revid, new_revid)
1218
        for hook in hooks:
1219
            hook(params)
1220
1221
    def _run_pre_change_branch_tip_hooks(self, new_revno, new_revid):
1222
        """Run the pre_change_branch_tip hooks."""
1223
        hooks = Branch.hooks['pre_change_branch_tip']
1224
        if not hooks:
1225
            return
1226
        old_revno, old_revid = self.last_revision_info()
1227
        params = ChangeBranchTipParams(
1228
            self, old_revno, new_revno, old_revid, new_revid)
1229
        for hook in hooks:
4943.1.1 by Robert Collins
Do not fiddle with exceptions in the pre_change_branch_tip hook running code.
1230
            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.
1231
1587.1.10 by Robert Collins
update updates working tree and branch together.
1232
    @needs_write_lock
1233
    def update(self):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1234
        """Synchronise this branch with the master branch if any.
1587.1.10 by Robert Collins
update updates working tree and branch together.
1235
1236
        :return: None or the last_revision pivoted out during the update.
1237
        """
1238
        return None
1239
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1240
    def check_revno(self, revno):
1241
        """\
1242
        Check whether a revno corresponds to any revision.
1243
        Zero (the NULL revision) is considered valid.
1244
        """
1245
        if revno != 0:
1246
            self.check_real_revno(revno)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1247
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
1248
    def check_real_revno(self, revno):
1249
        """\
1250
        Check whether a revno corresponds to a real revision.
1251
        Zero (the NULL revision) is considered invalid
1252
        """
1253
        if revno < 1 or revno > self.revno():
3236.1.2 by Michael Hudson
clean up branch.py imports
1254
            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.
1255
1256
    @needs_read_lock
4050.1.1 by Robert Collins
Fix race condition with branch hooks during cloning when the new branch is stacked.
1257
    def clone(self, to_bzrdir, revision_id=None, repository_policy=None):
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.
1258
        """Clone this branch into to_bzrdir preserving all semantic values.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1259
4044.1.1 by Robert Collins
Create Branch.create_clone_on_transport helper method to combine bzr and branch creation for push.
1260
        Most API users will want 'create_clone_on_transport', which creates a
1261
        new bzrdir and branch on the fly.
1262
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.
1263
        revision_id: if not None, the revision history in the new branch will
1264
                     be truncated to end with revision_id.
1265
        """
3650.5.1 by Aaron Bentley
Fix push to use clone all the time.
1266
        result = to_bzrdir.create_branch()
4288.1.8 by Robert Collins
Lock new branches while we configure them in clone and sprout for less lock churn.
1267
        result.lock_write()
1268
        try:
1269
            if repository_policy is not None:
1270
                repository_policy.configure_branch(result)
1271
            self.copy_content_into(result, revision_id=revision_id)
1272
        finally:
1273
            result.unlock()
1274
        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.
1275
1276
    @needs_read_lock
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.
1277
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None,
1278
            repository=None):
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.
1279
        """Create a new line of development from the branch, into to_bzrdir.
3650.2.1 by Aaron Bentley
Fix sprout to honour cloning format
1280
1281
        to_bzrdir controls the branch format.
1282
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.
1283
        revision_id: if not None, the revision history in the new branch will
1284
                     be truncated to end with revision_id.
1285
        """
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.
1286
        if (repository_policy is not None and
1287
            repository_policy.requires_stacking()):
1288
            to_bzrdir._format.require_stacking(_skip_repo=True)
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.
1289
        result = to_bzrdir.create_branch(repository=repository)
4288.1.10 by Robert Collins
Fix up lock correctness to deal with adding fallback repositories to locked branch objects.
1290
        result.lock_write()
4288.1.8 by Robert Collins
Lock new branches while we configure them in clone and sprout for less lock churn.
1291
        try:
1292
            if repository_policy is not None:
1293
                repository_policy.configure_branch(result)
1294
            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.
1295
            master_url = self.get_bound_location()
1296
            if master_url is None:
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.
1297
                result.set_parent(self.bzrdir.root_transport.base)
1298
            else:
6015.7.1 by John Arbash Meinel
No need to open the master branch just to get its URL.
1299
                result.set_parent(master_url)
4288.1.8 by Robert Collins
Lock new branches while we configure them in clone and sprout for less lock churn.
1300
        finally:
1301
            result.unlock()
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.
1302
        return result
1303
2230.3.18 by Aaron Bentley
Handle history sync as a special operation
1304
    def _synchronize_history(self, destination, revision_id):
2230.3.35 by Aaron Bentley
Add documentation for synchonize_history
1305
        """Synchronize last revision and revision history between branches.
1306
1307
        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.
1308
        BzrBranch6, but works for BzrBranch5, as long as the destination's
1309
        repository contains all the lefthand ancestors of the intended
1310
        last_revision.  If not, set_last_revision_info will fail.
2230.3.35 by Aaron Bentley
Add documentation for synchonize_history
1311
1312
        :param destination: The branch to copy the history into
1313
        :param revision_id: The revision-id to truncate history at.  May
1314
          be None to copy complete history.
1315
        """
3834.3.1 by Andrew Bennetts
Get rid of revision_history() call during copy_content_into.
1316
        source_revno, source_revision_id = self.last_revision_info()
1317
        if revision_id is None:
1318
            revno, revision_id = source_revno, source_revision_id
3650.3.3 by Aaron Bentley
fix sprout
1319
        else:
4266.3.8 by Jelmer Vernooij
Consistently use find_distance_to_null.
1320
            graph = self.repository.get_graph()
4266.3.1 by Jelmer Vernooij
Support cloning of branches with ghosts in the left hand side history.
1321
            try:
4266.3.8 by Jelmer Vernooij
Consistently use find_distance_to_null.
1322
                revno = graph.find_distance_to_null(revision_id, 
1323
                    [(source_revision_id, source_revno)])
1324
            except errors.GhostRevisionsHaveNoRevno:
1325
                # Default to 1, if we can't find anything else
1326
                revno = 1
3834.3.1 by Andrew Bennetts
Get rid of revision_history() call during copy_content_into.
1327
        destination.set_last_revision_info(revno, revision_id)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1328
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.
1329
    def copy_content_into(self, destination, revision_id=None):
1330
        """Copy the content of self into destination.
1331
1332
        revision_id: if not None, the revision history in the new branch will
1333
                     be truncated to end with revision_id.
1334
        """
5284.4.2 by Robert Collins
* ``Branch.copy_content_into`` is now a convenience method dispatching to
1335
        return InterBranch.get(self, destination).copy_content_into(
1336
            revision_id=revision_id)
4273.1.6 by Aaron Bentley
Ensure references are rebased.
1337
1338
    def update_references(self, target):
4273.1.8 by Aaron Bentley
Handle references in push, pull, merge.
1339
        if not getattr(self._format, 'supports_reference_locations', False):
1340
            return
4273.1.11 by Aaron Bentley
Clean up naming and docstrings
1341
        reference_dict = self._get_all_reference_info()
4273.1.9 by Aaron Bentley
Cleanup
1342
        if len(reference_dict) == 0:
1343
            return
4273.1.6 by Aaron Bentley
Ensure references are rebased.
1344
        old_base = self.base
1345
        new_base = target.base
4273.1.11 by Aaron Bentley
Clean up naming and docstrings
1346
        target_reference_dict = target._get_all_reference_info()
4273.1.6 by Aaron Bentley
Ensure references are rebased.
1347
        for file_id, (tree_path, branch_location) in (
1348
            reference_dict.items()):
1349
            branch_location = urlutils.rebase_url(branch_location,
1350
                                                  old_base, new_base)
4273.1.7 by Aaron Bentley
Make update_references do a merge.
1351
            target_reference_dict.setdefault(
1352
                file_id, (tree_path, branch_location))
4273.1.11 by Aaron Bentley
Clean up naming and docstrings
1353
        target._set_all_reference_info(target_reference_dict)
1185.66.1 by Aaron Bentley
Merged from mainline
1354
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
1355
    @needs_read_lock
4332.3.7 by Robert Collins
Convert Branch.check to take a refs dict as well.
1356
    def check(self, refs):
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
1357
        """Check consistency of the branch.
1358
1359
        In particular this checks that revisions given in the revision-history
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1360
        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
1361
        present in the repository.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1362
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
1363
        Callers will typically also want to check the repository.
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
1364
4332.3.7 by Robert Collins
Convert Branch.check to take a refs dict as well.
1365
        :param refs: Calculated refs for this branch as specified by
1366
            branch._get_check_refs()
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
1367
        :return: A BranchCheckResult.
1368
        """
4332.3.3 by Robert Collins
Alter Branch.check to log errors rather than raising.
1369
        result = BranchCheckResult(self)
3389.2.1 by John Arbash Meinel
Add code to 'bzr check' to detect when the mainline history is inconsistent.
1370
        last_revno, last_revision_id = self.last_revision_info()
4332.3.7 by Robert Collins
Convert Branch.check to take a refs dict as well.
1371
        actual_revno = refs[('lefthand-distance', last_revision_id)]
1372
        if actual_revno != last_revno:
4332.3.3 by Robert Collins
Alter Branch.check to log errors rather than raising.
1373
            result.errors.append(errors.BzrCheckError(
1374
                'revno does not match len(mainline) %s != %s' % (
4332.3.7 by Robert Collins
Convert Branch.check to take a refs dict as well.
1375
                last_revno, actual_revno)))
1376
        # TODO: We should probably also check that self.revision_history
1377
        # matches the repository for older branch formats.
1378
        # If looking for the code that cross-checks repository parents against
1379
        # the iter_reverse_revision_history output, that is now a repository
1380
        # specific check.
4332.3.3 by Robert Collins
Alter Branch.check to log errors rather than raising.
1381
        return result
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
1382
6127.1.9 by Jelmer Vernooij
Add lightweight option to _get_checkout_format().
1383
    def _get_checkout_format(self, lightweight=False):
1910.2.39 by Aaron Bentley
Fix checkout bug
1384
        """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.
1385
        Weaves are used if this branch's repository uses weaves.
1910.2.39 by Aaron Bentley
Fix checkout bug
1386
        """
5582.10.3 by Jelmer Vernooij
Remove custom code for presplitout.
1387
        format = self.repository.bzrdir.checkout_metadir()
1388
        format.set_branch_format(self._format)
1910.2.39 by Aaron Bentley
Fix checkout bug
1389
        return format
1390
4044.1.1 by Robert Collins
Create Branch.create_clone_on_transport helper method to combine bzr and branch creation for push.
1391
    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.
1392
        stacked_on=None, create_prefix=False, use_existing_dir=False,
1393
        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.
1394
        """Create a clone of this branch and its bzrdir.
1395
1396
        :param to_transport: The transport to clone onto.
1397
        :param revision_id: The revision id to use as tip in the new branch.
1398
            If None the tip is obtained from this branch.
1399
        :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.
1400
        :param create_prefix: Create any missing directories leading up to
1401
            to_transport.
1402
        :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.
1403
        """
4044.1.2 by Robert Collins
Reinstate the TODO comment about bzrdir.clone_on_transport.
1404
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1405
        # clone call. Or something. 20090224 RBC/spiv.
5147.4.1 by Jelmer Vernooij
Pass branch names in more places.
1406
        # XXX: Should this perhaps clone colocated branches as well, 
1407
        # 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.
1408
        if revision_id is None:
1409
            revision_id = self.last_revision()
4634.105.1 by Andrew Bennetts
Fix traceback when doing 'bzr push --use-existing-dir' into a dir with an invalid .bzr directory.
1410
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1411
            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.
1412
            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.
1413
            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.
1414
        return dir_to.open_branch()
1415
2245.2.1 by Robert Collins
Split branch pushing out of branch pulling.
1416
    def create_checkout(self, to_location, revision_id=None,
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
1417
                        lightweight=False, accelerator_tree=None,
1418
                        hardlink=False):
1551.8.3 by Aaron Bentley
Make create_checkout_convenience a Branch method
1419
        """Create a checkout of a branch.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1420
1551.8.3 by Aaron Bentley
Make create_checkout_convenience a Branch method
1421
        :param to_location: The url to produce the checkout at
1422
        :param revision_id: The revision to check out
1551.8.5 by Aaron Bentley
Change name to create_checkout
1423
        :param lightweight: If True, produce a lightweight checkout, otherwise,
5891.1.3 by Andrew Bennetts
Move docstring formatting fixes.
1424
            produce a bound branch (heavyweight checkout)
3123.5.17 by Aaron Bentley
Update docs
1425
        :param accelerator_tree: A tree which can be used for retrieving file
1426
            contents more quickly than the revision tree, i.e. a workingtree.
1427
            The revision tree will be used for cases where accelerator_tree's
1428
            content is different.
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
1429
        :param hardlink: If true, hard-link files from accelerator_tree,
1430
            where possible.
1551.8.3 by Aaron Bentley
Make create_checkout_convenience a Branch method
1431
        :return: The tree of the created checkout
1432
        """
1910.2.39 by Aaron Bentley
Fix checkout bug
1433
        t = transport.get_transport(to_location)
2475.3.3 by John Arbash Meinel
Change calls to try/mkdir('.')/except FileExists to ensure_base()
1434
        t.ensure_base()
6127.1.9 by Jelmer Vernooij
Add lightweight option to _get_checkout_format().
1435
        format = self._get_checkout_format(lightweight=lightweight)
1551.8.3 by Aaron Bentley
Make create_checkout_convenience a Branch method
1436
        if lightweight:
2100.3.26 by Aaron Bentley
checkout type is maintained for subtrees
1437
            checkout = format.initialize_on_transport(t)
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
1438
            from_branch = BranchReferenceFormat().initialize(checkout, 
1439
                target_branch=self)
1551.8.3 by Aaron Bentley
Make create_checkout_convenience a Branch method
1440
        else:
1441
            checkout_branch = bzrdir.BzrDir.create_branch_convenience(
1910.2.39 by Aaron Bentley
Fix checkout bug
1442
                to_location, force_new_tree=False, format=format)
1551.8.3 by Aaron Bentley
Make create_checkout_convenience a Branch method
1443
            checkout = checkout_branch.bzrdir
1444
            checkout_branch.bind(self)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1445
            # 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
1446
            # branch tip correctly, and seed it with history.
1447
            checkout_branch.pull(self, stop_revision=revision_id)
2955.5.3 by Vincent Ladeuil
Fix second unwanted connection by providing the right branch to create_checkout.
1448
            from_branch=None
1449
        tree = checkout.create_workingtree(revision_id,
3123.5.2 by Aaron Bentley
Allow checkout --files_from
1450
                                           from_branch=from_branch,
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
1451
                                           accelerator_tree=accelerator_tree,
1452
                                           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.
1453
        basis_tree = tree.basis_tree()
1454
        basis_tree.lock_read()
1455
        try:
1456
            for path, file_id in basis_tree.iter_references():
1457
                reference_parent = self.reference_parent(file_id, path)
1458
                reference_parent.create_checkout(tree.abspath(path),
1459
                    basis_tree.get_reference_revision(file_id, path),
1460
                    lightweight)
1461
        finally:
1462
            basis_tree.unlock()
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
1463
        return tree
1551.8.3 by Aaron Bentley
Make create_checkout_convenience a Branch method
1464
3389.2.3 by John Arbash Meinel
Add Branch.reconcile() functionality.
1465
    @needs_write_lock
1466
    def reconcile(self, thorough=True):
1467
        """Make sure the data stored in this branch is consistent."""
1468
        from bzrlib.reconcile import BranchReconciler
1469
        reconciler = BranchReconciler(self, thorough=thorough)
1470
        reconciler.reconcile()
1471
        return reconciler
1472
4273.1.4 by Aaron Bentley
Relative reference locations are branch-relative.
1473
    def reference_parent(self, file_id, path, possible_transports=None):
2100.3.29 by Aaron Bentley
Get merge working initially
1474
        """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.
1475
2100.3.29 by Aaron Bentley
Get merge working initially
1476
        :param file_id: The file_id of the tree reference
1477
        :param path: The path of the file_id in the tree
1478
        :return: A branch associated with the file_id
1479
        """
1480
        # FIXME should provide multiple branches, based on config
5158.6.11 by Martin Pool
Revert some fragile dependencies of branch on .base
1481
        return Branch.open(self.bzrdir.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
1482
                           possible_transports=possible_transports)
2100.3.23 by Aaron Bentley
Nested checkouts kinda work
1483
2220.2.30 by Martin Pool
split out tag-merging code and add some tests
1484
    def supports_tags(self):
1485
        return self._format.supports_tags()
1486
5086.4.7 by Jelmer Vernooij
Put automatic_tag_name on Branch.
1487
    def automatic_tag_name(self, revision_id):
1488
        """Try to automatically find the tag name for a revision.
1489
1490
        :param revision_id: Revision id of the revision.
5086.4.8 by Jelmer Vernooij
Review comments from Ian.
1491
        :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.
1492
        """
1493
        for hook in Branch.hooks['automatic_tag_name']:
1494
            ret = hook(self, revision_id)
1495
            if ret is not None:
1496
                return ret
1497
        return None
1498
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.
1499
    def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
1500
                                         other_branch):
3441.5.18 by Andrew Bennetts
Fix some test failures.
1501
        """Ensure that revision_b is a descendant of revision_a.
1502
1503
        This is a helper function for update_revisions.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1504
3441.5.18 by Andrew Bennetts
Fix some test failures.
1505
        :raises: DivergedBranches if revision_b has diverged from revision_a.
1506
        :returns: True if revision_b is a descendant of revision_a.
1507
        """
1508
        relation = self._revision_relations(revision_a, revision_b, graph)
1509
        if relation == 'b_descends_from_a':
1510
            return True
1511
        elif relation == 'diverged':
1512
            raise errors.DivergedBranches(self, other_branch)
1513
        elif relation == 'a_descends_from_b':
1514
            return False
1515
        else:
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1516
            raise AssertionError("invalid relation: %r" % (relation,))
3441.5.18 by Andrew Bennetts
Fix some test failures.
1517
1518
    def _revision_relations(self, revision_a, revision_b, graph):
1519
        """Determine the relationship between two revisions.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1520
3441.5.18 by Andrew Bennetts
Fix some test failures.
1521
        :returns: One of: 'a_descends_from_b', 'b_descends_from_a', 'diverged'
1522
        """
1523
        heads = graph.heads([revision_a, revision_b])
1524
        if heads == set([revision_b]):
1525
            return 'b_descends_from_a'
1526
        elif heads == set([revision_a, revision_b]):
1527
            # These branches have diverged
1528
            return 'diverged'
1529
        elif heads == set([revision_a]):
1530
            return 'a_descends_from_b'
1531
        else:
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1532
            raise AssertionError("invalid heads: %r" % (heads,))
3441.5.18 by Andrew Bennetts
Fix some test failures.
1533
5741.1.11 by Jelmer Vernooij
Don't make heads_to_fetch() take a stop_revision.
1534
    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.
1535
        """Return the heads that must and that should be fetched to copy this
1536
        branch into another repo.
1537
1538
        :returns: a 2-tuple of (must_fetch, if_present_fetch).  must_fetch is a
1539
            set of heads that must be fetched.  if_present_fetch is a set of
1540
            heads that must be fetched if present, but no error is necessary if
1541
            they are not present.
1542
        """
5741.1.11 by Jelmer Vernooij
Don't make heads_to_fetch() take a stop_revision.
1543
        # For bzr native formats must_fetch is just the tip, and if_present_fetch
1544
        # are the tags.
1545
        must_fetch = set([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.
1546
        if_present_fetch = set()
1547
        c = self.get_config()
1548
        include_tags = c.get_user_option_as_bool('branch.fetch_tags',
1549
                                                 default=False)
1550
        if include_tags:
1551
            try:
1552
                if_present_fetch = set(self.tags.get_reverse_tag_dict())
1553
            except errors.TagsNotSupported:
1554
                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.
1555
        must_fetch.discard(_mod_revision.NULL_REVISION)
1556
        if_present_fetch.discard(_mod_revision.NULL_REVISION)
1557
        return must_fetch, if_present_fetch
1558
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1559
5669.3.10 by Jelmer Vernooij
Use ControlComponentFormat.
1560
class BranchFormat(controldir.ControlComponentFormat):
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1561
    """An encapsulation of the initialization and open routines for a format.
1562
1563
    Formats provide three things:
1564
     * An initialization routine,
1565
     * a format string,
1566
     * an open routine.
1567
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1568
    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
1569
    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
1570
    can be classes themselves with class methods - it simply depends on
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1571
    whether state is needed for a given format or not.
1572
1573
    Once a format is deprecated, just deprecate the initialize and open
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1574
    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.
1575
    object will be created every time regardless.
1576
    """
1577
2363.5.5 by Aaron Bentley
add info.describe_format
1578
    def __eq__(self, other):
1579
        return self.__class__ is other.__class__
1580
1581
    def __ne__(self, other):
1582
        return not (self == other)
1583
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1584
    @classmethod
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
1585
    def find_format(klass, a_bzrdir, name=None):
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1586
        """Return the format for the branch object in a_bzrdir."""
1587
        try:
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
1588
            transport = a_bzrdir.get_branch_transport(None, name=name)
4708.2.1 by Martin
Ensure all files opened by bazaar proper are explicitly closed
1589
            format_string = transport.get_bytes("format")
5662.2.6 by Jelmer Vernooij
add more tests.
1590
            return format_registry.get(format_string)
3236.1.2 by Michael Hudson
clean up branch.py imports
1591
        except errors.NoSuchFile:
4734.4.7 by Andrew Bennetts
Defer checking for a repository in NotBranchError case until we format the error as a string. (test_smart currently fails)
1592
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1593
        except KeyError:
3246.3.2 by Daniel Watkins
Modified uses of errors.UnknownFormatError.
1594
            raise errors.UnknownFormatError(format=format_string, kind='branch')
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1595
1596
    @classmethod
5662.2.2 by Jelmer Vernooij
Move most format registration functions to BranchFormatRegistry.
1597
    @deprecated_method(deprecated_in((2, 4, 0)))
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1598
    def get_default_format(klass):
1599
        """Return the current default format."""
5662.2.2 by Jelmer Vernooij
Move most format registration functions to BranchFormatRegistry.
1600
        return format_registry.get_default()
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1601
5305.1.1 by Robert Collins
``Branch`` formats can now be loaded lazily by registering a
1602
    @classmethod
5662.2.2 by Jelmer Vernooij
Move most format registration functions to BranchFormatRegistry.
1603
    @deprecated_method(deprecated_in((2, 4, 0)))
5305.1.1 by Robert Collins
``Branch`` formats can now be loaded lazily by registering a
1604
    def get_formats(klass):
1605
        """Get all the known formats.
1606
1607
        Warning: This triggers a load of all lazy registered formats: do not
1608
        use except when that is desireed.
1609
        """
5662.2.2 by Jelmer Vernooij
Move most format registration functions to BranchFormatRegistry.
1610
        return format_registry._get_all()
5305.1.1 by Robert Collins
``Branch`` formats can now be loaded lazily by registering a
1611
5147.4.6 by Jelmer Vernooij
consistency in names
1612
    def get_reference(self, a_bzrdir, name=None):
2414.2.1 by Andrew Bennetts
Some miscellaneous new APIs, tests and other changes from the hpss branch.
1613
        """Get the target reference of the branch in a_bzrdir.
1614
1615
        format probing must have been completed before calling
1616
        this method - it is assumed that the format of the branch
1617
        in a_bzrdir is correct.
1618
1619
        :param a_bzrdir: The bzrdir to get the branch data from.
5147.4.6 by Jelmer Vernooij
consistency in names
1620
        :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.
1621
        :return: None if the branch is not a reference branch.
1622
        """
1623
        return None
1624
3078.2.1 by Ian Clatworthy
Refactor switch to support heavyweight checkouts
1625
    @classmethod
5147.4.6 by Jelmer Vernooij
consistency in names
1626
    def set_reference(self, a_bzrdir, name, to_branch):
3078.2.1 by Ian Clatworthy
Refactor switch to support heavyweight checkouts
1627
        """Set the target reference of the branch in a_bzrdir.
1628
1629
        format probing must have been completed before calling
1630
        this method - it is assumed that the format of the branch
1631
        in a_bzrdir is correct.
1632
1633
        :param a_bzrdir: The bzrdir to set the branch reference for.
5147.4.6 by Jelmer Vernooij
consistency in names
1634
        :param name: Name of colocated branch to set, None for default
3078.2.1 by Ian Clatworthy
Refactor switch to support heavyweight checkouts
1635
        :param to_branch: branch that the checkout is to reference
1636
        """
1637
        raise NotImplementedError(self.set_reference)
1638
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1639
    def get_format_string(self):
1640
        """Return the ASCII format string that identifies this format."""
1641
        raise NotImplementedError(self.get_format_string)
1642
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1643
    def get_format_description(self):
1644
        """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).
1645
        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
1646
5107.3.2 by Marco Pantaleoni
Renamed 'post_branch' hook to 'post_branch_init', for more consistency,
1647
    def _run_post_branch_init_hooks(self, a_bzrdir, name, branch):
1648
        hooks = Branch.hooks['post_branch_init']
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
1649
        if not hooks:
1650
            return
5107.3.2 by Marco Pantaleoni
Renamed 'post_branch' hook to 'post_branch_init', for more consistency,
1651
        params = BranchInitHookParams(self, a_bzrdir, name, branch)
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
1652
        for hook in hooks:
1653
            hook(params)
1654
6123.9.12 by Jelmer Vernooij
Add append_revisions_only argument to BranchFormat.initialize.
1655
    def initialize(self, a_bzrdir, name=None, repository=None,
1656
                   append_revisions_only=None):
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
1657
        """Create a branch of this format in a_bzrdir.
1658
        
1659
        :param name: Name of the colocated branch to create.
1660
        """
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1661
        raise NotImplementedError(self.initialize)
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1662
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.
1663
    def is_supported(self):
1664
        """Is this format supported?
1665
1666
        Supported formats can be initialized and opened.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1667
        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.
1668
        some other features depending on the reason for not being supported.
1669
        """
1670
        return True
1671
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.
1672
    def make_tags(self, branch):
1673
        """Create a tags object for branch.
1674
1675
        This method is on BranchFormat, because BranchFormats are reflected
1676
        over the wire via network_name(), whereas full Branch instances require
1677
        multiple VFS method calls to operate at all.
1678
1679
        The default implementation returns a disabled-tags instance.
1680
1681
        Note that it is normal for branch to be a RemoteBranch when using tags
1682
        on a RemoteBranch.
1683
        """
6105.1.1 by Jelmer Vernooij
Fix "pydoc bzrlib.branch" by importing modules, not objects, using lazy_import.
1684
        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.
1685
4032.3.1 by Robert Collins
Add a BranchFormat.network_name() method as preparation for creating branches via RPC calls.
1686
    def network_name(self):
1687
        """A simple byte string uniquely identifying this format for RPC calls.
1688
1689
        MetaDir branch formats use their disk format string to identify the
1690
        repository over the wire. All in one formats such as bzr < 0.8, and
1691
        foreign formats like svn/git and hg should use some marker which is
1692
        unique and immutable.
1693
        """
1694
        raise NotImplementedError(self.network_name)
1695
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.
1696
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
1697
            found_repository=None):
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1698
        """Return the branch object for a_bzrdir
1699
4160.2.12 by Andrew Bennetts
Improve docstrings and remove a line of cruft.
1700
        :param a_bzrdir: A BzrDir that contains a branch.
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
1701
        :param name: Name of colocated branch to open
4160.2.12 by Andrew Bennetts
Improve docstrings and remove a line of cruft.
1702
        :param _found: a private parameter, do not use it. It is used to
1703
            indicate if format probing has already be done.
1704
        :param ignore_fallbacks: when set, no fallback branches will be opened
1705
            (if there are any).  Default is to open fallbacks.
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1706
        """
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
1707
        raise NotImplementedError(self.open)
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1708
1709
    @classmethod
5662.2.2 by Jelmer Vernooij
Move most format registration functions to BranchFormatRegistry.
1710
    @deprecated_method(deprecated_in((2, 4, 0)))
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1711
    def register_format(klass, format):
5305.1.1 by Robert Collins
``Branch`` formats can now be loaded lazily by registering a
1712
        """Register a metadir format.
5662.2.2 by Jelmer Vernooij
Move most format registration functions to BranchFormatRegistry.
1713
5305.1.1 by Robert Collins
``Branch`` formats can now be loaded lazily by registering a
1714
        See MetaDirBranchFormatFactory for the ability to register a format
1715
        without loading the code the format needs until it is actually used.
1716
        """
5662.2.1 by Jelmer Vernooij
Add BranchFormatRegistry.
1717
        format_registry.register(format)
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1718
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.
1719
    @classmethod
5662.2.2 by Jelmer Vernooij
Move most format registration functions to BranchFormatRegistry.
1720
    @deprecated_method(deprecated_in((2, 4, 0)))
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1721
    def set_default_format(klass, format):
5662.2.2 by Jelmer Vernooij
Move most format registration functions to BranchFormatRegistry.
1722
        format_registry.set_default(format)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1723
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.
1724
    def supports_set_append_revisions_only(self):
1725
        """True if this format supports set_append_revisions_only."""
1726
        return False
1727
3575.2.2 by Martin Pool
branch --stacked should force a stacked format
1728
    def supports_stacking(self):
1729
        """True if this format records a stacked-on branch."""
1730
        return False
1731
5674.1.1 by Jelmer Vernooij
Add supports_leave_lock flag to BranchFormat and RepositoryFormat.
1732
    def supports_leaving_lock(self):
1733
        """True if this format supports leaving locks in place."""
1734
        return False # by default
1735
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1736
    @classmethod
5662.2.6 by Jelmer Vernooij
add more tests.
1737
    @deprecated_method(deprecated_in((2, 4, 0)))
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.
1738
    def unregister_format(klass, format):
5662.2.3 by Jelmer Vernooij
Fix tests.
1739
        format_registry.remove(format)
5642.2.1 by Jelmer Vernooij
Allow the registration of non-metadir branch formats.
1740
1553.4.8 by Michael Ellerman
Define __str__ for BranchFormat, just return the format string with the
1741
    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.
1742
        return self.get_format_description().rstrip()
1553.4.8 by Michael Ellerman
Define __str__ for BranchFormat, just return the format string with the
1743
2220.2.10 by Martin Pool
(broken) start moving things to branches
1744
    def supports_tags(self):
1745
        """True if this format supports tags stored in the branch"""
1746
        return False  # by default
1747
6123.4.6 by Jelmer Vernooij
Move flags to BranchFormat.
1748
    def tags_are_versioned(self):
1749
        """Whether the tag container for this branch versions tags."""
1750
        return False
1751
1752
    def supports_tags_referencing_ghosts(self):
1753
        """True if tags can reference ghost revisions."""
1754
        return True
1755
1534.4.2 by Robert Collins
Introduce BranchFormats - factoring out intialisation of Branches.
1756
5305.1.1 by Robert Collins
``Branch`` formats can now be loaded lazily by registering a
1757
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
5305.1.2 by Robert Collins
More clarity about how to use the lazy registration feature.
1758
    """A factory for a BranchFormat object, permitting simple lazy registration.
1759
    
1760
    While none of the built in BranchFormats are lazy registered yet,
1761
    bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
1762
    use it, and the bzr-loom plugin uses it as well (see
1763
    bzrlib.plugins.loom.formats).
1764
    """
5305.1.1 by Robert Collins
``Branch`` formats can now be loaded lazily by registering a
1765
1766
    def __init__(self, format_string, module_name, member_name):
1767
        """Create a MetaDirBranchFormatFactory.
1768
1769
        :param format_string: The format string the format has.
1770
        :param module_name: Module to load the format class from.
1771
        :param member_name: Attribute name within the module for the format class.
1772
        """
1773
        registry._LazyObjectGetter.__init__(self, module_name, member_name)
1774
        self._format_string = format_string
1775
        
1776
    def get_format_string(self):
1777
        """See BranchFormat.get_format_string."""
1778
        return self._format_string
1779
1780
    def __call__(self):
1781
        """Used for network_format_registry support."""
1782
        return self.get_obj()()
1783
1784
2370.4.1 by Robert Collins
New SmartServer hooks facility. There are two initial hooks documented
1785
class BranchHooks(Hooks):
2245.1.3 by Robert Collins
Add install_hook to the BranchHooks class as the official means for installing a hook.
1786
    """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
1787
2245.1.3 by Robert Collins
Add install_hook to the BranchHooks class as the official means for installing a hook.
1788
    e.g. ['set_rh'] Is the list of items to be called when the
1789
    set_revision_history function is invoked.
1790
    """
1791
5622.3.10 by Jelmer Vernooij
Don't require arguments to hooks.
1792
    def __init__(self):
2245.1.3 by Robert Collins
Add install_hook to the BranchHooks class as the official means for installing a hook.
1793
        """Create the default hooks.
1794
1795
        These are all empty initially, because by default nothing should get
1796
        notified.
1797
        """
5622.3.10 by Jelmer Vernooij
Don't require arguments to hooks.
1798
        Hooks.__init__(self, "bzrlib.branch", "Branch.hooks")
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
1799
        self.add_hook('set_rh',
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
1800
            "Invoked whenever the revision history has been set via "
1801
            "set_revision_history. The api signature is (branch, "
1802
            "revision_history), and the branch will be write-locked. "
1803
            "The set_rh hook can be expensive for bzr to trigger, a better "
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
1804
            "hook to use is Branch.post_change_branch_tip.", (0, 15))
1805
        self.add_hook('open',
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
1806
            "Called with the Branch object that has been opened after a "
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
1807
            "branch is opened.", (1, 8))
1808
        self.add_hook('post_push',
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
1809
            "Called after a push operation completes. post_push is called "
4053.3.4 by Jelmer Vernooij
Update branch hooks documentation.
1810
            "with a bzrlib.branch.BranchPushResult object and only runs in the "
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
1811
            "bzr client.", (0, 15))
1812
        self.add_hook('post_pull',
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
1813
            "Called after a pull operation completes. post_pull is called "
1814
            "with a bzrlib.branch.PullResult object and only runs in the "
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
1815
            "bzr client.", (0, 15))
1816
        self.add_hook('pre_commit',
5430.4.2 by Vincent Ladeuil
Fix typo in Branch.pre_commit HookPoint docstring.
1817
            "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.
1818
            "completed. pre_commit is called with (local, master, old_revno, "
1819
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
1820
            "). old_revid is NULL_REVISION for the first commit to a branch, "
1821
            "tree_delta is a TreeDelta object describing changes from the "
1822
            "basis revision. hooks MUST NOT modify this delta. "
1823
            " future_tree is an in-memory tree obtained from "
1824
            "CommitBuilder.revision_tree() and hooks MUST NOT modify this "
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
1825
            "tree.", (0,91))
1826
        self.add_hook('post_commit',
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
1827
            "Called in the bzr client after a commit has completed. "
1828
            "post_commit is called with (local, master, old_revno, old_revid, "
1829
            "new_revno, new_revid). old_revid is NULL_REVISION for the first "
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
1830
            "commit to a branch.", (0, 15))
1831
        self.add_hook('post_uncommit',
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
1832
            "Called in the bzr client after an uncommit completes. "
1833
            "post_uncommit is called with (local, master, old_revno, "
1834
            "old_revid, new_revno, new_revid) where local is the local branch "
1835
            "or None, master is the target branch, and an empty branch "
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
1836
            "receives new_revno of 0, new_revid of None.", (0, 15))
1837
        self.add_hook('pre_change_branch_tip',
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
1838
            "Called in bzr client and server before a change to the tip of a "
1839
            "branch is made. pre_change_branch_tip is called with a "
1840
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
1841
            "commit, uncommit will all trigger this hook.", (1, 6))
1842
        self.add_hook('post_change_branch_tip',
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
1843
            "Called in bzr client and server after a change to the tip of a "
1844
            "branch is made. post_change_branch_tip is called with a "
1845
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
1846
            "commit, uncommit will all trigger this hook.", (1, 4))
1847
        self.add_hook('transform_fallback_location',
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
1848
            "Called when a stacked branch is activating its fallback "
1849
            "locations. transform_fallback_location is called with (branch, "
1850
            "url), and should return a new url. Returning the same url "
1851
            "allows it to be used as-is, returning a different one can be "
1852
            "used to cause the branch to stack on a closer copy of that "
1853
            "fallback_location. Note that the branch cannot have history "
1854
            "accessing methods called on it during this hook because the "
1855
            "fallback locations have not been activated. When there are "
1856
            "multiple hooks installed for transform_fallback_location, "
1857
            "all are called with the url returned from the previous hook."
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
1858
            "The order is however undefined.", (1, 9))
1859
        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)
1860
            "Called to determine an automatic tag name for a revision. "
5086.4.5 by Jelmer Vernooij
Make automatic_tag_name a hook on Branch.
1861
            "automatic_tag_name is called with (branch, revision_id) and "
1862
            "should return a tag name or None if no tag name could be "
5086.4.9 by Jelmer Vernooij
Update documentation.
1863
            "determined. The first non-None tag name returned will be used.",
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
1864
            (2, 2))
1865
        self.add_hook('post_branch_init',
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
1866
            "Called after new branch initialization completes. "
5107.3.6 by Marco Pantaleoni
Documented behaviour of 'post_branch_init' for lightweight checkouts.
1867
            "post_branch_init is called with a "
1868
            "bzrlib.branch.BranchInitHookParams. "
1869
            "Note that init, branch and checkout (both heavyweight and "
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
1870
            "lightweight) will all trigger this hook.", (2, 2))
1871
        self.add_hook('post_switch',
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
1872
            "Called after a checkout switches branch. "
1873
            "post_switch is called with a "
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
1874
            "bzrlib.branch.SwitchHookParams.", (2, 2))
5086.4.5 by Jelmer Vernooij
Make automatic_tag_name a hook on Branch.
1875
2245.1.3 by Robert Collins
Add install_hook to the BranchHooks class as the official means for installing a hook.
1876
1877
1878
# install the default hooks into the Branch class.
5622.3.10 by Jelmer Vernooij
Don't require arguments to hooks.
1879
Branch.hooks = BranchHooks()
2245.1.3 by Robert Collins
Add install_hook to the BranchHooks class as the official means for installing a hook.
1880
1881
3323.2.1 by Ian Clatworthy
first cut at post_change_branch_tip hook
1882
class ChangeBranchTipParams(object):
5891.1.2 by Andrew Bennetts
Fix a bunch of docstring formatting nits, making pydoctor a bit happier.
1883
    """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()
1884
3331.1.7 by James Henstridge
Make the branch a member of the ChangeBranchTipParams object.
1885
    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()
1886
3331.1.13 by James Henstridge
Use last_revision_info() to retrieve the new revision number and ID.
1887
    :ivar branch: the branch being changed
1888
    :ivar old_revno: revision number before the change
1889
    :ivar new_revno: revision number after the change
1890
    :ivar old_revid: revision id before the change
1891
    :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()
1892
3323.2.1 by Ian Clatworthy
first cut at post_change_branch_tip hook
1893
    The revid fields are strings. The revno fields are integers.
1894
    """
1895
3331.1.7 by James Henstridge
Make the branch a member of the ChangeBranchTipParams object.
1896
    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
1897
        """Create a group of ChangeBranchTip parameters.
1898
3331.1.7 by James Henstridge
Make the branch a member of the ChangeBranchTipParams object.
1899
        :param branch: The branch being changed.
3331.1.5 by James Henstridge
Put revno before revid in method arguments to match last_revision_info()
1900
        :param old_revno: Revision number before the change.
1901
        :param new_revno: Revision number after the change.
3323.2.1 by Ian Clatworthy
first cut at post_change_branch_tip hook
1902
        :param old_revid: Tip revision id before the change.
1903
        :param new_revid: Tip revision id after the change.
1904
        """
3331.1.7 by James Henstridge
Make the branch a member of the ChangeBranchTipParams object.
1905
        self.branch = branch
3331.1.5 by James Henstridge
Put revno before revid in method arguments to match last_revision_info()
1906
        self.old_revno = old_revno
1907
        self.new_revno = new_revno
3323.2.1 by Ian Clatworthy
first cut at post_change_branch_tip hook
1908
        self.old_revid = old_revid
1909
        self.new_revid = new_revid
1910
3517.2.3 by Andrew Bennetts
Better tests for {pre,post}_change_branch_tip hooks.
1911
    def __eq__(self, other):
1912
        return self.__dict__ == other.__dict__
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1913
3517.2.3 by Andrew Bennetts
Better tests for {pre,post}_change_branch_tip hooks.
1914
    def __repr__(self):
1915
        return "<%s of %s from (%s, %s) to (%s, %s)>" % (
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1916
            self.__class__.__name__, self.branch,
3517.2.3 by Andrew Bennetts
Better tests for {pre,post}_change_branch_tip hooks.
1917
            self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1918
5107.3.4 by Marco Pantaleoni
Applied suggestions from merge reviewer (John A Meinel):
1919
5107.3.2 by Marco Pantaleoni
Renamed 'post_branch' hook to 'post_branch_init', for more consistency,
1920
class BranchInitHookParams(object):
5891.1.2 by Andrew Bennetts
Fix a bunch of docstring formatting nits, making pydoctor a bit happier.
1921
    """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',
1922
1923
    There are 4 fields that hooks may wish to access:
1924
1925
    :ivar format: the branch format
5107.3.6 by Marco Pantaleoni
Documented behaviour of 'post_branch_init' for lightweight checkouts.
1926
    :ivar bzrdir: the BzrDir 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',
1927
    :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.
1928
    :ivar branch: the branch created
1929
1930
    Note that for lightweight checkouts, the bzrdir and format fields refer to
1931
    the checkout, hence they are different from the corresponding fields in
1932
    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',
1933
    """
1934
1935
    def __init__(self, format, a_bzrdir, name, branch):
5107.3.2 by Marco Pantaleoni
Renamed 'post_branch' hook to 'post_branch_init', for more consistency,
1936
        """Create a group of BranchInitHook parameters.
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
1937
1938
        :param format: the branch format
5107.3.6 by Marco Pantaleoni
Documented behaviour of 'post_branch_init' for lightweight checkouts.
1939
        :param a_bzrdir: the BzrDir where the branch will be/has been
1940
            initialized
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
1941
        :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.
1942
        :param branch: the branch created
1943
1944
        Note that for lightweight checkouts, the bzrdir and format fields refer
1945
        to the checkout, hence they are different from the corresponding fields
1946
        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',
1947
        """
1948
        self.format = format
1949
        self.bzrdir = a_bzrdir
5107.3.4 by Marco Pantaleoni
Applied suggestions from merge reviewer (John A Meinel):
1950
        self.name = name
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
1951
        self.branch = branch
1952
1953
    def __eq__(self, other):
1954
        return self.__dict__ == other.__dict__
1955
1956
    def __repr__(self):
5050.21.1 by Andrew Bennetts
Remove broken and apparently unused code path from BranchInitHookParams.__repr__.
1957
        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',
1958
5107.3.4 by Marco Pantaleoni
Applied suggestions from merge reviewer (John A Meinel):
1959
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
1960
class SwitchHookParams(object):
5891.1.2 by Andrew Bennetts
Fix a bunch of docstring formatting nits, making pydoctor a bit happier.
1961
    """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',
1962
1963
    There are 4 fields that hooks may wish to access:
1964
1965
    :ivar control_dir: BzrDir of the checkout to change
1966
    :ivar to_branch: branch that the checkout is to reference
1967
    :ivar force: skip the check for local commits in a heavy checkout
1968
    :ivar revision_id: revision ID to switch to (or None)
1969
    """
1970
1971
    def __init__(self, control_dir, to_branch, force, revision_id):
1972
        """Create a group of SwitchHook parameters.
1973
1974
        :param control_dir: BzrDir of the checkout to change
1975
        :param to_branch: branch that the checkout is to reference
1976
        :param force: skip the check for local commits in a heavy checkout
1977
        :param revision_id: revision ID to switch to (or None)
1978
        """
1979
        self.control_dir = control_dir
5107.3.4 by Marco Pantaleoni
Applied suggestions from merge reviewer (John A Meinel):
1980
        self.to_branch = to_branch
1981
        self.force = force
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
1982
        self.revision_id = revision_id
1983
1984
    def __eq__(self, other):
1985
        return self.__dict__ == other.__dict__
1986
1987
    def __repr__(self):
1988
        return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
1989
            self.control_dir, self.to_branch,
1990
            self.revision_id)
3323.2.1 by Ian Clatworthy
first cut at post_change_branch_tip hook
1991
5107.3.4 by Marco Pantaleoni
Applied suggestions from merge reviewer (John A Meinel):
1992
3221.11.2 by Robert Collins
Create basic stackable branch facility.
1993
class BranchFormatMetadir(BranchFormat):
1994
    """Common logic for meta-dir based branch formats."""
1995
1996
    def _branch_class(self):
1997
        """What class to instantiate on open calls."""
1998
        raise NotImplementedError(self._branch_class)
1999
6123.9.12 by Jelmer Vernooij
Add append_revisions_only argument to BranchFormat.initialize.
2000
    def _get_initial_config(self, append_revisions_only=None):
2001
        if append_revisions_only:
2002
            return "append_revisions_only = True\n"
2003
        else:
2004
            # Avoid writing anything if append_revisions_only is disabled,
2005
            # as that is the default.
2006
            return ""
2007
5757.1.2 by Jelmer Vernooij
Add separate file for knit pack repository formats.
2008
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
2009
                           repository=None):
2010
        """Initialize a branch in a bzrdir, with specified files
2011
2012
        :param a_bzrdir: The bzrdir to initialize the branch in
2013
        :param utf8_files: The files to create as a list of
2014
            (filename, content) tuples
2015
        :param name: Name of colocated branch to create, if any
2016
        :return: a branch in this format
2017
        """
2018
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
2019
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
2020
        control_files = lockable_files.LockableFiles(branch_transport,
2021
            'lock', lockdir.LockDir)
2022
        control_files.create_lock()
2023
        control_files.lock_write()
2024
        try:
2025
            utf8_files += [('format', self.get_format_string())]
2026
            for (filename, content) in utf8_files:
2027
                branch_transport.put_bytes(
2028
                    filename, content,
2029
                    mode=a_bzrdir._get_file_mode())
2030
        finally:
2031
            control_files.unlock()
2032
        branch = self.open(a_bzrdir, name, _found=True,
2033
                found_repository=repository)
2034
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2035
        return branch
2036
4032.3.1 by Robert Collins
Add a BranchFormat.network_name() method as preparation for creating branches via RPC calls.
2037
    def network_name(self):
2038
        """A simple byte string uniquely identifying this format for RPC calls.
2039
2040
        Metadir branch formats use their format string.
2041
        """
2042
        return self.get_format_string()
2043
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.
2044
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
2045
            found_repository=None):
4160.2.12 by Andrew Bennetts
Improve docstrings and remove a line of cruft.
2046
        """See BranchFormat.open()."""
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2047
        if not _found:
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
2048
            format = BranchFormat.find_format(a_bzrdir, name=name)
3221.13.3 by Ian Clatworthy
Merge bzr.dev r3466
2049
            if format.__class__ != self.__class__:
2050
                raise AssertionError("wrong format %r found for %r" %
2051
                    (format, self))
5158.6.3 by Martin Pool
Update some Branch calls to use ControlComponent style.
2052
        transport = a_bzrdir.get_branch_transport(None, name=name)
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2053
        try:
2054
            control_files = lockable_files.LockableFiles(transport, 'lock',
2055
                                                         lockdir.LockDir)
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.
2056
            if found_repository is None:
2057
                found_repository = a_bzrdir.find_repository()
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2058
            return self._branch_class()(_format=self,
2059
                              _control_files=control_files,
5085.1.1 by Jelmer Vernooij
Let branches know about their colocated name.
2060
                              name=name,
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2061
                              a_bzrdir=a_bzrdir,
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.
2062
                              _repository=found_repository,
4160.2.6 by Andrew Bennetts
Add ignore_fallbacks flag.
2063
                              ignore_fallbacks=ignore_fallbacks)
3221.13.3 by Ian Clatworthy
Merge bzr.dev r3466
2064
        except errors.NoSuchFile:
4734.4.7 by Andrew Bennetts
Defer checking for a repository in NotBranchError case until we format the error as a string. (test_smart currently fails)
2065
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2066
2067
    def __init__(self):
2068
        super(BranchFormatMetadir, self).__init__()
2069
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
3834.5.2 by John Arbash Meinel
Track down the various BranchFormats that weren't setting the branch format as part of the _matchingbzrdir format.
2070
        self._matchingbzrdir.set_branch_format(self)
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2071
2072
    def supports_tags(self):
2073
        return True
2074
5674.1.1 by Jelmer Vernooij
Add supports_leave_lock flag to BranchFormat and RepositoryFormat.
2075
    def supports_leaving_lock(self):
2076
        return True
2077
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2078
2079
class BzrBranchFormat5(BranchFormatMetadir):
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
2080
    """Bzr branch format 5.
2081
2082
    This format has:
2083
     - a revision-history file.
2084
     - a format string
1553.5.71 by Martin Pool
Change branch format 5 to use LockDirs, not transport locks
2085
     - a lock dir guarding the branch itself
2086
     - all of this stored in a branch/ subdirectory
1534.6.4 by Robert Collins
Creating or opening a branch will use the repository if the format supports that.
2087
     - works with shared repositories.
1553.5.71 by Martin Pool
Change branch format 5 to use LockDirs, not transport locks
2088
2089
    This format is new in bzr 0.8.
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
2090
    """
2091
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2092
    def _branch_class(self):
2093
        return BzrBranch5
2094
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
2095
    def get_format_string(self):
2096
        """See BranchFormat.get_format_string()."""
2097
        return "Bazaar-NG branch format 5\n"
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
2098
2099
    def get_format_description(self):
2100
        """See BranchFormat.get_format_description()."""
2101
        return "Branch format 5"
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2102
6123.9.12 by Jelmer Vernooij
Add append_revisions_only argument to BranchFormat.initialize.
2103
    def initialize(self, a_bzrdir, name=None, repository=None,
2104
                   append_revisions_only=None):
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
2105
        """Create a branch of this format in a_bzrdir."""
6123.9.12 by Jelmer Vernooij
Add append_revisions_only argument to BranchFormat.initialize.
2106
        if append_revisions_only:
2107
            raise errors.UpgradeRequired(a_bzrdir.user_url)
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
2108
        utf8_files = [('revision-history', ''),
2109
                      ('branch-name', ''),
2110
                      ]
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.
2111
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
2112
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2113
    def supports_tags(self):
2114
        return False
2115
2116
2117
class BzrBranchFormat6(BranchFormatMetadir):
2696.3.1 by Martin Pool
(broken) start switching format to dirstate-tags
2118
    """Branch format with last-revision and tags.
2230.3.12 by Aaron Bentley
Clean up trailing whitespace
2119
2230.3.38 by Aaron Bentley
Update docs per Martin's suggestion
2120
    Unlike previous formats, this has no explicit revision history. Instead,
2121
    this just stores the last-revision, and the left-hand history leading
2122
    up to there is the history.
2123
2124
    This format was introduced in bzr 0.15
2696.3.1 by Martin Pool
(broken) start switching format to dirstate-tags
2125
    and became the default in 0.91.
2230.3.1 by Aaron Bentley
Get branch6 creation working
2126
    """
2127
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2128
    def _branch_class(self):
2129
        return BzrBranch6
2130
2230.3.1 by Aaron Bentley
Get branch6 creation working
2131
    def get_format_string(self):
2132
        """See BranchFormat.get_format_string()."""
2255.2.230 by Robert Collins
Update tree format signatures to mention introducing bzr version.
2133
        return "Bazaar Branch Format 6 (bzr 0.15)\n"
2230.3.1 by Aaron Bentley
Get branch6 creation working
2134
2135
    def get_format_description(self):
2136
        """See BranchFormat.get_format_description()."""
2137
        return "Branch format 6"
2138
6123.9.12 by Jelmer Vernooij
Add append_revisions_only argument to BranchFormat.initialize.
2139
    def initialize(self, a_bzrdir, name=None, repository=None,
2140
                   append_revisions_only=None):
2230.3.1 by Aaron Bentley
Get branch6 creation working
2141
        """Create a branch of this format in a_bzrdir."""
2230.3.51 by Aaron Bentley
Store revno for Branch6, set_last_revision -> set_last_revision_info
2142
        utf8_files = [('last-revision', '0 null:\n'),
6123.9.12 by Jelmer Vernooij
Add append_revisions_only argument to BranchFormat.initialize.
2143
                      ('branch.conf',
2144
                          self._get_initial_config(append_revisions_only)),
2220.2.28 by Martin Pool
Integrate tags with Branch6:
2145
                      ('tags', ''),
2230.3.1 by Aaron Bentley
Get branch6 creation working
2146
                      ]
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.
2147
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2230.3.1 by Aaron Bentley
Get branch6 creation working
2148
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.
2149
    def make_tags(self, branch):
2150
        """See bzrlib.branch.BranchFormat.make_tags()."""
6105.1.1 by Jelmer Vernooij
Fix "pydoc bzrlib.branch" by importing modules, not objects, using lazy_import.
2151
        return _mod_tag.BasicTags(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.
2152
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.
2153
    def supports_set_append_revisions_only(self):
2154
        return True
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.
2155
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2156
4273.1.1 by Aaron Bentley
Implement branch format for tree references.
2157
class BzrBranchFormat8(BranchFormatMetadir):
2158
    """Metadir format supporting storing locations of subtree branches."""
2159
2160
    def _branch_class(self):
2161
        return BzrBranch8
2162
2163
    def get_format_string(self):
2164
        """See BranchFormat.get_format_string()."""
2165
        return "Bazaar Branch Format 8 (needs bzr 1.15)\n"
2166
2167
    def get_format_description(self):
2168
        """See BranchFormat.get_format_description()."""
2169
        return "Branch format 8"
2170
6123.9.12 by Jelmer Vernooij
Add append_revisions_only argument to BranchFormat.initialize.
2171
    def initialize(self, a_bzrdir, name=None, repository=None,
2172
                   append_revisions_only=None):
4273.1.1 by Aaron Bentley
Implement branch format for tree references.
2173
        """Create a branch of this format in a_bzrdir."""
2174
        utf8_files = [('last-revision', '0 null:\n'),
6123.9.12 by Jelmer Vernooij
Add append_revisions_only argument to BranchFormat.initialize.
2175
                      ('branch.conf',
2176
                          self._get_initial_config(append_revisions_only)),
4273.1.1 by Aaron Bentley
Implement branch format for tree references.
2177
                      ('tags', ''),
2178
                      ('references', '')
2179
                      ]
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.
2180
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
4273.1.1 by Aaron Bentley
Implement branch format for tree references.
2181
2182
    def make_tags(self, branch):
2183
        """See bzrlib.branch.BranchFormat.make_tags()."""
6105.1.1 by Jelmer Vernooij
Fix "pydoc bzrlib.branch" by importing modules, not objects, using lazy_import.
2184
        return _mod_tag.BasicTags(branch)
4273.1.1 by Aaron Bentley
Implement branch format for tree references.
2185
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.
2186
    def supports_set_append_revisions_only(self):
2187
        return True
2188
4273.1.1 by Aaron Bentley
Implement branch format for tree references.
2189
    def supports_stacking(self):
2190
        return True
2191
4273.1.5 by Aaron Bentley
Ensure references are propagated by sprout/clone.
2192
    supports_reference_locations = True
2193
4273.1.1 by Aaron Bentley
Implement branch format for tree references.
2194
5757.1.2 by Jelmer Vernooij
Add separate file for knit pack repository formats.
2195
class BzrBranchFormat7(BranchFormatMetadir):
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2196
    """Branch format with last-revision, tags, and a stacked location pointer.
2197
2198
    The stacked location pointer is passed down to the repository and requires
2199
    a repository format with supports_external_lookups = True.
2200
3221.13.6 by Ian Clatworthy
update BzrBranch7 format to say 1.6, not 1.3
2201
    This format was introduced in bzr 1.6.
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2202
    """
2203
6123.9.12 by Jelmer Vernooij
Add append_revisions_only argument to BranchFormat.initialize.
2204
    def initialize(self, a_bzrdir, name=None, repository=None,
2205
                   append_revisions_only=None):
4273.1.12 by Aaron Bentley
Don't create reference files for older formats.
2206
        """Create a branch of this format in a_bzrdir."""
2207
        utf8_files = [('last-revision', '0 null:\n'),
6123.9.12 by Jelmer Vernooij
Add append_revisions_only argument to BranchFormat.initialize.
2208
                      ('branch.conf',
2209
                          self._get_initial_config(append_revisions_only)),
4273.1.12 by Aaron Bentley
Don't create reference files for older formats.
2210
                      ('tags', ''),
2211
                      ]
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.
2212
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
4273.1.12 by Aaron Bentley
Don't create reference files for older formats.
2213
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2214
    def _branch_class(self):
2215
        return BzrBranch7
2216
2217
    def get_format_string(self):
2218
        """See BranchFormat.get_format_string()."""
3221.13.6 by Ian Clatworthy
update BzrBranch7 format to say 1.6, not 1.3
2219
        return "Bazaar Branch Format 7 (needs bzr 1.6)\n"
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2220
2221
    def get_format_description(self):
2222
        """See BranchFormat.get_format_description()."""
2223
        return "Branch format 7"
2224
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.
2225
    def supports_set_append_revisions_only(self):
2226
        return True
2227
5757.1.2 by Jelmer Vernooij
Add separate file for knit pack repository formats.
2228
    def supports_stacking(self):
2229
        return True
2230
5757.1.4 by Jelmer Vernooij
Add bzrlib.repofmt.knitpack_repo to the blacklist in test_import_tariff.
2231
    def make_tags(self, branch):
2232
        """See bzrlib.branch.BranchFormat.make_tags()."""
6105.1.1 by Jelmer Vernooij
Fix "pydoc bzrlib.branch" by importing modules, not objects, using lazy_import.
2233
        return _mod_tag.BasicTags(branch)
5757.1.4 by Jelmer Vernooij
Add bzrlib.repofmt.knitpack_repo to the blacklist in test_import_tariff.
2234
4273.1.5 by Aaron Bentley
Ensure references are propagated by sprout/clone.
2235
    supports_reference_locations = False
2236
2230.3.1 by Aaron Bentley
Get branch6 creation working
2237
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.
2238
class BranchReferenceFormat(BranchFormat):
2239
    """Bzr branch reference format.
2240
2241
    Branch references are used in implementing checkouts, they
2242
    act as an alias to the real branch which is at some other url.
2243
2244
    This format has:
2245
     - A location file
2246
     - a format string
2247
    """
2248
2249
    def get_format_string(self):
2250
        """See BranchFormat.get_format_string()."""
2251
        return "Bazaar-NG Branch Reference Format 1\n"
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
2252
2253
    def get_format_description(self):
2254
        """See BranchFormat.get_format_description()."""
2255
        return "Checkout reference format 1"
2955.5.2 by Vincent Ladeuil
Fix first unwanted connection.
2256
5147.4.6 by Jelmer Vernooij
consistency in names
2257
    def get_reference(self, a_bzrdir, name=None):
2414.2.1 by Andrew Bennetts
Some miscellaneous new APIs, tests and other changes from the hpss branch.
2258
        """See BranchFormat.get_reference()."""
5147.4.6 by Jelmer Vernooij
consistency in names
2259
        transport = a_bzrdir.get_branch_transport(None, name=name)
4708.2.1 by Martin
Ensure all files opened by bazaar proper are explicitly closed
2260
        return transport.get_bytes('location')
2414.2.1 by Andrew Bennetts
Some miscellaneous new APIs, tests and other changes from the hpss branch.
2261
5147.4.6 by Jelmer Vernooij
consistency in names
2262
    def set_reference(self, a_bzrdir, name, to_branch):
3078.2.1 by Ian Clatworthy
Refactor switch to support heavyweight checkouts
2263
        """See BranchFormat.set_reference()."""
5147.4.6 by Jelmer Vernooij
consistency in names
2264
        transport = a_bzrdir.get_branch_transport(None, name=name)
3078.2.1 by Ian Clatworthy
Refactor switch to support heavyweight checkouts
2265
        location = transport.put_bytes('location', to_branch.base)
2266
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.
2267
    def initialize(self, a_bzrdir, name=None, target_branch=None,
6123.9.12 by Jelmer Vernooij
Add append_revisions_only argument to BranchFormat.initialize.
2268
            repository=None, append_revisions_only=None):
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.
2269
        """Create a branch of this format in a_bzrdir."""
2270
        if target_branch is None:
2271
            # this format does not implement branch itself, thus the implicit
2272
            # creation contract must see it as uninitializable
2273
            raise errors.UninitializableFormat(self)
5158.6.3 by Martin Pool
Update some Branch calls to use ControlComponent style.
2274
        mutter('creating branch reference in %s', a_bzrdir.user_url)
6082.1.1 by Jelmer Vernooij
Don't attempt to create branch references in control directories that don't support it.
2275
        if a_bzrdir._format.fixed_components:
2276
            raise errors.IncompatibleFormat(self, a_bzrdir._format)
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
2277
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
1955.3.9 by John Arbash Meinel
Find more occurrances of put() and replace with put_file or put_bytes
2278
        branch_transport.put_bytes('location',
5158.6.3 by Martin Pool
Update some Branch calls to use ControlComponent style.
2279
            target_branch.bzrdir.user_url)
1955.3.9 by John Arbash Meinel
Find more occurrances of put() and replace with put_file or put_bytes
2280
        branch_transport.put_bytes('format', self.get_format_string())
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
2281
        branch = self.open(
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
2282
            a_bzrdir, name, _found=True,
2955.5.2 by Vincent Ladeuil
Fix first unwanted connection.
2283
            possible_transports=[target_branch.bzrdir.root_transport])
5107.3.4 by Marco Pantaleoni
Applied suggestions from merge reviewer (John A Meinel):
2284
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
2285
        return branch
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.
2286
2287
    def __init__(self):
2288
        super(BranchReferenceFormat, self).__init__()
2289
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
3834.5.2 by John Arbash Meinel
Track down the various BranchFormats that weren't setting the branch format as part of the _matchingbzrdir format.
2290
        self._matchingbzrdir.set_branch_format(self)
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.
2291
2292
    def _make_reference_clone_function(format, a_branch):
2293
        """Create a clone() routine for a branch dynamically."""
4050.1.3 by Robert Collins
Add missed new parameter for branch reference cloning.
2294
        def clone(to_bzrdir, revision_id=None,
2295
            repository_policy=None):
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.
2296
            """See Branch.clone()."""
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
2297
            return format.initialize(to_bzrdir, target_branch=a_branch)
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.
2298
            # cannot obey revision_id limits when cloning a reference ...
2299
            # FIXME RBC 20060210 either nuke revision_id for clone, or
2300
            # emit some sort of warning/error to the caller ?!
2301
        return clone
2302
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
2303
    def open(self, a_bzrdir, name=None, _found=False, location=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.
2304
             possible_transports=None, ignore_fallbacks=False,
2305
             found_repository=None):
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.
2306
        """Return the branch that the branch reference in a_bzrdir points at.
2307
4160.2.12 by Andrew Bennetts
Improve docstrings and remove a line of cruft.
2308
        :param a_bzrdir: A BzrDir that contains a branch.
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
2309
        :param name: Name of colocated branch to open, if any
4160.2.12 by Andrew Bennetts
Improve docstrings and remove a line of cruft.
2310
        :param _found: a private parameter, do not use it. It is used to
2311
            indicate if format probing has already be done.
2312
        :param ignore_fallbacks: when set, no fallback branches will be opened
2313
            (if there are any).  Default is to open fallbacks.
2314
        :param location: The location of the referenced branch.  If
2315
            unspecified, this will be determined from the branch reference in
2316
            a_bzrdir.
2317
        :param possible_transports: An optional reusable transports list.
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.
2318
        """
2319
        if not _found:
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
2320
            format = BranchFormat.find_format(a_bzrdir, name=name)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
2321
            if format.__class__ != self.__class__:
2322
                raise AssertionError("wrong format %r found for %r" %
2323
                    (format, self))
2018.6.1 by Robert Collins
Implement a BzrDir.open_branch smart server method for opening a branch without VFS.
2324
        if location is None:
5147.4.4 by Jelmer Vernooij
Support colocated branches in BranchReference.
2325
            location = self.get_reference(a_bzrdir, name)
2955.5.2 by Vincent Ladeuil
Fix first unwanted connection.
2326
        real_bzrdir = bzrdir.BzrDir.open(
2327
            location, possible_transports=possible_transports)
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
2328
        result = real_bzrdir.open_branch(name=name, 
2329
            ignore_fallbacks=ignore_fallbacks)
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.
2330
        # this changes the behaviour of result.clone to create a new reference
2331
        # rather than a copy of the content of the branch.
2332
        # I did not use a proxy object because that needs much more extensive
2333
        # testing, and we are only changing one behaviour at the moment.
2334
        # If we decide to alter more behaviours - i.e. the implicit nickname
2335
        # then this should be refactored to introduce a tested proxy branch
2336
        # and a subclass of that for use in overriding clone() and ....
2337
        # - RBC 20060210
2338
        result.clone = self._make_reference_clone_function(result)
2339
        return result
2340
2341
5669.3.9 by Jelmer Vernooij
Consistent naming.
2342
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
5662.2.1 by Jelmer Vernooij
Add BranchFormatRegistry.
2343
    """Branch format registry."""
2344
2345
    def __init__(self, other_registry=None):
2346
        super(BranchFormatRegistry, self).__init__(other_registry)
5662.2.2 by Jelmer Vernooij
Move most format registration functions to BranchFormatRegistry.
2347
        self._default_format = None
2348
2349
    def set_default(self, format):
2350
        self._default_format = format
2351
2352
    def get_default(self):
2353
        return self._default_format
2354
5662.2.1 by Jelmer Vernooij
Add BranchFormatRegistry.
2355
4032.3.1 by Robert Collins
Add a BranchFormat.network_name() method as preparation for creating branches via RPC calls.
2356
network_format_registry = registry.FormatRegistry()
2357
"""Registry of formats indexed by their network name.
2358
4070.2.1 by Robert Collins
Add a BzrDirFormat.network_name.
2359
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.
2360
referring to formats with smart server operations. See
2361
BranchFormat.network_name() for more detail.
2362
"""
2363
5662.2.1 by Jelmer Vernooij
Add BranchFormatRegistry.
2364
format_registry = BranchFormatRegistry(network_format_registry)
2365
4032.3.1 by Robert Collins
Add a BranchFormat.network_name() method as preparation for creating branches via RPC calls.
2366
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
2367
# formats which have no format string are not discoverable
2368
# and not independently creatable, so are not registered.
2696.3.3 by Martin Pool
Start setting the default format to dirstate-tags
2369
__format5 = BzrBranchFormat5()
2370
__format6 = BzrBranchFormat6()
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2371
__format7 = BzrBranchFormat7()
4273.1.1 by Aaron Bentley
Implement branch format for tree references.
2372
__format8 = BzrBranchFormat8()
5662.2.2 by Jelmer Vernooij
Move most format registration functions to BranchFormatRegistry.
2373
format_registry.register(__format5)
2374
format_registry.register(BranchReferenceFormat())
2375
format_registry.register(__format6)
2376
format_registry.register(__format7)
2377
format_registry.register(__format8)
2378
format_registry.set_default(__format7)
4032.3.1 by Robert Collins
Add a BranchFormat.network_name() method as preparation for creating branches via RPC calls.
2379
1534.4.5 by Robert Collins
Turn branch format.open into a factory.
2380
5200.3.6 by Robert Collins
Make all lock methods return Result objects, rather than lock_read returning self, as per John's review.
2381
class BranchWriteLockResult(LogicalLockResult):
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
2382
    """The result of write locking a branch.
2383
2384
    :ivar branch_token: The token obtained from the underlying branch lock, or
2385
        None.
2386
    :ivar unlock: A callable which will unlock the lock.
2387
    """
2388
2389
    def __init__(self, unlock, branch_token):
5200.3.6 by Robert Collins
Make all lock methods return Result objects, rather than lock_read returning self, as per John's review.
2390
        LogicalLockResult.__init__(self, unlock)
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
2391
        self.branch_token = branch_token
2392
5200.3.6 by Robert Collins
Make all lock methods return Result objects, rather than lock_read returning self, as per John's review.
2393
    def __repr__(self):
5200.3.5 by Robert Collins
Add __str__ to the new helper classes.
2394
        return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
2395
            self.unlock)
2396
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
2397
4731.1.2 by Andrew Bennetts
Refactor to reduce duplication.
2398
class BzrBranch(Branch, _RelockDebugMixin):
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
2399
    """A branch stored in the actual filesystem.
2400
2401
    Note that it's "local" in the context of the filesystem; it doesn't
2402
    really matter if it's on an nfs/smb/afs/coda/... share, as long as
2403
    it's writable, and can be accessed via the normal filesystem API.
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
2404
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2405
    :ivar _transport: Transport for file operations on this branch's
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
2406
        control files, typically pointing to the .bzr/branch directory.
2407
    :ivar repository: Repository for this branch.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2408
    :ivar base: The url of the base directory for this branch; the one
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
2409
        containing the .bzr directory.
5085.1.1 by Jelmer Vernooij
Let branches know about their colocated name.
2410
    :ivar name: Optional colocated branch name as it exists in the control
2411
        directory.
1 by mbp at sourcefrog
import from baz patch-364
2412
    """
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2413
2367.2.1 by Robert Collins
Remove bzrlib 0.8 compatability where it was making the code unclear or messy. (Robert Collins)
2414
    def __init__(self, _format=None,
5085.1.1 by Jelmer Vernooij
Let branches know about their colocated name.
2415
                 _control_files=None, a_bzrdir=None, name=None,
2416
                 _repository=None, ignore_fallbacks=False):
2367.2.1 by Robert Collins
Remove bzrlib 0.8 compatability where it was making the code unclear or messy. (Robert Collins)
2417
        """Create new branch object at a particular location."""
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
2418
        if a_bzrdir is None:
2367.2.1 by Robert Collins
Remove bzrlib 0.8 compatability where it was making the code unclear or messy. (Robert Collins)
2419
            raise ValueError('a_bzrdir must be supplied')
1534.4.44 by Robert Collins
Make a new BzrDir format that uses a versioned branch format in a branch/ subdirectory.
2420
        else:
2421
            self.bzrdir = a_bzrdir
2220.2.16 by mbp at sourcefrog
Make Branch._transport be the branch's control file transport
2422
        self._base = self.bzrdir.transport.clone('..').base
5085.1.1 by Jelmer Vernooij
Let branches know about their colocated name.
2423
        self.name = name
3446.1.1 by Martin Pool
merge further LockableFile deprecations
2424
        # XXX: We should be able to just do
2425
        #   self.base = self.bzrdir.root_transport.base
2426
        # but this does not quite work yet -- mbp 20080522
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
2427
        self._format = _format
1534.4.28 by Robert Collins
first cut at merge from integration.
2428
        if _control_files is None:
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
2429
            raise ValueError('BzrBranch _control_files is None')
1534.4.28 by Robert Collins
first cut at merge from integration.
2430
        self.control_files = _control_files
2220.2.16 by mbp at sourcefrog
Make Branch._transport be the branch's control file transport
2431
        self._transport = _control_files._transport
1534.6.4 by Robert Collins
Creating or opening a branch will use the repository if the format supports that.
2432
        self.repository = _repository
3221.11.11 by Robert Collins
Ensure opening a stacked branch gives a ready to use repository.
2433
        Branch.__init__(self)
1534.4.1 by Robert Collins
Allow parameterisation of the branch initialisation for bzrlib.
2434
1 by mbp at sourcefrog
import from baz patch-364
2435
    def __str__(self):
5085.1.1 by Jelmer Vernooij
Let branches know about their colocated name.
2436
        if self.name is None:
5158.6.3 by Martin Pool
Update some Branch calls to use ControlComponent style.
2437
            return '%s(%s)' % (self.__class__.__name__, self.user_url)
5085.1.1 by Jelmer Vernooij
Let branches know about their colocated name.
2438
        else:
5158.6.3 by Martin Pool
Update some Branch calls to use ControlComponent style.
2439
            return '%s(%s,%s)' % (self.__class__.__name__, self.user_url,
2440
                self.name)
1 by mbp at sourcefrog
import from baz patch-364
2441
2442
    __repr__ = __str__
2443
907.1.17 by John Arbash Meinel
Adding a Branch.base property, removing pull_loc()
2444
    def _get_base(self):
2220.2.16 by mbp at sourcefrog
Make Branch._transport be the branch's control file transport
2445
        """Returns the directory containing the control directory."""
1185.69.2 by John Arbash Meinel
Changed LockableFiles to take the root directory directly. Moved mode information into LockableFiles instead of Branch
2446
        return self._base
907.1.17 by John Arbash Meinel
Adding a Branch.base property, removing pull_loc()
2447
1442.1.5 by Robert Collins
Give branch.base a docstring.
2448
    base = property(_get_base, doc="The URL for the root of this branch.")
578 by Martin Pool
- start to move toward Branch.lock and unlock methods,
2449
4226.1.5 by Robert Collins
Reinstate the use of the Branch.get_config_file verb.
2450
    def _get_config(self):
6105.1.1 by Jelmer Vernooij
Fix "pydoc bzrlib.branch" by importing modules, not objects, using lazy_import.
2451
        return _mod_config.TransportConfig(self._transport, 'branch.conf')
4226.1.5 by Robert Collins
Reinstate the use of the Branch.get_config_file verb.
2452
1694.2.6 by Martin Pool
[merge] bzr.dev
2453
    def is_locked(self):
2454
        return self.control_files.is_locked()
2455
2018.5.142 by Andrew Bennetts
Change Branch.lock_token to only accept and receive the branch lock token (rather than the branch and repo lock tokens).
2456
    def lock_write(self, token=None):
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
2457
        """Lock the branch for write operations.
2458
2459
        :param token: A token to permit reacquiring a previously held and
2460
            preserved lock.
2461
        :return: A BranchWriteLockResult.
2462
        """
4731.1.2 by Andrew Bennetts
Refactor to reduce duplication.
2463
        if not self.is_locked():
2464
            self._note_lock('w')
4288.1.12 by Robert Collins
Review feedback.
2465
        # All-in-one needs to always unlock/lock.
4288.1.10 by Robert Collins
Fix up lock correctness to deal with adding fallback repositories to locked branch objects.
2466
        repo_control = getattr(self.repository, 'control_files', None)
4288.1.11 by Robert Collins
Hopefully fix locking tests to match the new code (and still be good statements of intent).
2467
        if self.control_files == repo_control or not self.is_locked():
4840.2.7 by Vincent Ladeuil
Move the _warn_if_deprecated call from repo.__init__ to
2468
            self.repository._warn_if_deprecated(self)
4288.1.10 by Robert Collins
Fix up lock correctness to deal with adding fallback repositories to locked branch objects.
2469
            self.repository.lock_write()
2470
            took_lock = True
2471
        else:
2472
            took_lock = False
1711.8.1 by John Arbash Meinel
Branch.lock_read/lock_write/unlock should handle failures
2473
        try:
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
2474
            return BranchWriteLockResult(self.unlock,
2475
                self.control_files.lock_write(token=token))
1711.8.1 by John Arbash Meinel
Branch.lock_read/lock_write/unlock should handle failures
2476
        except:
4288.1.10 by Robert Collins
Fix up lock correctness to deal with adding fallback repositories to locked branch objects.
2477
            if took_lock:
2478
                self.repository.unlock()
1711.8.1 by John Arbash Meinel
Branch.lock_read/lock_write/unlock should handle failures
2479
            raise
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
2480
1185.65.3 by Aaron Bentley
Fixed locking-- all tests pass
2481
    def lock_read(self):
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
2482
        """Lock the branch for read operations.
2483
5200.3.6 by Robert Collins
Make all lock methods return Result objects, rather than lock_read returning self, as per John's review.
2484
        :return: A bzrlib.lock.LogicalLockResult.
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
2485
        """
4731.1.2 by Andrew Bennetts
Refactor to reduce duplication.
2486
        if not self.is_locked():
2487
            self._note_lock('r')
4288.1.12 by Robert Collins
Review feedback.
2488
        # All-in-one needs to always unlock/lock.
4288.1.10 by Robert Collins
Fix up lock correctness to deal with adding fallback repositories to locked branch objects.
2489
        repo_control = getattr(self.repository, 'control_files', None)
4288.1.11 by Robert Collins
Hopefully fix locking tests to match the new code (and still be good statements of intent).
2490
        if self.control_files == repo_control or not self.is_locked():
4840.2.7 by Vincent Ladeuil
Move the _warn_if_deprecated call from repo.__init__ to
2491
            self.repository._warn_if_deprecated(self)
4288.1.10 by Robert Collins
Fix up lock correctness to deal with adding fallback repositories to locked branch objects.
2492
            self.repository.lock_read()
2493
            took_lock = True
2494
        else:
2495
            took_lock = False
1711.8.1 by John Arbash Meinel
Branch.lock_read/lock_write/unlock should handle failures
2496
        try:
1711.8.3 by John Arbash Meinel
Branch should lock Repository before it locks self, and unlock self before Repository
2497
            self.control_files.lock_read()
5200.3.6 by Robert Collins
Make all lock methods return Result objects, rather than lock_read returning self, as per John's review.
2498
            return LogicalLockResult(self.unlock)
1711.8.1 by John Arbash Meinel
Branch.lock_read/lock_write/unlock should handle failures
2499
        except:
4288.1.10 by Robert Collins
Fix up lock correctness to deal with adding fallback repositories to locked branch objects.
2500
            if took_lock:
2501
                self.repository.unlock()
1711.8.1 by John Arbash Meinel
Branch.lock_read/lock_write/unlock should handle failures
2502
            raise
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
2503
4634.85.11 by Andrew Bennetts
Suppress most errors from Branch.unlock too.
2504
    @only_raises(errors.LockNotHeld, errors.LockBroken)
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
2505
    def unlock(self):
4288.1.11 by Robert Collins
Hopefully fix locking tests to match the new code (and still be good statements of intent).
2506
        try:
2507
            self.control_files.unlock()
2508
        finally:
4288.1.12 by Robert Collins
Review feedback.
2509
            # All-in-one needs to always unlock/lock.
4288.1.11 by Robert Collins
Hopefully fix locking tests to match the new code (and still be good statements of intent).
2510
            repo_control = getattr(self.repository, 'control_files', None)
2511
            if (self.control_files == repo_control or
2512
                not self.control_files.is_locked()):
2513
                self.repository.unlock()
2514
            if not self.control_files.is_locked():
2515
                # we just released the lock
2516
                self._clear_cached_state()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2517
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
2518
    def peek_lock_mode(self):
2519
        if self.control_files._lock_count == 0:
2520
            return None
2521
        else:
2522
            return self.control_files._lock_mode
2523
1694.2.6 by Martin Pool
[merge] bzr.dev
2524
    def get_physical_lock_status(self):
2525
        return self.control_files.get_physical_lock_status()
2526
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
2527
    @needs_read_lock
1185.50.9 by John Arbash Meinel
[bug 3632] Matthieu Moy- bzr cat should default to last revision
2528
    def print_file(self, file, revision_id):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
2529
        """See Branch.print_file."""
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
2530
        return self.repository.print_file(file, revision_id)
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
2531
5718.7.15 by Jelmer Vernooij
Decorate _set_revision_history rather than set_revision_history.
2532
    @needs_write_lock
2230.3.51 by Aaron Bentley
Store revno for Branch6, set_last_revision -> set_last_revision_info
2533
    def set_last_revision_info(self, revno, revision_id):
5718.8.12 by Jelmer Vernooij
Fix raising of InvalidRevisionId.
2534
        if not revision_id or not isinstance(revision_id, basestring):
2535
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
5718.8.3 by Jelmer Vernooij
More branch restructuring.
2536
        revision_id = _mod_revision.ensure_null(revision_id)
2537
        old_revno, old_revid = self.last_revision_info()
6123.9.11 by Jelmer Vernooij
Make get_append_revisions_only public.
2538
        if self.get_append_revisions_only():
5718.8.3 by Jelmer Vernooij
More branch restructuring.
2539
            self._check_history_violation(revision_id)
2540
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
2541
        self._write_last_revision_info(revno, revision_id)
2542
        self._clear_cached_state()
2543
        self._last_revision_info_cache = revno, revision_id
2544
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2230.4.1 by Aaron Bentley
Get log as fast branch5
2545
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
2546
    def basis_tree(self):
2547
        """See Branch.basis_tree."""
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
2548
        return self.repository.revision_tree(self.last_revision())
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
2549
2230.3.8 by Aaron Bentley
Abstract mechanism from policy getting/setting parents
2550
    def _get_parent_location(self):
2551
        _locs = ['parent', 'pull', 'x-pull']
2552
        for l in _locs:
2553
            try:
3407.2.1 by Martin Pool
Deprecate LockableFiles.get
2554
                return self._transport.get_bytes(l).strip('\n')
3236.1.2 by Michael Hudson
clean up branch.py imports
2555
            except errors.NoSuchFile:
2230.3.8 by Aaron Bentley
Abstract mechanism from policy getting/setting parents
2556
                pass
2557
        return None
2558
3537.3.1 by Martin Pool
Rename branch.get_stacked_on to get_stacked_on_url
2559
    def get_stacked_on_url(self):
5158.6.3 by Martin Pool
Update some Branch calls to use ControlComponent style.
2560
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2561
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
2562
    def set_push_location(self, location):
1495.1.2 by Jelmer Vernooij
Move some generic methods of NativeBranch to Branch.
2563
        """See Branch.set_push_location."""
2120.6.4 by James Henstridge
add support for specifying policy when storing options
2564
        self.get_config().set_user_option(
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
2565
            'push_location', location,
2566
            store=_mod_config.STORE_LOCATION_NORECURSE)
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
2567
2230.3.8 by Aaron Bentley
Abstract mechanism from policy getting/setting parents
2568
    def _set_parent_location(self, url):
2569
        if url is None:
3407.2.3 by Martin Pool
Branch and Repository use their own ._transport rather than going through .control_files
2570
            self._transport.delete('parent')
2230.3.8 by Aaron Bentley
Abstract mechanism from policy getting/setting parents
2571
        else:
3407.2.3 by Martin Pool
Branch and Repository use their own ._transport rather than going through .control_files
2572
            self._transport.put_bytes('parent', url + '\n',
3407.2.18 by Martin Pool
BzrDir takes responsibility for default file/dir modes
2573
                mode=self.bzrdir._get_file_mode())
1150 by Martin Pool
- add new Branch.set_parent and tests
2574
5718.8.2 by Jelmer Vernooij
Split out full history branch code.
2575
    @needs_write_lock
2576
    def unbind(self):
2577
        """If bound, unbind"""
2578
        return self.set_bound_location(None)
2579
2580
    @needs_write_lock
2581
    def bind(self, other):
2582
        """Bind this branch to the branch other.
2583
2584
        This does not push or pull data between the branches, though it does
2585
        check for divergence to raise an error when the branches are not
2586
        either the same, or one a prefix of the other. That behaviour may not
2587
        be useful, so that check may be removed in future.
2588
2589
        :param other: The branch to bind to
2590
        :type other: Branch
2591
        """
2592
        # TODO: jam 20051230 Consider checking if the target is bound
2593
        #       It is debatable whether you should be able to bind to
2594
        #       a branch which is itself bound.
2595
        #       Committing is obviously forbidden,
2596
        #       but binding itself may not be.
2597
        #       Since we *have* to check at commit time, we don't
2598
        #       *need* to check here
2599
2600
        # we want to raise diverged if:
2601
        # last_rev is not in the other_last_rev history, AND
2602
        # other_last_rev is not in our history, and do it without pulling
2603
        # history around
2604
        self.set_bound_location(other.base)
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
2605
1505.1.3 by John Arbash Meinel
(broken) Adding more tests, and some functionality
2606
    def get_bound_location(self):
1185.66.8 by Aaron Bentley
Applied Jelmer's patch to make clone a branch operation
2607
        try:
3388.2.1 by Martin Pool
Deprecate LockableFiles.get_utf8
2608
            return self._transport.get_bytes('bound')[:-1]
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
2609
        except errors.NoSuchFile:
1505.1.3 by John Arbash Meinel
(broken) Adding more tests, and some functionality
2610
            return None
1185.66.8 by Aaron Bentley
Applied Jelmer's patch to make clone a branch operation
2611
2612
    @needs_read_lock
2806.2.2 by Vincent Ladeuil
Fix #128076 and #131396 by reusing bound branch transport.
2613
    def get_master_branch(self, possible_transports=None):
1505.1.24 by John Arbash Meinel
Updated commit to handle bound branches. Included test to handle commit after merge
2614
        """Return the branch we are bound to.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2615
1505.1.24 by John Arbash Meinel
Updated commit to handle bound branches. Included test to handle commit after merge
2616
        :return: Either a Branch, or None
2617
        """
5609.25.3 by Andrew Bennetts
Alternative fix: cache the result of get_master_branch for the lifetime of the branch lock.
2618
        if self._master_branch_cache is None:
2619
            self._master_branch_cache = self._get_master_branch(
2620
                possible_transports)
2621
        return self._master_branch_cache
2622
2623
    def _get_master_branch(self, possible_transports):
1505.1.24 by John Arbash Meinel
Updated commit to handle bound branches. Included test to handle commit after merge
2624
        bound_loc = self.get_bound_location()
2625
        if not bound_loc:
2626
            return None
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
2627
        try:
2806.2.2 by Vincent Ladeuil
Fix #128076 and #131396 by reusing bound branch transport.
2628
            return Branch.open(bound_loc,
2629
                               possible_transports=possible_transports)
1587.1.6 by Robert Collins
Update bound branch implementation to 0.8.
2630
        except (errors.NotBranchError, errors.ConnectionError), e:
2631
            raise errors.BoundBranchConnectionFailure(
2632
                    self, bound_loc, e)
1505.1.24 by John Arbash Meinel
Updated commit to handle bound branches. Included test to handle commit after merge
2633
1505.1.5 by John Arbash Meinel
Added a test for the unbind command.
2634
    @needs_write_lock
1505.1.3 by John Arbash Meinel
(broken) Adding more tests, and some functionality
2635
    def set_bound_location(self, location):
1505.1.27 by John Arbash Meinel
Adding tests against an sftp branch.
2636
        """Set the target where this branch is bound to.
2637
2638
        :param location: URL to the target branch
2639
        """
5609.25.3 by Andrew Bennetts
Alternative fix: cache the result of get_master_branch for the lifetime of the branch lock.
2640
        self._master_branch_cache = None
1505.1.25 by John Arbash Meinel
Updated pull. Now all paths which call set_revision_history maintain the branch invariant. All tests pass.
2641
        if location:
3446.1.1 by Martin Pool
merge further LockableFile deprecations
2642
            self._transport.put_bytes('bound', location+'\n',
2643
                mode=self.bzrdir._get_file_mode())
1185.64.2 by Goffredo Baroncelli
- implemented some suggestion by Robert Collins
2644
        else:
1505.1.25 by John Arbash Meinel
Updated pull. Now all paths which call set_revision_history maintain the branch invariant. All tests pass.
2645
            try:
3407.2.3 by Martin Pool
Branch and Repository use their own ._transport rather than going through .control_files
2646
                self._transport.delete('bound')
3236.1.2 by Michael Hudson
clean up branch.py imports
2647
            except errors.NoSuchFile:
1505.1.25 by John Arbash Meinel
Updated pull. Now all paths which call set_revision_history maintain the branch invariant. All tests pass.
2648
                return False
2649
            return True
1185.66.8 by Aaron Bentley
Applied Jelmer's patch to make clone a branch operation
2650
1587.1.10 by Robert Collins
update updates working tree and branch together.
2651
    @needs_write_lock
2806.2.2 by Vincent Ladeuil
Fix #128076 and #131396 by reusing bound branch transport.
2652
    def update(self, possible_transports=None):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2653
        """Synchronise this branch with the master branch if any.
1587.1.10 by Robert Collins
update updates working tree and branch together.
2654
2655
        :return: None or the last_revision that was pivoted out during the
2656
                 update.
2657
        """
2806.2.2 by Vincent Ladeuil
Fix #128076 and #131396 by reusing bound branch transport.
2658
        master = self.get_master_branch(possible_transports)
1587.1.10 by Robert Collins
update updates working tree and branch together.
2659
        if master is not None:
2653.2.4 by Aaron Bentley
Remove get_ancestry usage from branch
2660
            old_tip = _mod_revision.ensure_null(self.last_revision())
1587.1.10 by Robert Collins
update updates working tree and branch together.
2661
            self.pull(master, overwrite=True)
2653.2.4 by Aaron Bentley
Remove get_ancestry usage from branch
2662
            if self.repository.get_graph().is_ancestor(old_tip,
2663
                _mod_revision.ensure_null(self.last_revision())):
1587.1.10 by Robert Collins
update updates working tree and branch together.
2664
                return None
2665
            return old_tip
2666
        return None
2667
5718.8.2 by Jelmer Vernooij
Split out full history branch code.
2668
    def _read_last_revision_info(self):
2669
        revision_string = self._transport.get_bytes('last-revision')
2670
        revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
2671
        revision_id = cache_utf8.get_cached_utf8(revision_id)
2672
        revno = int(revno)
2673
        return revno, revision_id
2674
2675
    def _write_last_revision_info(self, revno, revision_id):
2676
        """Simply write out the revision id, with no checks.
2677
2678
        Use set_last_revision_info to perform this safely.
2679
2680
        Does not update the revision_history cache.
2681
        """
2682
        revision_id = _mod_revision.ensure_null(revision_id)
2683
        out_string = '%d %s\n' % (revno, revision_id)
2684
        self._transport.put_bytes('last-revision', out_string,
2685
            mode=self.bzrdir._get_file_mode())
2686
2687
2688
class FullHistoryBzrBranch(BzrBranch):
2689
    """Bzr branch which contains the full revision history."""
2690
2691
    @needs_write_lock
2692
    def set_last_revision_info(self, revno, revision_id):
5718.8.12 by Jelmer Vernooij
Fix raising of InvalidRevisionId.
2693
        if not revision_id or not isinstance(revision_id, basestring):
2694
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
5718.8.2 by Jelmer Vernooij
Split out full history branch code.
2695
        revision_id = _mod_revision.ensure_null(revision_id)
2696
        # this old format stores the full history, but this api doesn't
2697
        # provide it, so we must generate, and might as well check it's
2698
        # correct
2699
        history = self._lefthand_history(revision_id)
2700
        if len(history) != revno:
2701
            raise AssertionError('%d != %d' % (len(history), revno))
2702
        self._set_revision_history(history)
2703
2704
    def _read_last_revision_info(self):
2705
        rh = self.revision_history()
2706
        revno = len(rh)
2707
        if revno:
2708
            return (revno, rh[-1])
2709
        else:
2710
            return (0, _mod_revision.NULL_REVISION)
2711
2712
    @deprecated_method(deprecated_in((2, 4, 0)))
2713
    @needs_write_lock
2714
    def set_revision_history(self, rev_history):
2715
        """See Branch.set_revision_history."""
2716
        self._set_revision_history(rev_history)
2717
2718
    def _set_revision_history(self, rev_history):
2719
        if 'evil' in debug.debug_flags:
2720
            mutter_callsite(3, "set_revision_history scales with history.")
2721
        check_not_reserved_id = _mod_revision.check_not_reserved_id
2722
        for rev_id in rev_history:
2723
            check_not_reserved_id(rev_id)
2724
        if Branch.hooks['post_change_branch_tip']:
2725
            # Don't calculate the last_revision_info() if there are no hooks
2726
            # that will use it.
2727
            old_revno, old_revid = self.last_revision_info()
2728
        if len(rev_history) == 0:
2729
            revid = _mod_revision.NULL_REVISION
2730
        else:
2731
            revid = rev_history[-1]
2732
        self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
2733
        self._write_revision_history(rev_history)
2734
        self._clear_cached_state()
2735
        self._cache_revision_history(rev_history)
2736
        for hook in Branch.hooks['set_rh']:
2737
            hook(self, rev_history)
2738
        if Branch.hooks['post_change_branch_tip']:
2739
            self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2740
2741
    def _write_revision_history(self, history):
2742
        """Factored out of set_revision_history.
2743
2744
        This performs the actual writing to disk.
2745
        It is intended to be called by set_revision_history."""
2746
        self._transport.put_bytes(
2747
            'revision-history', '\n'.join(history),
2748
            mode=self.bzrdir._get_file_mode())
2749
2750
    def _gen_revision_history(self):
2751
        history = self._transport.get_bytes('revision-history').split('\n')
2752
        if history[-1:] == ['']:
2753
            # There shouldn't be a trailing newline, but just in case.
2754
            history.pop()
2755
        return history
2756
2757
    def _synchronize_history(self, destination, revision_id):
5718.8.11 by Jelmer Vernooij
Fix _synchronize_history check.
2758
        if not isinstance(destination, FullHistoryBzrBranch):
5718.8.2 by Jelmer Vernooij
Split out full history branch code.
2759
            super(BzrBranch, self)._synchronize_history(
2760
                destination, revision_id)
2761
            return
2762
        if revision_id == _mod_revision.NULL_REVISION:
2763
            new_history = []
2764
        else:
2765
            new_history = self.revision_history()
2766
        if revision_id is not None and new_history != []:
2767
            try:
2768
                new_history = new_history[:new_history.index(revision_id) + 1]
2769
            except ValueError:
2770
                rev = self.repository.get_revision(revision_id)
2771
                new_history = rev.get_history(self.repository)[1:]
2772
        destination._set_revision_history(new_history)
2773
5718.8.6 by Jelmer Vernooij
Move generate_revision_history.
2774
    @needs_write_lock
2775
    def generate_revision_history(self, revision_id, last_rev=None,
2776
        other_branch=None):
2777
        """Create a new revision history that will finish with revision_id.
2778
2779
        :param revision_id: the new tip to use.
2780
        :param last_rev: The previous last_revision. If not None, then this
2781
            must be a ancestory of revision_id, or DivergedBranches is raised.
2782
        :param other_branch: The other branch that DivergedBranches should
2783
            raise with respect to.
2784
        """
2785
        self._set_revision_history(self._lefthand_history(revision_id,
2786
            last_rev, other_branch))
2787
5718.8.2 by Jelmer Vernooij
Split out full history branch code.
2788
2789
class BzrBranch5(FullHistoryBzrBranch):
2790
    """A format 5 branch. This supports new features over plain branches.
2791
2792
    It has support for a master_branch which is the data for bound branches.
2793
    """
2794
2795
2796
class BzrBranch8(BzrBranch):
4273.1.1 by Aaron Bentley
Implement branch format for tree references.
2797
    """A branch that stores tree-reference locations."""
3221.11.11 by Robert Collins
Ensure opening a stacked branch gives a ready to use repository.
2798
2799
    def _open_hook(self):
4160.2.6 by Andrew Bennetts
Add ignore_fallbacks flag.
2800
        if self._ignore_fallbacks:
2801
            return
3221.11.11 by Robert Collins
Ensure opening a stacked branch gives a ready to use repository.
2802
        try:
3537.3.1 by Martin Pool
Rename branch.get_stacked_on to get_stacked_on_url
2803
            url = self.get_stacked_on_url()
3221.11.11 by Robert Collins
Ensure opening a stacked branch gives a ready to use repository.
2804
        except (errors.UnstackableRepositoryFormat, errors.NotStacked,
2805
            errors.UnstackableBranchFormat):
2806
            pass
2807
        else:
3770.2.1 by Michael Hudson
test and feature
2808
            for hook in Branch.hooks['transform_fallback_location']:
2809
                url = hook(self, url)
3770.2.3 by Michael Hudson
check for None being returned for a hook
2810
                if url is None:
2811
                    hook_name = Branch.hooks.get_hook_name(hook)
2812
                    raise AssertionError(
2813
                        "'transform_fallback_location' hook %s returned "
2814
                        "None, not a URL." % hook_name)
4379.2.2 by John Arbash Meinel
Change the Repository.add_fallback_repository() contract slightly.
2815
            self._activate_fallback_location(url)
3221.11.11 by Robert Collins
Ensure opening a stacked branch gives a ready to use repository.
2816
4160.2.8 by Andrew Bennetts
Slightly less messy BzrBranch7.__init__.
2817
    def __init__(self, *args, **kwargs):
2818
        self._ignore_fallbacks = kwargs.get('ignore_fallbacks', False)
4273.1.1 by Aaron Bentley
Implement branch format for tree references.
2819
        super(BzrBranch8, self).__init__(*args, **kwargs)
3060.3.1 by Lukáš Lalinský
Cache last_revision_info in BzrBranch6, since this is often called multiple times within one lock and we don't want to read the file over and over again.
2820
        self._last_revision_info_cache = None
4273.1.15 by Aaron Bentley
Add reference_info caching.
2821
        self._reference_info = None
3060.3.1 by Lukáš Lalinský
Cache last_revision_info in BzrBranch6, since this is often called multiple times within one lock and we don't want to read the file over and over again.
2822
2823
    def _clear_cached_state(self):
4273.1.1 by Aaron Bentley
Implement branch format for tree references.
2824
        super(BzrBranch8, self)._clear_cached_state()
3060.3.1 by Lukáš Lalinský
Cache last_revision_info in BzrBranch6, since this is often called multiple times within one lock and we don't want to read the file over and over again.
2825
        self._last_revision_info_cache = None
4273.1.15 by Aaron Bentley
Add reference_info caching.
2826
        self._reference_info = None
3060.3.1 by Lukáš Lalinský
Cache last_revision_info in BzrBranch6, since this is often called multiple times within one lock and we don't want to read the file over and over again.
2827
2230.3.32 by Aaron Bentley
Implement strict history policy
2828
    def _check_history_violation(self, revision_id):
5718.8.23 by Jelmer Vernooij
Avoid Branch._lefthand_history when checking for history violations.
2829
        current_revid = self.last_revision()
2830
        last_revision = _mod_revision.ensure_null(current_revid)
2598.5.2 by Aaron Bentley
Got all tests passing with Branch returning 'null:' for null revision
2831
        if _mod_revision.is_null(last_revision):
2230.3.32 by Aaron Bentley
Implement strict history policy
2832
            return
5718.8.23 by Jelmer Vernooij
Avoid Branch._lefthand_history when checking for history violations.
2833
        graph = self.repository.get_graph()
2834
        for lh_ancestor in graph.iter_lefthand_ancestry(revision_id):
2835
            if lh_ancestor == current_revid:
2836
                return
2837
        raise errors.AppendRevisionsOnlyViolation(self.user_url)
2230.3.32 by Aaron Bentley
Implement strict history policy
2838
2230.4.1 by Aaron Bentley
Get log as fast branch5
2839
    def _gen_revision_history(self):
2230.3.2 by Aaron Bentley
Get all branch tests passing
2840
        """Generate the revision history from last revision
2841
        """
3495.2.1 by Aaron Bentley
Tolerate ghosts in mainline (#235055)
2842
        last_revno, last_revision = self.last_revision_info()
2843
        self._extend_partial_history(stop_index=last_revno-1)
3298.2.10 by Aaron Bentley
Refactor partial history code
2844
        return list(reversed(self._partial_revision_history_cache))
2845
2230.3.36 by Aaron Bentley
Refactor getting/setting locations with config
2846
    @needs_write_lock
2847
    def _set_parent_location(self, url):
2848
        """Set the parent branch"""
2849
        self._set_config_location('parent_location', url, make_relative=True)
2230.3.3 by Aaron Bentley
Add more config testing
2850
2851
    @needs_read_lock
2230.3.8 by Aaron Bentley
Abstract mechanism from policy getting/setting parents
2852
    def _get_parent_location(self):
2230.3.3 by Aaron Bentley
Add more config testing
2853
        """Set the parent branch"""
2230.3.36 by Aaron Bentley
Refactor getting/setting locations with config
2854
        return self._get_config_location('parent_location')
2230.3.3 by Aaron Bentley
Add more config testing
2855
4273.1.15 by Aaron Bentley
Add reference_info caching.
2856
    @needs_write_lock
4273.1.11 by Aaron Bentley
Clean up naming and docstrings
2857
    def _set_all_reference_info(self, info_dict):
2858
        """Replace all reference info stored in a branch.
2859
2860
        :param info_dict: A dict of {file_id: (tree_path, branch_location)}
2861
        """
2862
        s = StringIO()
2863
        writer = rio.RioWriter(s)
2864
        for key, (tree_path, branch_location) in info_dict.iteritems():
2865
            stanza = rio.Stanza(file_id=key, tree_path=tree_path,
2866
                                branch_location=branch_location)
2867
            writer.write_stanza(stanza)
2868
        self._transport.put_bytes('references', s.getvalue())
4273.1.15 by Aaron Bentley
Add reference_info caching.
2869
        self._reference_info = info_dict
4273.1.11 by Aaron Bentley
Clean up naming and docstrings
2870
4273.1.15 by Aaron Bentley
Add reference_info caching.
2871
    @needs_read_lock
4273.1.11 by Aaron Bentley
Clean up naming and docstrings
2872
    def _get_all_reference_info(self):
2873
        """Return all the reference info stored in a branch.
2874
2875
        :return: A dict of {file_id: (tree_path, branch_location)}
2876
        """
4273.1.15 by Aaron Bentley
Add reference_info caching.
2877
        if self._reference_info is not None:
2878
            return self._reference_info
4273.1.1 by Aaron Bentley
Implement branch format for tree references.
2879
        rio_file = self._transport.get('references')
2880
        try:
2881
            stanzas = rio.read_stanzas(rio_file)
2882
            info_dict = dict((s['file_id'], (s['tree_path'],
2883
                             s['branch_location'])) for s in stanzas)
2884
        finally:
2885
            rio_file.close()
4273.1.15 by Aaron Bentley
Add reference_info caching.
2886
        self._reference_info = info_dict
4273.1.1 by Aaron Bentley
Implement branch format for tree references.
2887
        return info_dict
2888
2889
    def set_reference_info(self, file_id, tree_path, branch_location):
4273.1.11 by Aaron Bentley
Clean up naming and docstrings
2890
        """Set the branch location to use for a tree reference.
2891
2892
        :param file_id: The file-id of the tree reference.
2893
        :param tree_path: The path of the tree reference in the tree.
2894
        :param branch_location: The location of the branch to retrieve tree
2895
            references from.
2896
        """
2897
        info_dict = self._get_all_reference_info()
4273.1.1 by Aaron Bentley
Implement branch format for tree references.
2898
        info_dict[file_id] = (tree_path, branch_location)
2899
        if None in (tree_path, branch_location):
2900
            if tree_path is not None:
2901
                raise ValueError('tree_path must be None when branch_location'
2902
                                 ' is None.')
2903
            if branch_location is not None:
2904
                raise ValueError('branch_location must be None when tree_path'
2905
                                 ' is None.')
2906
            del info_dict[file_id]
4273.1.11 by Aaron Bentley
Clean up naming and docstrings
2907
        self._set_all_reference_info(info_dict)
4273.1.1 by Aaron Bentley
Implement branch format for tree references.
2908
2909
    def get_reference_info(self, file_id):
4273.1.11 by Aaron Bentley
Clean up naming and docstrings
2910
        """Get the tree_path and branch_location for a tree reference.
2911
2912
        :return: a tuple of (tree_path, branch_location)
2913
        """
2914
        return self._get_all_reference_info().get(file_id, (None, None))
4273.1.1 by Aaron Bentley
Implement branch format for tree references.
2915
4273.1.4 by Aaron Bentley
Relative reference locations are branch-relative.
2916
    def reference_parent(self, file_id, path, possible_transports=None):
4273.1.2 by Aaron Bentley
Use reference_info to get reference_parent.
2917
        """Return the parent branch for a tree-reference file_id.
2918
2919
        :param file_id: The file_id of the tree reference
2920
        :param path: The path of the file_id in the tree
2921
        :return: A branch associated with the file_id
2922
        """
2923
        branch_location = self.get_reference_info(file_id)[1]
2924
        if branch_location is None:
4273.1.4 by Aaron Bentley
Relative reference locations are branch-relative.
2925
            return Branch.reference_parent(self, file_id, path,
2926
                                           possible_transports)
5158.6.3 by Martin Pool
Update some Branch calls to use ControlComponent style.
2927
        branch_location = urlutils.join(self.user_url, branch_location)
4273.1.4 by Aaron Bentley
Relative reference locations are branch-relative.
2928
        return Branch.open(branch_location,
2929
                           possible_transports=possible_transports)
4273.1.2 by Aaron Bentley
Use reference_info to get reference_parent.
2930
2230.3.3 by Aaron Bentley
Add more config testing
2931
    def set_push_location(self, location):
2932
        """See Branch.set_push_location."""
2230.3.36 by Aaron Bentley
Refactor getting/setting locations with config
2933
        self._set_config_location('push_location', location)
2230.3.3 by Aaron Bentley
Add more config testing
2934
2935
    def set_bound_location(self, location):
2936
        """See Branch.set_push_location."""
5609.25.5 by Andrew Bennetts
Add tests that get_master_branch isn't cached when it shouldn't be, and fix a bug that reveals.
2937
        self._master_branch_cache = None
2230.3.7 by Aaron Bentley
Fix binding return values
2938
        result = None
2230.3.31 by Aaron Bentley
Implement re-binding previously-bound branches
2939
        config = self.get_config()
2230.3.6 by Aaron Bentley
work in progress bind stuff
2940
        if location is None:
2230.3.31 by Aaron Bentley
Implement re-binding previously-bound branches
2941
            if config.get_user_option('bound') != 'True':
2230.3.7 by Aaron Bentley
Fix binding return values
2942
                return False
2230.3.31 by Aaron Bentley
Implement re-binding previously-bound branches
2943
            else:
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
2944
                config.set_user_option('bound', 'False', warn_masked=True)
2230.3.31 by Aaron Bentley
Implement re-binding previously-bound branches
2945
                return True
2946
        else:
2230.3.36 by Aaron Bentley
Refactor getting/setting locations with config
2947
            self._set_config_location('bound_location', location,
2948
                                      config=config)
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
2949
            config.set_user_option('bound', 'True', warn_masked=True)
2230.3.31 by Aaron Bentley
Implement re-binding previously-bound branches
2950
        return True
2951
2952
    def _get_bound_location(self, bound):
2953
        """Return the bound location in the config file.
2954
2955
        Return None if the bound parameter does not match"""
2956
        config = self.get_config()
2957
        config_bound = (config.get_user_option('bound') == 'True')
2958
        if config_bound != bound:
2959
            return None
2230.3.36 by Aaron Bentley
Refactor getting/setting locations with config
2960
        return self._get_config_location('bound_location', config=config)
2230.3.3 by Aaron Bentley
Add more config testing
2961
2230.3.31 by Aaron Bentley
Implement re-binding previously-bound branches
2962
    def get_bound_location(self):
2963
        """See Branch.set_push_location."""
2964
        return self._get_bound_location(True)
2965
2966
    def get_old_bound_location(self):
2967
        """See Branch.get_old_bound_location"""
2968
        return self._get_bound_location(False)
2969
3537.3.1 by Martin Pool
Rename branch.get_stacked_on to get_stacked_on_url
2970
    def get_stacked_on_url(self):
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
2971
        # you can always ask for the URL; but you might not be able to use it
2972
        # if the repo can't support stacking.
2973
        ## self._check_stackable_repo()
5993.4.1 by Andrew Bennetts
Make Branch.open more than 3x faster.
2974
        # stacked_on_location is only ever defined in branch.conf, so don't
2975
        # waste effort reading the whole stack of config files.
2976
        config = self.get_config()._get_branch_data_config()
2977
        stacked_url = self._get_config_location('stacked_on_location',
2978
            config=config)
3221.18.2 by Ian Clatworthy
store stacked-on location in branch.conf
2979
        if stacked_url is None:
3221.11.6 by Robert Collins
Stackable branch fixes.
2980
            raise errors.NotStacked(self)
2981
        return stacked_url
3221.11.2 by Robert Collins
Create basic stackable branch facility.
2982
3060.3.3 by Lukáš Lalinský
Make RevisionSpec_revid and RevisionSpec_revno not load the whole revision history.
2983
    @needs_read_lock
3060.3.2 by Lukáš Lalinský
Make RevisionSpec_last not load the whole history.
2984
    def get_rev_id(self, revno, history=None):
2985
        """Find the revision id of the specified revno."""
2986
        if revno == 0:
2987
            return _mod_revision.NULL_REVISION
2988
2989
        last_revno, last_revision_id = self.last_revision_info()
2990
        if revno <= 0 or revno > last_revno:
2991
            raise errors.NoSuchRevision(self, revno)
2992
2993
        if history is not None:
3298.3.3 by Aaron Bentley
Update from review
2994
            return history[revno - 1]
3060.3.2 by Lukáš Lalinský
Make RevisionSpec_last not load the whole history.
2995
3298.2.10 by Aaron Bentley
Refactor partial history code
2996
        index = last_revno - revno
3298.3.2 by Aaron Bentley
Catch history mismatch, cleanup
2997
        if len(self._partial_revision_history_cache) <= index:
2998
            self._extend_partial_history(stop_index=index)
3298.2.10 by Aaron Bentley
Refactor partial history code
2999
        if len(self._partial_revision_history_cache) > index:
3000
            return self._partial_revision_history_cache[index]
3060.3.6 by Lukáš Lalinský
Implement partial history cache in BzrBranch6.
3001
        else:
3298.2.10 by Aaron Bentley
Refactor partial history code
3002
            raise errors.NoSuchRevision(self, revno)
3060.3.2 by Lukáš Lalinský
Make RevisionSpec_last not load the whole history.
3003
3298.2.12 by Aaron Bentley
Add Branch6.revision_id_to_revno
3004
    @needs_read_lock
3005
    def revision_id_to_revno(self, revision_id):
3006
        """Given a revision id, return its revno"""
3007
        if _mod_revision.is_null(revision_id):
3008
            return 0
3009
        try:
3010
            index = self._partial_revision_history_cache.index(revision_id)
3011
        except ValueError:
5689.2.1 by Jelmer Vernooij
Properly raise GhostsHaveNoRevno in revision_id_to_revno.
3012
            try:
3013
                self._extend_partial_history(stop_revision=revision_id)
3014
            except errors.RevisionNotPresent, e:
3015
                raise errors.GhostRevisionsHaveNoRevno(revision_id, e.revision_id)
3298.2.12 by Aaron Bentley
Add Branch6.revision_id_to_revno
3016
            index = len(self._partial_revision_history_cache) - 1
3017
            if self._partial_revision_history_cache[index] != revision_id:
3018
                raise errors.NoSuchRevision(self, revision_id)
3019
        return self.revno() - index
3020
2230.3.34 by Aaron Bentley
cleanup
3021
4273.1.1 by Aaron Bentley
Implement branch format for tree references.
3022
class BzrBranch7(BzrBranch8):
3023
    """A branch with support for a fallback repository."""
3024
3025
    def set_reference_info(self, file_id, tree_path, branch_location):
3026
        Branch.set_reference_info(self, file_id, tree_path, branch_location)
3027
3028
    def get_reference_info(self, file_id):
3029
        Branch.get_reference_info(self, file_id)
3030
4273.1.4 by Aaron Bentley
Relative reference locations are branch-relative.
3031
    def reference_parent(self, file_id, path, possible_transports=None):
3032
        return Branch.reference_parent(self, file_id, path,
3033
                                       possible_transports)
4273.1.2 by Aaron Bentley
Use reference_info to get reference_parent.
3034
4273.1.1 by Aaron Bentley
Implement branch format for tree references.
3035
3221.11.2 by Robert Collins
Create basic stackable branch facility.
3036
class BzrBranch6(BzrBranch7):
3037
    """See BzrBranchFormat6 for the capabilities of this branch.
3038
3221.18.1 by Ian Clatworthy
tweaks by ianc during review
3039
    This subclass of BzrBranch7 disables the new features BzrBranch7 added,
3040
    i.e. stacking.
3221.11.2 by Robert Collins
Create basic stackable branch facility.
3041
    """
3042
3537.3.1 by Martin Pool
Rename branch.get_stacked_on to get_stacked_on_url
3043
    def get_stacked_on_url(self):
5158.6.3 by Martin Pool
Update some Branch calls to use ControlComponent style.
3044
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
3221.11.2 by Robert Collins
Create basic stackable branch facility.
3045
3046
2297.1.1 by Martin Pool
Pull now returns a PullResult rather than just an integer.
3047
######################################################################
3048
# results of operations
3049
2220.2.37 by Martin Pool
Report conflicting tags from push.
3050
3051
class _Result(object):
3052
3053
    def _show_tag_conficts(self, to_file):
3054
        if not getattr(self, 'tag_conflicts', None):
3055
            return
3056
        to_file.write('Conflicting tags:\n')
3057
        for name, value1, value2 in self.tag_conflicts:
3058
            to_file.write('    %s\n' % (name, ))
3059
3060
3061
class PullResult(_Result):
2297.1.6 by Martin Pool
Add docs for Results, give some members cleaner names
3062
    """Result of a Branch.pull operation.
3063
3064
    :ivar old_revno: Revision number before pull.
3065
    :ivar new_revno: Revision number after pull.
3066
    :ivar old_revid: Tip revision id before pull.
3067
    :ivar new_revid: Tip revision id after pull.
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
3068
    :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.
3069
    :ivar master_branch: Master branch of the target, or the target if no
3070
        Master
3071
    :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.
3072
    :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.
3073
    :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.
3074
    :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
3075
    """
2297.1.1 by Martin Pool
Pull now returns a PullResult rather than just an integer.
3076
5348.1.2 by Martin Pool
Deprecate casting PushResult and PullResult to int to get the relative revno change
3077
    @deprecated_method(deprecated_in((2, 3, 0)))
2297.1.3 by Martin Pool
PullResult can pretend to be an int for api compatibility with old .pull()
3078
    def __int__(self):
5348.1.2 by Martin Pool
Deprecate casting PushResult and PullResult to int to get the relative revno change
3079
        """Return the relative change in revno.
3080
3081
        :deprecated: Use `new_revno` and `old_revno` instead.
3082
        """
2297.1.4 by Martin Pool
Push now returns a PushResult rather than just an integer.
3083
        return self.new_revno - self.old_revno
3084
2220.2.39 by Martin Pool
Pull also merges tags and warns if they conflict
3085
    def report(self, to_file):
6112.4.3 by Jelmer Vernooij
Fix push tests.
3086
        tag_conflicts = getattr(self, "tag_conflicts", None)
3087
        tag_updates = getattr(self, "tag_updates", None)
3200.1.1 by James Westby
Make pull --quiet more quiet. Fixes #185907.
3088
        if not is_quiet():
6112.4.1 by Jelmer Vernooij
Show how many tags have been updated in bzr pull.
3089
            if self.old_revid != self.new_revid:
3200.1.1 by James Westby
Make pull --quiet more quiet. Fixes #185907.
3090
                to_file.write('Now on revision %d.\n' % self.new_revno)
6112.4.3 by Jelmer Vernooij
Fix push tests.
3091
            if tag_updates:
3092
                to_file.write('%d tag(s) updated.\n' % len(tag_updates))
3093
            if self.old_revid == self.new_revid and not tag_updates:
3094
                if not tag_conflicts:
6112.4.1 by Jelmer Vernooij
Show how many tags have been updated in bzr pull.
3095
                    to_file.write('No revisions or tags to pull.\n')
3096
                else:
3097
                    to_file.write('No revisions to pull.\n')
2220.2.39 by Martin Pool
Pull also merges tags and warns if they conflict
3098
        self._show_tag_conficts(to_file)
3099
2297.1.4 by Martin Pool
Push now returns a PushResult rather than just an integer.
3100
4053.3.1 by Jelmer Vernooij
Rename PushResult to BranchPushResult.
3101
class BranchPushResult(_Result):
2297.1.6 by Martin Pool
Add docs for Results, give some members cleaner names
3102
    """Result of a Branch.push operation.
3103
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
3104
    :ivar old_revno: Revision number (eg 10) of the target before push.
3105
    :ivar new_revno: Revision number (eg 12) of the target after push.
3106
    :ivar old_revid: Tip revision id (eg joe@foo.com-1234234-aoeua34) of target
3107
        before the push.
3108
    :ivar new_revid: Tip revision id (eg joe@foo.com-5676566-boa234a) of target
3109
        after the push.
3110
    :ivar source_branch: Source branch object that the push was from. This is
3111
        read locked, and generally is a local (and thus low latency) branch.
3112
    :ivar master_branch: If target is a bound branch, the master branch of
3113
        target, or target itself. Always write locked.
3114
    :ivar target_branch: The direct Branch where data is being sent (write
3115
        locked).
3116
    :ivar local_branch: If the target is a bound branch this will be the
3117
        target, otherwise it will be None.
2297.1.6 by Martin Pool
Add docs for Results, give some members cleaner names
3118
    """
2297.1.4 by Martin Pool
Push now returns a PushResult rather than just an integer.
3119
5348.1.2 by Martin Pool
Deprecate casting PushResult and PullResult to int to get the relative revno change
3120
    @deprecated_method(deprecated_in((2, 3, 0)))
2297.1.4 by Martin Pool
Push now returns a PushResult rather than just an integer.
3121
    def __int__(self):
5348.1.2 by Martin Pool
Deprecate casting PushResult and PullResult to int to get the relative revno change
3122
        """Return the relative change in revno.
3123
3124
        :deprecated: Use `new_revno` and `old_revno` instead.
3125
        """
2297.1.3 by Martin Pool
PullResult can pretend to be an int for api compatibility with old .pull()
3126
        return self.new_revno - self.old_revno
2297.1.1 by Martin Pool
Pull now returns a PullResult rather than just an integer.
3127
2220.2.37 by Martin Pool
Report conflicting tags from push.
3128
    def report(self, to_file):
6112.4.5 by Jelmer Vernooij
Add note about bzr pull / bzr push output inconsistency.
3129
        # TODO: This function gets passed a to_file, but then
3130
        # ignores it and calls note() instead. This is also
3131
        # inconsistent with PullResult(), which writes to stdout.
3132
        # -- JRV20110901, bug #838853
6112.4.3 by Jelmer Vernooij
Fix push tests.
3133
        tag_conflicts = getattr(self, "tag_conflicts", None)
3134
        tag_updates = getattr(self, "tag_updates", None)
6112.4.2 by Jelmer Vernooij
Fix tag tests.
3135
        if not is_quiet():
3136
            if self.old_revid != self.new_revid:
6112.4.3 by Jelmer Vernooij
Fix push tests.
3137
                note('Pushed up to revision %d.' % self.new_revno)
3138
            if tag_updates:
3139
                note('%d tag(s) updated.' % len(tag_updates))
3140
            if self.old_revid == self.new_revid and not tag_updates:
3141
                if not tag_conflicts:
3142
                    note('No new revisions or tags to push.')
6112.4.2 by Jelmer Vernooij
Fix tag tests.
3143
                else:
6112.4.3 by Jelmer Vernooij
Fix push tests.
3144
                    note('No new revisions to push.')
2220.2.37 by Martin Pool
Report conflicting tags from push.
3145
        self._show_tag_conficts(to_file)
3146
2297.1.1 by Martin Pool
Pull now returns a PullResult rather than just an integer.
3147
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
3148
class BranchCheckResult(object):
3149
    """Results of checking branch consistency.
3150
3151
    :see: Branch.check
3152
    """
3153
3154
    def __init__(self, branch):
3155
        self.branch = branch
4332.3.3 by Robert Collins
Alter Branch.check to log errors rather than raising.
3156
        self.errors = []
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
3157
3158
    def report_results(self, verbose):
3159
        """Report the check results via trace.note.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3160
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
3161
        :param verbose: Requests more detailed display of what was checked,
3162
            if any.
3163
        """
5158.6.3 by Martin Pool
Update some Branch calls to use ControlComponent style.
3164
        note('checked branch %s format %s', self.branch.user_url,
4332.3.3 by Robert Collins
Alter Branch.check to log errors rather than raising.
3165
            self.branch._format)
3166
        for error in self.errors:
3167
            note('found error:%s', error)
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
3168
3169
2230.3.29 by Aaron Bentley
Implement conversion to branch 6
3170
class Converter5to6(object):
3171
    """Perform an in-place upgrade of format 5 to format 6"""
3172
3173
    def convert(self, branch):
3174
        # Data for 5 and 6 can peacefully coexist.
3175
        format = BzrBranchFormat6()
3176
        new_branch = format.open(branch.bzrdir, _found=True)
3177
3178
        # Copy source data into target
3331.1.15 by Andrew Bennetts
Use _write_last_revision_info rather than set_last_revision_info in Converter5to6, because we just want to write the last-revision file, not trigger hooks with half-converted branches.
3179
        new_branch._write_last_revision_info(*branch.last_revision_info())
2230.3.29 by Aaron Bentley
Implement conversion to branch 6
3180
        new_branch.set_parent(branch.get_parent())
3181
        new_branch.set_bound_location(branch.get_bound_location())
3182
        new_branch.set_push_location(branch.get_push_location())
3183
2220.2.43 by Martin Pool
Should clear tag file when upgrading format 5 to 6 to prevent warning
3184
        # New branch has no tags by default
3185
        new_branch.tags._set_tag_dict({})
3186
2230.3.29 by Aaron Bentley
Implement conversion to branch 6
3187
        # Copying done; now update target format
3407.2.5 by Martin Pool
Deprecate LockableFiles.put_utf8
3188
        new_branch._transport.put_bytes('format',
3189
            format.get_format_string(),
3407.2.18 by Martin Pool
BzrDir takes responsibility for default file/dir modes
3190
            mode=new_branch.bzrdir._get_file_mode())
2230.3.29 by Aaron Bentley
Implement conversion to branch 6
3191
3192
        # Clean up old files
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
3193
        new_branch._transport.delete('revision-history')
2230.3.29 by Aaron Bentley
Implement conversion to branch 6
3194
        try:
3195
            branch.set_parent(None)
3236.1.2 by Michael Hudson
clean up branch.py imports
3196
        except errors.NoSuchFile:
2230.3.29 by Aaron Bentley
Implement conversion to branch 6
3197
            pass
3198
        branch.set_bound_location(None)
3221.11.4 by Robert Collins
Add a converter for format 7 branches.
3199
3200
3201
class Converter6to7(object):
3202
    """Perform an in-place upgrade of format 6 to format 7"""
3203
3204
    def convert(self, branch):
3221.11.5 by Robert Collins
Correctly handle multi-step branch upgrades.
3205
        format = BzrBranchFormat7()
3221.18.2 by Ian Clatworthy
store stacked-on location in branch.conf
3206
        branch._set_config_location('stacked_on_location', '')
3221.11.4 by Robert Collins
Add a converter for format 7 branches.
3207
        # update target format
3221.13.5 by Ian Clatworthy
fix LockableFiles deprecations
3208
        branch._transport.put_bytes('format', format.get_format_string())
3758.1.1 by Andrew Bennetts
Fix #230902 by being more careful not to squash a pre-existing exception when calling foo.unlock()
3209
3210
4273.1.13 by Aaron Bentley
Implement upgrade from branch format 7 to 8.
3211
class Converter7to8(object):
5906.1.1 by Jelmer Vernooij
Remove unused constants, fix docstring.
3212
    """Perform an in-place upgrade of format 7 to format 8"""
4273.1.13 by Aaron Bentley
Implement upgrade from branch format 7 to 8.
3213
3214
    def convert(self, branch):
3215
        format = BzrBranchFormat8()
3216
        branch._transport.put_bytes('references', '')
3217
        # update target format
3218
        branch._transport.put_bytes('format', format.get_format_string())
3219
3758.1.1 by Andrew Bennetts
Fix #230902 by being more careful not to squash a pre-existing exception when calling foo.unlock()
3220
4000.5.1 by Jelmer Vernooij
Add InterBranch.
3221
class InterBranch(InterObject):
3222
    """This class represents operations taking place between two branches.
3223
3224
    Its instances have methods like pull() and push() and contain
3225
    references to the source and target repositories these operations
3226
    can be carried out on.
3227
    """
3228
3229
    _optimisers = []
3978.3.11 by Jelmer Vernooij
Move InterBranchBzrDir to bzrlib.push.
3230
    """The available optimised InterBranch types."""
3231
5297.2.1 by Robert Collins
``bzrlib.branch.InterBranch._get_branch_formats_to_test`` now returns
3232
    @classmethod
3233
    def _get_branch_formats_to_test(klass):
3234
        """Return an iterable of format tuples for testing.
3235
        
3236
        :return: An iterable of (from_format, to_format) to use when testing
3237
            this InterBranch class. Each InterBranch class should define this
3238
            method itself.
3239
        """
3240
        raise NotImplementedError(klass._get_branch_formats_to_test)
3978.3.11 by Jelmer Vernooij
Move InterBranchBzrDir to bzrlib.push.
3241
5297.2.2 by Robert Collins
Fixup tests in per_interbranch not being strict about making the from format the configured one.
3242
    @needs_write_lock
4000.5.9 by Jelmer Vernooij
Add InterBranch.pull().
3243
    def pull(self, overwrite=False, stop_revision=None,
4000.5.21 by Jelmer Vernooij
Merge bzr.dev.
3244
             possible_transports=None, local=False):
4000.5.10 by Jelmer Vernooij
Fix comment for InterBranch.pull.
3245
        """Mirror source into target branch.
3246
3247
        The target branch is considered to be 'local', having low latency.
3248
3249
        :returns: PullResult instance
4000.5.9 by Jelmer Vernooij
Add InterBranch.pull().
3250
        """
3251
        raise NotImplementedError(self.pull)
3252
5297.2.2 by Robert Collins
Fixup tests in per_interbranch not being strict about making the from format the configured one.
3253
    @needs_write_lock
5853.2.2 by Jelmer Vernooij
Make lossy_push an argument to InterBranch.push.
3254
    def push(self, overwrite=False, stop_revision=None, lossy=False,
4211.1.3 by Jelmer Vernooij
Fix trailing whitespace, add prototype for InterBranch.push().
3255
             _override_hook_source_branch=None):
3256
        """Mirror the source branch into the target branch.
3257
3258
        The source branch is considered to be 'local', having low latency.
3259
        """
3260
        raise NotImplementedError(self.push)
3261
5358.1.1 by Jelmer Vernooij
Add stub for InterBranch.copy_content_into.
3262
    @needs_write_lock
3263
    def copy_content_into(self, revision_id=None):
3264
        """Copy the content of source into target
3265
3266
        revision_id: if not None, the revision history in the new branch will
3267
                     be truncated to end with revision_id.
3268
        """
3269
        raise NotImplementedError(self.copy_content_into)
3270
5741.1.1 by Jelmer Vernooij
Move fetch implementation to InterBranch.
3271
    @needs_write_lock
5852.1.1 by Jelmer Vernooij
Add limit argument to Branch.fetch.
3272
    def fetch(self, stop_revision=None, limit=None):
5741.1.1 by Jelmer Vernooij
Move fetch implementation to InterBranch.
3273
        """Fetch revisions.
3274
3275
        :param stop_revision: Last revision to fetch
5852.1.1 by Jelmer Vernooij
Add limit argument to Branch.fetch.
3276
        :param limit: Optional rough limit of revisions to fetch
5741.1.1 by Jelmer Vernooij
Move fetch implementation to InterBranch.
3277
        """
3278
        raise NotImplementedError(self.fetch)
3279
3978.3.11 by Jelmer Vernooij
Move InterBranchBzrDir to bzrlib.push.
3280
3281
class GenericInterBranch(InterBranch):
5284.4.1 by Robert Collins
* Fetching was slightly confused about the best code to use and was
3282
    """InterBranch implementation that uses public Branch functions."""
3283
3284
    @classmethod
3285
    def is_compatible(klass, source, target):
3286
        # GenericBranch uses the public API, so always compatible
3287
        return True
4000.5.1 by Jelmer Vernooij
Add InterBranch.
3288
5297.2.1 by Robert Collins
``bzrlib.branch.InterBranch._get_branch_formats_to_test`` now returns
3289
    @classmethod
3290
    def _get_branch_formats_to_test(klass):
5662.2.2 by Jelmer Vernooij
Move most format registration functions to BranchFormatRegistry.
3291
        return [(format_registry.get_default(), format_registry.get_default())]
4000.5.3 by Jelmer Vernooij
Add tests for InterBranch.
3292
5284.4.1 by Robert Collins
* Fetching was slightly confused about the best code to use and was
3293
    @classmethod
3294
    def unwrap_format(klass, format):
3295
        if isinstance(format, remote.RemoteBranchFormat):
3296
            format._ensure_real()
3297
            return format._custom_format
5050.53.4 by Andrew Bennetts
Don't propagate tags to the master branch during cmd_merge.
3298
        return format
5284.4.1 by Robert Collins
* Fetching was slightly confused about the best code to use and was
3299
5284.4.2 by Robert Collins
* ``Branch.copy_content_into`` is now a convenience method dispatching to
3300
    @needs_write_lock
3301
    def copy_content_into(self, revision_id=None):
3302
        """Copy the content of source into target
3303
3304
        revision_id: if not None, the revision history in the new branch will
3305
                     be truncated to end with revision_id.
3306
        """
3307
        self.source.update_references(self.target)
3308
        self.source._synchronize_history(self.target, revision_id)
3309
        try:
3310
            parent = self.source.get_parent()
3311
        except errors.InaccessibleParent, e:
3312
            mutter('parent was not accessible to copy: %s', e)
3313
        else:
3314
            if parent:
3315
                self.target.set_parent(parent)
3316
        if self.source._push_should_merge_tags():
5284.4.3 by Robert Collins
Fix missed self.source change in copy_content_into.
3317
            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
3318
3319
    @needs_write_lock
5852.1.1 by Jelmer Vernooij
Add limit argument to Branch.fetch.
3320
    def fetch(self, stop_revision=None, limit=None):
5741.1.1 by Jelmer Vernooij
Move fetch implementation to InterBranch.
3321
        if self.target.base == self.source.base:
3322
            return (0, [])
3323
        self.source.lock_read()
3324
        try:
5741.1.6 by Jelmer Vernooij
Add stop_revision argument to Branch.heads_to_fetch.
3325
            fetch_spec_factory = fetch.FetchSpecFactory()
3326
            fetch_spec_factory.source_branch = self.source
3327
            fetch_spec_factory.source_branch_stop_revision_id = stop_revision
3328
            fetch_spec_factory.source_repo = self.source.repository
3329
            fetch_spec_factory.target_repo = self.target.repository
3330
            fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
5852.1.5 by Andrew Bennetts, Jelmer Vernooij
Support limit= for fetching between Bazaar branches.
3331
            fetch_spec_factory.limit = limit
5741.1.6 by Jelmer Vernooij
Add stop_revision argument to Branch.heads_to_fetch.
3332
            fetch_spec = fetch_spec_factory.make_fetch_spec()
5741.1.1 by Jelmer Vernooij
Move fetch implementation to InterBranch.
3333
            return self.target.repository.fetch(self.source.repository,
5741.1.4 by Jelmer Vernooij
Change Branch.fetch to take fetch_tags argument rather than fetch_spec.
3334
                fetch_spec=fetch_spec)
5741.1.1 by Jelmer Vernooij
Move fetch implementation to InterBranch.
3335
        finally:
3336
            self.source.unlock()
3337
5809.2.1 by Jelmer Vernooij
Deprecate Branch.update_revisions.
3338
    @needs_write_lock
3339
    def _update_revisions(self, stop_revision=None, overwrite=False,
5809.2.4 by Jelmer Vernooij
remove unused argument.
3340
            graph=None):
5284.4.2 by Robert Collins
* ``Branch.copy_content_into`` is now a convenience method dispatching to
3341
        other_revno, other_last_revision = self.source.last_revision_info()
3342
        stop_revno = None # unknown
3343
        if stop_revision is None:
3344
            stop_revision = other_last_revision
3345
            if _mod_revision.is_null(stop_revision):
3346
                # if there are no commits, we're done.
3347
                return
3348
            stop_revno = other_revno
4000.5.1 by Jelmer Vernooij
Add InterBranch.
3349
5284.4.2 by Robert Collins
* ``Branch.copy_content_into`` is now a convenience method dispatching to
3350
        # what's the current last revision, before we fetch [and change it
3351
        # possibly]
3352
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
3353
        # we fetch here so that we don't process data twice in the common
3354
        # case of having something to pull, and so that the check for
3355
        # already merged can operate on the just fetched graph, which will
3356
        # be cached in memory.
5741.1.8 by Jelmer Vernooij
Remove fetch_tags argument.
3357
        self.fetch(stop_revision=stop_revision)
5284.4.2 by Robert Collins
* ``Branch.copy_content_into`` is now a convenience method dispatching to
3358
        # Check to see if one is an ancestor of the other
3359
        if not overwrite:
3360
            if graph is None:
3361
                graph = self.target.repository.get_graph()
3362
            if self.target._check_if_descendant_or_diverged(
3363
                    stop_revision, last_rev, graph, self.source):
3364
                # stop_revision is a descendant of last_rev, but we aren't
3365
                # overwriting, so we're done.
3366
                return
3367
        if stop_revno is None:
3368
            if graph is None:
3369
                graph = self.target.repository.get_graph()
3370
            this_revno, this_last_revision = \
3371
                    self.target.last_revision_info()
3372
            stop_revno = graph.find_distance_to_null(stop_revision,
3373
                            [(other_last_revision, other_revno),
3374
                             (this_last_revision, this_revno)])
3375
        self.target.set_last_revision_info(stop_revno, stop_revision)
4000.5.1 by Jelmer Vernooij
Add InterBranch.
3376
5297.2.2 by Robert Collins
Fixup tests in per_interbranch not being strict about making the from format the configured one.
3377
    @needs_write_lock
4000.5.9 by Jelmer Vernooij
Add InterBranch.pull().
3378
    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
3379
             possible_transports=None, run_hooks=True,
4000.5.21 by Jelmer Vernooij
Merge bzr.dev.
3380
             _override_hook_target=None, local=False):
5284.4.1 by Robert Collins
* Fetching was slightly confused about the best code to use and was
3381
        """Pull from source into self, updating my master if any.
4000.5.9 by Jelmer Vernooij
Add InterBranch.pull().
3382
3383
        :param run_hooks: Private parameter - if false, this branch
3384
            is being called because it's the master of the primary branch,
3385
            so it should not run its hooks.
3386
        """
5284.4.1 by Robert Collins
* Fetching was slightly confused about the best code to use and was
3387
        bound_location = self.target.get_bound_location()
3388
        if local and not bound_location:
4000.5.21 by Jelmer Vernooij
Merge bzr.dev.
3389
            raise errors.LocalRequiresBoundBranch()
5284.4.1 by Robert Collins
* Fetching was slightly confused about the best code to use and was
3390
        master_branch = None
5609.50.1 by Vincent Ladeuil
Be more tolerant about ``bound_location`` from config files
3391
        source_is_master = False
3392
        if bound_location:
5609.50.2 by Vincent Ladeuil
Fix typos caught by Jonathan.
3393
            # bound_location comes from a config file, some care has to be
3394
            # taken to relate it to source.user_url
5609.50.1 by Vincent Ladeuil
Be more tolerant about ``bound_location`` from config files
3395
            normalized = urlutils.normalize_url(bound_location)
3396
            try:
3397
                relpath = self.source.user_transport.relpath(normalized)
3398
                source_is_master = (relpath == '')
3399
            except (errors.PathNotChild, errors.InvalidURL):
3400
                source_is_master = False
5582.5.1 by John Arbash Meinel
Fix bug 701212. Don't set the tags for a master branch during update.
3401
        if not local and bound_location and not source_is_master:
5284.4.1 by Robert Collins
* Fetching was slightly confused about the best code to use and was
3402
            # not pulling from master, so we need to update master.
3403
            master_branch = self.target.get_master_branch(possible_transports)
3404
            master_branch.lock_write()
4000.5.9 by Jelmer Vernooij
Add InterBranch.pull().
3405
        try:
5284.4.1 by Robert Collins
* Fetching was slightly confused about the best code to use and was
3406
            if master_branch:
3407
                # pull from source into master.
3408
                master_branch.pull(self.source, overwrite, stop_revision,
3409
                    run_hooks=False)
3410
            return self._pull(overwrite,
3411
                stop_revision, _hook_master=master_branch,
3412
                run_hooks=run_hooks,
5582.5.1 by John Arbash Meinel
Fix bug 701212. Don't set the tags for a master branch during update.
3413
                _override_hook_target=_override_hook_target,
3414
                merge_tags_to_master=not source_is_master)
4000.5.9 by Jelmer Vernooij
Add InterBranch.pull().
3415
        finally:
5284.4.1 by Robert Collins
* Fetching was slightly confused about the best code to use and was
3416
            if master_branch:
3417
                master_branch.unlock()
4000.5.9 by Jelmer Vernooij
Add InterBranch.pull().
3418
5853.2.2 by Jelmer Vernooij
Make lossy_push an argument to InterBranch.push.
3419
    def push(self, overwrite=False, stop_revision=None, lossy=False,
4211.1.1 by Jelmer Vernooij
Move Branch.push to InterBranch.push.
3420
             _override_hook_source_branch=None):
3421
        """See InterBranch.push.
3422
3423
        This is the basic concrete implementation of push()
3424
5891.1.2 by Andrew Bennetts
Fix a bunch of docstring formatting nits, making pydoctor a bit happier.
3425
        :param _override_hook_source_branch: If specified, run the hooks
3426
            passing this Branch as the source, rather than self.  This is for
3427
            use of RemoteBranch, where push is delegated to the underlying
3428
            vfs-based Branch.
4211.1.1 by Jelmer Vernooij
Move Branch.push to InterBranch.push.
3429
        """
5853.2.2 by Jelmer Vernooij
Make lossy_push an argument to InterBranch.push.
3430
        if lossy:
3431
            raise errors.LossyPushToSameVCS(self.source, self.target)
4211.1.1 by Jelmer Vernooij
Move Branch.push to InterBranch.push.
3432
        # TODO: Public option to disable running hooks - should be trivial but
3433
        # needs tests.
5915.1.1 by Andrew Bennetts
Removed bzrlib.branch._run_with_write_locked_target. Use bzrlib.cleanup instead.
3434
3435
        op = cleanup.OperationWithCleanups(self._push_with_bound_branches)
3436
        op.add_cleanup(self.source.lock_read().unlock)
3437
        op.add_cleanup(self.target.lock_write().unlock)
3438
        return op.run(overwrite, stop_revision,
3439
            _override_hook_source_branch=_override_hook_source_branch)
4211.1.1 by Jelmer Vernooij
Move Branch.push to InterBranch.push.
3440
5809.2.3 by Jelmer Vernooij
Kill update_revisions private implementation.
3441
    def _basic_push(self, overwrite, stop_revision):
3442
        """Basic implementation of push without bound branches or hooks.
3443
3444
        Must be called with source read locked and target write locked.
3445
        """
3446
        result = BranchPushResult()
3447
        result.source_branch = self.source
3448
        result.target_branch = self.target
3449
        result.old_revno, result.old_revid = self.target.last_revision_info()
3450
        self.source.update_references(self.target)
3451
        if result.old_revid != stop_revision:
3452
            # We assume that during 'push' this repository is closer than
3453
            # the target.
3454
            graph = self.source.repository.get_graph(self.target.repository)
3455
            self._update_revisions(stop_revision, overwrite=overwrite,
3456
                    graph=graph)
3457
        if self.source._push_should_merge_tags():
6112.4.4 by Jelmer Vernooij
Fix long lines.
3458
            result.tag_updates, result.tag_conflicts = (
3459
                self.source.tags.merge_to(self.target.tags, overwrite))
5809.2.3 by Jelmer Vernooij
Kill update_revisions private implementation.
3460
        result.new_revno, result.new_revid = self.target.last_revision_info()
3461
        return result
3462
5915.1.1 by Andrew Bennetts
Removed bzrlib.branch._run_with_write_locked_target. Use bzrlib.cleanup instead.
3463
    def _push_with_bound_branches(self, operation, overwrite, stop_revision,
4211.1.1 by Jelmer Vernooij
Move Branch.push to InterBranch.push.
3464
            _override_hook_source_branch=None):
3465
        """Push from source into target, and into target's master if any.
3466
        """
3467
        def _run_hooks():
3468
            if _override_hook_source_branch:
3469
                result.source_branch = _override_hook_source_branch
3470
            for hook in Branch.hooks['post_push']:
3471
                hook(result)
3472
3473
        bound_location = self.target.get_bound_location()
3474
        if bound_location and self.target.base != bound_location:
3475
            # there is a master branch.
3476
            #
3477
            # XXX: Why the second check?  Is it even supported for a branch to
3478
            # be bound to itself? -- mbp 20070507
3479
            master_branch = self.target.get_master_branch()
3480
            master_branch.lock_write()
5915.1.1 by Andrew Bennetts
Removed bzrlib.branch._run_with_write_locked_target. Use bzrlib.cleanup instead.
3481
            operation.add_cleanup(master_branch.unlock)
3482
            # push into the master from the source branch.
3483
            master_inter = InterBranch.get(self.source, master_branch)
3484
            master_inter._basic_push(overwrite, stop_revision)
3485
            # and push into the target branch from the source. Note that
3486
            # we push from the source branch again, because it's considered
3487
            # the highest bandwidth repository.
3488
            result = self._basic_push(overwrite, stop_revision)
3489
            result.master_branch = master_branch
3490
            result.local_branch = self.target
4211.1.1 by Jelmer Vernooij
Move Branch.push to InterBranch.push.
3491
        else:
5915.1.1 by Andrew Bennetts
Removed bzrlib.branch._run_with_write_locked_target. Use bzrlib.cleanup instead.
3492
            master_branch = None
4211.1.1 by Jelmer Vernooij
Move Branch.push to InterBranch.push.
3493
            # no master branch
5809.2.3 by Jelmer Vernooij
Kill update_revisions private implementation.
3494
            result = self._basic_push(overwrite, stop_revision)
4211.1.1 by Jelmer Vernooij
Move Branch.push to InterBranch.push.
3495
            # TODO: Why set master_branch and local_branch if there's no
3496
            # binding?  Maybe cleaner to just leave them unset? -- mbp
3497
            # 20070504
3498
            result.master_branch = self.target
3499
            result.local_branch = None
5915.1.1 by Andrew Bennetts
Removed bzrlib.branch._run_with_write_locked_target. Use bzrlib.cleanup instead.
3500
        _run_hooks()
3501
        return result
4211.1.1 by Jelmer Vernooij
Move Branch.push to InterBranch.push.
3502
5284.4.1 by Robert Collins
* Fetching was slightly confused about the best code to use and was
3503
    def _pull(self, overwrite=False, stop_revision=None,
3504
             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.
3505
             _override_hook_target=None, local=False,
3506
             merge_tags_to_master=True):
5284.4.1 by Robert Collins
* Fetching was slightly confused about the best code to use and was
3507
        """See Branch.pull.
3508
3509
        This function is the core worker, used by GenericInterBranch.pull to
3510
        avoid duplication when pulling source->master and source->local.
3511
3512
        :param _hook_master: Private parameter - set the branch to
3513
            be supplied as the master to pull hooks.
4000.5.9 by Jelmer Vernooij
Add InterBranch.pull().
3514
        :param run_hooks: Private parameter - if false, this branch
3515
            is being called because it's the master of the primary branch,
3516
            so it should not run its hooks.
5662.2.6 by Jelmer Vernooij
add more tests.
3517
            is being called because it's the master of the primary branch,
3518
            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
3519
        :param _override_hook_target: Private parameter - set the branch to be
3520
            supplied as the target_branch to pull hooks.
3521
        :param local: Only update the local branch, and not the bound branch.
4000.5.9 by Jelmer Vernooij
Add InterBranch.pull().
3522
        """
5284.4.1 by Robert Collins
* Fetching was slightly confused about the best code to use and was
3523
        # This type of branch can't be bound.
3524
        if local:
4000.5.21 by Jelmer Vernooij
Merge bzr.dev.
3525
            raise errors.LocalRequiresBoundBranch()
5284.4.1 by Robert Collins
* Fetching was slightly confused about the best code to use and was
3526
        result = PullResult()
3527
        result.source_branch = self.source
3528
        if _override_hook_target is None:
3529
            result.target_branch = self.target
3530
        else:
3531
            result.target_branch = _override_hook_target
3532
        self.source.lock_read()
4000.5.9 by Jelmer Vernooij
Add InterBranch.pull().
3533
        try:
5284.4.1 by Robert Collins
* Fetching was slightly confused about the best code to use and was
3534
            # We assume that during 'pull' the target repository is closer than
3535
            # the source one.
3536
            self.source.update_references(self.target)
3537
            graph = self.target.repository.get_graph(self.source.repository)
3538
            # TODO: Branch formats should have a flag that indicates 
3539
            # that revno's are expensive, and pull() should honor that flag.
3540
            # -- JRV20090506
3541
            result.old_revno, result.old_revid = \
3542
                self.target.last_revision_info()
5809.2.3 by Jelmer Vernooij
Kill update_revisions private implementation.
3543
            self._update_revisions(stop_revision, overwrite=overwrite,
5809.2.1 by Jelmer Vernooij
Deprecate Branch.update_revisions.
3544
                graph=graph)
5284.4.1 by Robert Collins
* Fetching was slightly confused about the best code to use and was
3545
            # TODO: The old revid should be specified when merging tags, 
3546
            # so a tags implementation that versions tags can only 
3547
            # pull in the most recent changes. -- JRV20090506
6112.4.4 by Jelmer Vernooij
Fix long lines.
3548
            result.tag_updates, result.tag_conflicts = (
3549
                self.source.tags.merge_to(self.target.tags, overwrite,
3550
                    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
3551
            result.new_revno, result.new_revid = self.target.last_revision_info()
3552
            if _hook_master:
3553
                result.master_branch = _hook_master
3554
                result.local_branch = result.target_branch
3555
            else:
3556
                result.master_branch = result.target_branch
3557
                result.local_branch = None
3558
            if run_hooks:
3559
                for hook in Branch.hooks['post_pull']:
3560
                    hook(result)
4000.5.9 by Jelmer Vernooij
Add InterBranch.pull().
3561
        finally:
5284.4.1 by Robert Collins
* Fetching was slightly confused about the best code to use and was
3562
            self.source.unlock()
3563
        return result
4000.5.9 by Jelmer Vernooij
Add InterBranch.pull().
3564
3565
4000.5.1 by Jelmer Vernooij
Add InterBranch.
3566
InterBranch.register_optimiser(GenericInterBranch)