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