~bzr-pqm/bzr/bzr.dev

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