~bzr-pqm/bzr/bzr.dev

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