/brz/remove-bazaar

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