/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
6404.6.1 by Vincent Ladeuil
Tests passing for a first rough version of a cached branch config store. The changes here are too invasive and several parallel proposals have been made.
1
# Copyright (C) 2010, 2011, 2012 Canonical Ltd
5363.2.1 by Jelmer Vernooij
Add controldir file.
2
#
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.
7
#
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.
12
#
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
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
17
"""ControlDir is the basic control directory class.
5363.2.1 by Jelmer Vernooij
Add controldir file.
18
19
The ControlDir class is the base for the control directory used
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
20
by all bzr and foreign formats. For the ".bzr" implementation,
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
21
see breezy.bzrdir.BzrDir.
5363.2.21 by Jelmer Vernooij
Update comments.
22
5363.2.1 by Jelmer Vernooij
Add controldir file.
23
"""
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
24
6379.6.7 by Jelmer Vernooij
Move importing from future until after doc string, otherwise the doc string will disappear.
25
from __future__ import absolute_import
26
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
27
from .lazy_import import lazy_import
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
28
lazy_import(globals(), """
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
29
import textwrap
30
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
31
from breezy import (
6826 by Jelmer Vernooij
Merge lp:~jelmer/brz/move-acquisition.
32
    branch as _mod_branch,
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
33
    hooks,
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
34
    revision as _mod_revision,
5609.9.1 by Martin
Blindly change all users of get_transport to address the function via the transport module
35
    transport as _mod_transport,
6207.3.7 by Jelmer Vernooij
Fix import of trace.note and gettext.
36
    trace,
5717.1.1 by Jelmer Vernooij
Support overriding check_supported.
37
    ui,
5268.7.26 by Jelmer Vernooij
Unescape branch name.
38
    urlutils,
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
39
    )
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
40
from breezy.transport import local
41
from breezy.push import (
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
42
    PushResult,
43
    )
44
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
45
from breezy.i18n import gettext
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
46
""")
47
6734.1.13 by Jelmer Vernooij
Move MustHaveWorkingTree.
48
from . import (
49
    errors,
50
    registry,
51
    )
52
53
54
class MustHaveWorkingTree(errors.BzrError):
55
6734.1.22 by Jelmer Vernooij
review comments.
56
    _fmt = "Branching '%(url)s'(%(format)s) must create a working tree."
6734.1.13 by Jelmer Vernooij
Move MustHaveWorkingTree.
57
58
    def __init__(self, format, url):
59
        errors.BzrError.__init__(self, format=format, url=url)
5536.1.8 by Andrew Bennetts
Garden the imports in controldir.py.
60
5363.2.10 by Jelmer Vernooij
base ControlDir on ControlComponent.
61
6929.8.2 by Jelmer Vernooij
Fix new switch tests.
62
class BranchReferenceLoop(errors.BzrError):
63
64
    _fmt = "Can not create branch reference that points at branch itself."
65
66
    def __init__(self, branch):
67
        errors.BzrError.__init__(self, branch=branch)
68
69
5363.2.10 by Jelmer Vernooij
base ControlDir on ControlComponent.
70
class ControlComponent(object):
71
    """Abstract base class for control directory components.
72
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
73
    This provides interfaces that are common across controldirs,
5363.2.10 by Jelmer Vernooij
base ControlDir on ControlComponent.
74
    repositories, branches, and workingtree control directories.
75
76
    They all expose two urls and transports: the *user* URL is the
77
    one that stops above the control directory (eg .bzr) and that
78
    should normally be used in messages, and the *control* URL is
79
    under that in eg .bzr/checkout and is used to read the control
80
    files.
81
82
    This can be used as a mixin and is intended to fit with
83
    foreign formats.
84
    """
85
86
    @property
87
    def control_transport(self):
88
        raise NotImplementedError
89
90
    @property
91
    def control_url(self):
92
        return self.control_transport.base
93
94
    @property
95
    def user_transport(self):
96
        raise NotImplementedError
97
98
    @property
99
    def user_url(self):
100
        return self.user_transport.base
101
102
103
class ControlDir(ControlComponent):
5363.2.21 by Jelmer Vernooij
Update comments.
104
    """A control directory.
105
106
    While this represents a generic control directory, there are a few
107
    features that are present in this interface that are currently only
108
    supported by one of its implementations, BzrDir.
109
110
    These features (bound branches, stacked branches) are currently only
111
    supported by Bazaar, but could be supported by other version control
112
    systems as well. Implementations are required to raise the appropriate
113
    exceptions when an operation is requested that is not supported.
114
115
    This also makes life easier for API users who can rely on the
116
    implementation always allowing a particular feature to be requested but
117
    raising an exception when it is not supported, rather than requiring the
118
    API users to check for magic attributes to see what features are supported.
119
    """
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
120
121
    def can_convert_format(self):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
122
        """Return true if this controldir is one whose format we can convert
123
        from."""
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
124
        return True
125
126
    def list_branches(self):
127
        """Return a sequence of all branches local to this control directory.
128
129
        """
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
130
        return list(self.get_branches().values())
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
131
7490.13.2 by Jelmer Vernooij
Fix reference handling.
132
    def branch_names(self):
133
        """List all branch names in this control directory.
134
135
        :return: List of branch names
136
        """
137
        try:
138
            self.get_branch_reference()
139
        except (errors.NotBranchError, errors.NoRepositoryPresent):
140
            return []
141
        else:
142
            return [""]
143
6282.5.4 by Neil Martinsen-Burrell
add get_branches method to return a dictionary of names and branches
144
    def get_branches(self):
6282.5.11 by Jelmer Vernooij
Review tweaks.
145
        """Get all branches in this control directory, as a dictionary.
7143.15.2 by Jelmer Vernooij
Run autopep8.
146
6282.5.11 by Jelmer Vernooij
Review tweaks.
147
        :return: Dictionary mapping branch names to instances.
148
        """
6282.5.9 by Neil Martinsen-Burrell
implement list_branches in terms of get_branches
149
        try:
7143.15.2 by Jelmer Vernooij
Run autopep8.
150
            return {"": self.open_branch()}
6282.5.9 by Neil Martinsen-Burrell
implement list_branches in terms of get_branches
151
        except (errors.NotBranchError, errors.NoRepositoryPresent):
7143.15.2 by Jelmer Vernooij
Run autopep8.
152
            return {}
6282.5.4 by Neil Martinsen-Burrell
add get_branches method to return a dictionary of names and branches
153
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
154
    def is_control_filename(self, filename):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
155
        """True if filename is the name of a path which is reserved for
156
        controldirs.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
157
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
158
        :param filename: A filename within the root transport of this
159
            controldir.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
160
161
        This is true IF and ONLY IF the filename is part of the namespace reserved
162
        for bzr control dirs. Currently this is the '.bzr' directory in the root
163
        of the root_transport. it is expected that plugins will need to extend
164
        this in the future - for instance to make bzr talk with svn working
165
        trees.
166
        """
7311.2.2 by Jelmer Vernooij
Add ControlDirFormat.is_control_filename.
167
        return self._format.is_control_filename(filename)
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
168
169
    def needs_format_conversion(self, format=None):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
170
        """Return true if this controldir needs convert_format run on it.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
171
172
        For instance, if the repository format is out of date but the
173
        branch and working tree are not, this should return True.
174
175
        :param format: Optional parameter indicating a specific desired
176
                       format we plan to arrive at.
177
        """
178
        raise NotImplementedError(self.needs_format_conversion)
179
5688.1.1 by Jelmer Vernooij
Add a stub for ControlDir.create_repository.
180
    def create_repository(self, shared=False):
181
        """Create a new repository in this control directory.
182
183
        :param shared: If a shared repository should be created
184
        :return: The newly created repository
185
        """
186
        raise NotImplementedError(self.create_repository)
187
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
188
    def destroy_repository(self):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
189
        """Destroy the repository in this ControlDir."""
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
190
        raise NotImplementedError(self.destroy_repository)
191
6123.9.12 by Jelmer Vernooij
Add append_revisions_only argument to BranchFormat.initialize.
192
    def create_branch(self, name=None, repository=None,
193
                      append_revisions_only=None):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
194
        """Create a branch in this ControlDir.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
195
196
        :param name: Name of the colocated branch to create, None for
6437.22.3 by Jelmer Vernooij
Fix docstrings.
197
            the user selected branch or "" for the active branch.
6123.9.12 by Jelmer Vernooij
Add append_revisions_only argument to BranchFormat.initialize.
198
        :param append_revisions_only: Whether this branch should only allow
199
            appending new revisions to its history.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
200
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
201
        The controldirs format will control what branch format is created.
202
        For more control see BranchFormatXX.create(a_controldir).
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
203
        """
204
        raise NotImplementedError(self.create_branch)
205
206
    def destroy_branch(self, name=None):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
207
        """Destroy a branch in this ControlDir.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
208
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
209
        :param name: Name of the branch to destroy, None for the
6437.22.3 by Jelmer Vernooij
Fix docstrings.
210
            user selected branch or "" for the active branch.
6437.22.1 by Jelmer Vernooij
Except ControlDir.destroy_branch to raise NotBranchError if the branch did not exist.
211
        :raise NotBranchError: When the branch does not exist
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
212
        """
213
        raise NotImplementedError(self.destroy_branch)
214
215
    def create_workingtree(self, revision_id=None, from_branch=None,
7143.15.2 by Jelmer Vernooij
Run autopep8.
216
                           accelerator_tree=None, hardlink=False):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
217
        """Create a working tree at this ControlDir.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
218
219
        :param revision_id: create it as of this revision id.
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
220
        :param from_branch: override controldir branch
5363.2.17 by Jelmer Vernooij
merge bzr.dev.
221
            (for lightweight checkouts)
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
222
        :param accelerator_tree: A tree which can be used for retrieving file
223
            contents more quickly than the revision tree, i.e. a workingtree.
224
            The revision tree will be used for cases where accelerator_tree's
225
            content is different.
226
        """
227
        raise NotImplementedError(self.create_workingtree)
228
229
    def destroy_workingtree(self):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
230
        """Destroy the working tree at this ControlDir.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
231
232
        Formats that do not support this may raise UnsupportedOperation.
233
        """
234
        raise NotImplementedError(self.destroy_workingtree)
235
236
    def destroy_workingtree_metadata(self):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
237
        """Destroy the control files for the working tree at this ControlDir.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
238
239
        The contents of working tree files are not affected.
240
        Formats that do not support this may raise UnsupportedOperation.
241
        """
242
        raise NotImplementedError(self.destroy_workingtree_metadata)
243
5268.7.27 by Jelmer Vernooij
Add stub for ControlDir.find_branch_format.
244
    def find_branch_format(self, name=None):
6207.3.3 by jelmer at samba
Fix tests and the like.
245
        """Find the branch 'format' for this controldir.
5268.7.27 by Jelmer Vernooij
Add stub for ControlDir.find_branch_format.
246
247
        This might be a synthetic object for e.g. RemoteBranch and SVN.
248
        """
249
        raise NotImplementedError(self.find_branch_format)
250
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
251
    def get_branch_reference(self, name=None):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
252
        """Return the referenced URL for the branch in this controldir.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
253
254
        :param name: Optional colocated branch name
255
        :raises NotBranchError: If there is no Branch.
256
        :raises NoColocatedBranchSupport: If a branch name was specified
257
            but colocated branches are not supported.
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
258
        :return: The URL the branch in this controldir references if it is a
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
259
            reference branch, or None for regular branches.
260
        """
261
        if name is not None:
262
            raise errors.NoColocatedBranchSupport(self)
263
        return None
264
6437.7.2 by Jelmer Vernooij
Update NEWS, tweak docstrings.
265
    def set_branch_reference(self, target_branch, name=None):
6437.7.1 by Jelmer Vernooij
Add ControlDir.set_branch_reference.
266
        """Set the referenced URL for the branch in this controldir.
267
268
        :param name: Optional colocated branch name
6437.7.2 by Jelmer Vernooij
Update NEWS, tweak docstrings.
269
        :param target_branch: Branch to reference
6437.7.1 by Jelmer Vernooij
Add ControlDir.set_branch_reference.
270
        :raises NoColocatedBranchSupport: If a branch name was specified
271
            but colocated branches are not supported.
6437.7.2 by Jelmer Vernooij
Update NEWS, tweak docstrings.
272
        :return: The referencing branch
6437.7.1 by Jelmer Vernooij
Add ControlDir.set_branch_reference.
273
        """
274
        raise NotImplementedError(self.set_branch_reference)
275
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
276
    def open_branch(self, name=None, unsupported=False,
6305.3.2 by Jelmer Vernooij
Only make a single connection.
277
                    ignore_fallbacks=False, possible_transports=None):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
278
        """Open the branch object at this ControlDir if one is present.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
279
6305.3.2 by Jelmer Vernooij
Only make a single connection.
280
        :param unsupported: if True, then no longer supported branch formats can
281
            still be opened.
282
        :param ignore_fallbacks: Whether to open fallback repositories
283
        :param possible_transports: Transports to use for opening e.g.
284
            fallback repositories.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
285
        """
286
        raise NotImplementedError(self.open_branch)
287
288
    def open_repository(self, _unsupported=False):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
289
        """Open the repository object at this ControlDir if one is present.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
290
291
        This will not follow the Branch object pointer - it's strictly a direct
292
        open facility. Most client code should use open_branch().repository to
293
        get at a repository.
294
295
        :param _unsupported: a private parameter, not part of the api.
296
        """
297
        raise NotImplementedError(self.open_repository)
298
299
    def find_repository(self):
300
        """Find the repository that should be used.
301
302
        This does not require a branch as we use it to find the repo for
303
        new branches as well as to hook existing branches up to their
304
        repository.
305
        """
306
        raise NotImplementedError(self.find_repository)
307
6402.1.1 by Jelmer Vernooij
Simplify probing.
308
    def open_workingtree(self, unsupported=False,
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
309
                         recommend_upgrade=True, from_branch=None):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
310
        """Open the workingtree object at this ControlDir if one is present.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
311
312
        :param recommend_upgrade: Optional keyword parameter, when True (the
313
            default), emit through the ui module a recommendation that the user
314
            upgrade the working tree when the workingtree being opened is old
315
            (but still fully supported).
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
316
        :param from_branch: override controldir branch (for lightweight
317
            checkouts)
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
318
        """
319
        raise NotImplementedError(self.open_workingtree)
320
321
    def has_branch(self, name=None):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
322
        """Tell if this controldir contains a branch.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
323
324
        Note: if you're going to open the branch, you should just go ahead
325
        and try, and not ask permission first.  (This method just opens the
326
        branch and discards it, and that's somewhat expensive.)
327
        """
328
        try:
6305.3.2 by Jelmer Vernooij
Only make a single connection.
329
            self.open_branch(name, ignore_fallbacks=True)
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
330
            return True
331
        except errors.NotBranchError:
332
            return False
333
5268.7.22 by Jelmer Vernooij
Add ControlDir._get_selected_branch.
334
    def _get_selected_branch(self):
335
        """Return the name of the branch selected by the user.
336
6437.22.3 by Jelmer Vernooij
Fix docstrings.
337
        :return: Name of the branch selected by the user, or "".
5268.7.22 by Jelmer Vernooij
Add ControlDir._get_selected_branch.
338
        """
5268.7.26 by Jelmer Vernooij
Unescape branch name.
339
        branch = self.root_transport.get_segment_parameters().get("branch")
6436.1.1 by Jelmer Vernooij
Change default branch name to "".
340
        if branch is None:
341
            branch = ""
342
        return urlutils.unescape(branch)
5268.7.22 by Jelmer Vernooij
Add ControlDir._get_selected_branch.
343
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
344
    def has_workingtree(self):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
345
        """Tell if this controldir contains a working tree.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
346
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
347
        This will still raise an exception if the controldir has a workingtree
348
        that is remote & inaccessible.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
349
350
        Note: if you're going to open the working tree, you should just go ahead
351
        and try, and not ask permission first.  (This method just opens the
352
        workingtree and discards it, and that's somewhat expensive.)
353
        """
354
        try:
355
            self.open_workingtree(recommend_upgrade=False)
356
            return True
357
        except errors.NoWorkingTree:
358
            return False
359
360
    def cloning_metadir(self, require_stacking=False):
361
        """Produce a metadir suitable for cloning or sprouting with.
362
363
        These operations may produce workingtrees (yes, even though they're
364
        "cloning" something that doesn't have a tree), so a viable workingtree
365
        format must be selected.
366
367
        :require_stacking: If True, non-stackable formats will be upgraded
368
            to similar stackable formats.
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
369
        :returns: a ControlDirFormat with all component formats either set
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
370
            appropriately or set to None if that component should not be
371
            created.
372
        """
373
        raise NotImplementedError(self.cloning_metadir)
374
375
    def checkout_metadir(self):
6305.5.13 by Jelmer Vernooij
More documentation.
376
        """Produce a metadir suitable for checkouts of this controldir.
377
378
        :returns: A ControlDirFormat with all component formats
379
            either set appropriately or set to None if that component
380
            should not be created.
381
        """
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
382
        return self.cloning_metadir()
383
384
    def sprout(self, url, revision_id=None, force_new_repo=False,
385
               recurse='down', possible_transports=None,
386
               accelerator_tree=None, hardlink=False, stacked=False,
6929.14.2 by Jelmer Vernooij
Support --lossy argument to 'brz push'.
387
               source_branch=None, create_tree_if_local=True,
388
               lossy=False):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
389
        """Create a copy of this controldir prepared for use as a new line of
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
390
        development.
391
392
        If url's last component does not exist, it will be created.
393
394
        Attributes related to the identity of the source branch like
395
        branch nickname will be cleaned, a working tree is created
396
        whether one existed before or not; and a local branch is always
397
        created.
398
5891.1.3 by Andrew Bennetts
Move docstring formatting fixes.
399
        :param revision_id: if revision_id is not None, then the clone
400
            operation may tune itself to download less data.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
401
        :param accelerator_tree: A tree which can be used for retrieving file
402
            contents more quickly than the revision tree, i.e. a workingtree.
403
            The revision tree will be used for cases where accelerator_tree's
404
            content is different.
405
        :param hardlink: If true, hard-link files from accelerator_tree,
406
            where possible.
407
        :param stacked: If true, create a stacked branch referring to the
408
            location of this control directory.
409
        :param create_tree_if_local: If true, a working-tree will be created
410
            when working locally.
411
        """
5735.1.1 by Jelmer Vernooij
Move ControlDir.sprout to BzrDir.
412
        raise NotImplementedError(self.sprout)
5535.3.12 by Andrew Bennetts
Shift more complexity out of sprout.
413
6929.14.2 by Jelmer Vernooij
Support --lossy argument to 'brz push'.
414
    def push_branch(self, source, revision_id=None, overwrite=False,
7489.4.2 by Jelmer Vernooij
Plumb through tag_selector.
415
                    remember=False, create_prefix=False, lossy=False,
416
                    tag_selector=None):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
417
        """Push the source branch into this ControlDir."""
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
418
        br_to = None
419
        # If we can open a branch, use its direct repository, otherwise see
420
        # if there is a repository without a branch.
421
        try:
422
            br_to = self.open_branch()
423
        except errors.NotBranchError:
424
            # Didn't find a branch, can we find a repository?
425
            repository_to = self.find_repository()
426
        else:
427
            # Found a branch, so we must have found a repository
428
            repository_to = br_to.repository
429
430
        push_result = PushResult()
431
        push_result.source_branch = source
432
        if br_to is None:
433
            # We have a repository but no branch, copy the revisions, and then
434
            # create a branch.
5609.26.1 by John Arbash Meinel
Fix bug #465517, 'bzr push' to a target with a repo but no branch
435
            if revision_id is None:
436
                # No revision supplied by the user, default to the branch
437
                # revision
438
                revision_id = source.last_revision()
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
439
            repository_to.fetch(source.repository, revision_id=revision_id)
7489.4.2 by Jelmer Vernooij
Plumb through tag_selector.
440
            br_to = source.sprout(
441
                self, revision_id=revision_id, lossy=lossy,
442
                tag_selector=tag_selector)
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
443
            if source.get_push_location() is None or remember:
6404.6.7 by Vincent Ladeuil
Change set/remove to require a lock for the branch config files.
444
                # FIXME: Should be done only if we succeed ? -- vila 2012-01-18
445
                source.set_push_location(br_to.base)
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
446
            push_result.stacked_on = None
447
            push_result.branch_push_result = None
448
            push_result.old_revno = None
449
            push_result.old_revid = _mod_revision.NULL_REVISION
450
            push_result.target_branch = br_to
451
            push_result.master_branch = None
452
            push_result.workingtree_updated = False
453
        else:
454
            # We have successfully opened the branch, remember if necessary:
455
            if source.get_push_location() is None or remember:
6404.6.7 by Vincent Ladeuil
Change set/remove to require a lock for the branch config files.
456
                # FIXME: Should be done only if we succeed ? -- vila 2012-01-18
457
                source.set_push_location(br_to.base)
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
458
            try:
459
                tree_to = self.open_workingtree()
460
            except errors.NotLocalUrl:
7290.26.1 by Jelmer Vernooij
Fix switching in git repositories.
461
                push_result.branch_push_result = source.push(
7489.4.2 by Jelmer Vernooij
Plumb through tag_selector.
462
                    br_to, overwrite, stop_revision=revision_id, lossy=lossy,
463
                    tag_selector=tag_selector)
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
464
                push_result.workingtree_updated = False
465
            except errors.NoWorkingTree:
7290.26.1 by Jelmer Vernooij
Fix switching in git repositories.
466
                push_result.branch_push_result = source.push(
7489.4.2 by Jelmer Vernooij
Plumb through tag_selector.
467
                    br_to, overwrite, stop_revision=revision_id, lossy=lossy,
468
                    tag_selector=tag_selector)
7143.15.2 by Jelmer Vernooij
Run autopep8.
469
                push_result.workingtree_updated = None  # Not applicable
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
470
            else:
6929.14.1 by Jelmer Vernooij
add --lossy option to 'bzr push'.
471
                with tree_to.lock_write():
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
472
                    push_result.branch_push_result = source.push(
6929.14.1 by Jelmer Vernooij
add --lossy option to 'bzr push'.
473
                        tree_to.branch, overwrite, stop_revision=revision_id,
7489.4.2 by Jelmer Vernooij
Plumb through tag_selector.
474
                        lossy=lossy, tag_selector=tag_selector)
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
475
                    tree_to.update()
476
                push_result.workingtree_updated = True
477
            push_result.old_revno = push_result.branch_push_result.old_revno
478
            push_result.old_revid = push_result.branch_push_result.old_revid
479
            push_result.target_branch = \
480
                push_result.branch_push_result.target_branch
481
        return push_result
482
5363.2.19 by Jelmer Vernooij
Put _get_tree_branch onto ControlDir.
483
    def _get_tree_branch(self, name=None):
6207.3.3 by jelmer at samba
Fix tests and the like.
484
        """Return the branch and tree, if any, for this controldir.
5363.2.19 by Jelmer Vernooij
Put _get_tree_branch onto ControlDir.
485
486
        :param name: Name of colocated branch to open.
487
488
        Return None for tree if not present or inaccessible.
489
        Raise NotBranchError if no branch is present.
490
        :return: (tree, branch)
491
        """
492
        try:
493
            tree = self.open_workingtree()
494
        except (errors.NoWorkingTree, errors.NotLocalUrl):
495
            tree = None
496
            branch = self.open_branch(name=name)
497
        else:
498
            if name is not None:
499
                branch = self.open_branch(name=name)
500
            else:
501
                branch = tree.branch
502
        return tree, branch
503
5363.2.24 by Jelmer Vernooij
Move get_config to ControlDir.
504
    def get_config(self):
505
        """Get configuration for this ControlDir."""
506
        raise NotImplementedError(self.get_config)
5363.2.19 by Jelmer Vernooij
Put _get_tree_branch onto ControlDir.
507
5363.2.28 by Jelmer Vernooij
Move clone() onto ControlDir.clone(), add ControlDir.clone_on_transport() stub.
508
    def check_conversion_target(self, target_format):
6207.3.3 by jelmer at samba
Fix tests and the like.
509
        """Check that a controldir as a whole can be converted to a new format."""
5363.2.28 by Jelmer Vernooij
Move clone() onto ControlDir.clone(), add ControlDir.clone_on_transport() stub.
510
        raise NotImplementedError(self.check_conversion_target)
511
512
    def clone(self, url, revision_id=None, force_new_repo=False,
7489.4.2 by Jelmer Vernooij
Plumb through tag_selector.
513
              preserve_stacking=False, tag_selector=None):
6207.3.3 by jelmer at samba
Fix tests and the like.
514
        """Clone this controldir and its contents to url verbatim.
5363.2.28 by Jelmer Vernooij
Move clone() onto ControlDir.clone(), add ControlDir.clone_on_transport() stub.
515
516
        :param url: The url create the clone at.  If url's last component does
517
            not exist, it will be created.
518
        :param revision_id: The tip revision-id to use for any branch or
519
            working tree.  If not None, then the clone operation may tune
520
            itself to download less data.
521
        :param force_new_repo: Do not use a shared repository for the target
522
                               even if one is available.
523
        :param preserve_stacking: When cloning a stacked branch, stack the
524
            new branch on top of the other branch's stacked-on branch.
525
        """
5609.9.1 by Martin
Blindly change all users of get_transport to address the function via the transport module
526
        return self.clone_on_transport(_mod_transport.get_transport(url),
5363.2.28 by Jelmer Vernooij
Move clone() onto ControlDir.clone(), add ControlDir.clone_on_transport() stub.
527
                                       revision_id=revision_id,
528
                                       force_new_repo=force_new_repo,
7489.4.2 by Jelmer Vernooij
Plumb through tag_selector.
529
                                       preserve_stacking=preserve_stacking,
530
                                       tag_selector=tag_selector)
5363.2.28 by Jelmer Vernooij
Move clone() onto ControlDir.clone(), add ControlDir.clone_on_transport() stub.
531
532
    def clone_on_transport(self, transport, revision_id=None,
7143.15.2 by Jelmer Vernooij
Run autopep8.
533
                           force_new_repo=False, preserve_stacking=False, stacked_on=None,
7489.4.2 by Jelmer Vernooij
Plumb through tag_selector.
534
                           create_prefix=False, use_existing_dir=True, no_tree=False,
535
                           tag_selector=None):
6207.3.3 by jelmer at samba
Fix tests and the like.
536
        """Clone this controldir and its contents to transport verbatim.
5363.2.28 by Jelmer Vernooij
Move clone() onto ControlDir.clone(), add ControlDir.clone_on_transport() stub.
537
538
        :param transport: The transport for the location to produce the clone
539
            at.  If the target directory does not exist, it will be created.
540
        :param revision_id: The tip revision-id to use for any branch or
541
            working tree.  If not None, then the clone operation may tune
542
            itself to download less data.
543
        :param force_new_repo: Do not use a shared repository for the target,
544
                               even if one is available.
545
        :param preserve_stacking: When cloning a stacked branch, stack the
546
            new branch on top of the other branch's stacked-on branch.
547
        :param create_prefix: Create any missing directories leading up to
548
            to_transport.
549
        :param use_existing_dir: Use an existing directory if one exists.
5664.1.1 by Jelmer Vernooij
Document no_tree option to ControlDir.clone_on_transport.
550
        :param no_tree: If set to true prevents creation of a working tree.
5363.2.28 by Jelmer Vernooij
Move clone() onto ControlDir.clone(), add ControlDir.clone_on_transport() stub.
551
        """
552
        raise NotImplementedError(self.clone_on_transport)
553
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
554
    @classmethod
6681.2.3 by Jelmer Vernooij
Rename find_bzrdir.
555
    def find_controldirs(klass, transport, evaluate=None, list_current=None):
6207.3.3 by jelmer at samba
Fix tests and the like.
556
        """Find control dirs recursively from current location.
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
557
558
        This is intended primarily as a building block for more sophisticated
559
        functionality, like finding trees under a directory, or finding
560
        branches that use a given repository.
561
562
        :param evaluate: An optional callable that yields recurse, value,
6207.3.3 by jelmer at samba
Fix tests and the like.
563
            where recurse controls whether this controldir is recursed into
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
564
            and value is the value to yield.  By default, all bzrdirs
6207.3.3 by jelmer at samba
Fix tests and the like.
565
            are recursed into, and the return value is the controldir.
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
566
        :param list_current: if supplied, use this function to list the current
567
            directory, instead of Transport.list_dir
568
        :return: a generator of found bzrdirs, or whatever evaluate returns.
569
        """
570
        if list_current is None:
571
            def list_current(transport):
572
                return transport.list_dir('')
573
        if evaluate is None:
6207.3.3 by jelmer at samba
Fix tests and the like.
574
            def evaluate(controldir):
575
                return True, controldir
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
576
577
        pending = [transport]
578
        while len(pending) > 0:
579
            current_transport = pending.pop()
580
            recurse = True
581
            try:
6207.3.6 by Jelmer Vernooij
use klass rather than cls everywhere for consistency
582
                controldir = klass.open_from_transport(current_transport)
7358.2.1 by Jelmer Vernooij
Ignore UnknownFormatError in ControlDir.find_controldirs
583
            except (errors.NotBranchError, errors.PermissionDenied,
584
                    errors.UnknownFormatError):
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
585
                pass
586
            else:
6207.3.3 by jelmer at samba
Fix tests and the like.
587
                recurse, value = evaluate(controldir)
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
588
                yield value
589
            try:
590
                subdirs = list_current(current_transport)
591
            except (errors.NoSuchFile, errors.PermissionDenied):
592
                continue
593
            if recurse:
594
                for subdir in sorted(subdirs, reverse=True):
595
                    pending.append(current_transport.clone(subdir))
596
597
    @classmethod
6207.3.6 by Jelmer Vernooij
use klass rather than cls everywhere for consistency
598
    def find_branches(klass, transport):
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
599
        """Find all branches under a transport.
600
601
        This will find all branches below the transport, including branches
602
        inside other branches.  Where possible, it will use
603
        Repository.find_branches.
604
605
        To list all the branches that use a particular Repository, see
606
        Repository.find_branches
607
        """
6207.3.3 by jelmer at samba
Fix tests and the like.
608
        def evaluate(controldir):
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
609
            try:
6207.3.3 by jelmer at samba
Fix tests and the like.
610
                repository = controldir.open_repository()
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
611
            except errors.NoRepositoryPresent:
612
                pass
613
            else:
614
                return False, ([], repository)
6207.3.3 by jelmer at samba
Fix tests and the like.
615
            return True, (controldir.list_branches(), None)
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
616
        ret = []
6681.2.3 by Jelmer Vernooij
Rename find_bzrdir.
617
        for branches, repo in klass.find_controldirs(
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
618
                transport, evaluate=evaluate):
619
            if repo is not None:
620
                ret.extend(repo.find_branches())
621
            if branches is not None:
622
                ret.extend(branches)
623
        return ret
624
625
    @classmethod
6207.3.6 by Jelmer Vernooij
use klass rather than cls everywhere for consistency
626
    def create_branch_and_repo(klass, base, force_new_repo=False, format=None):
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
627
        """Create a new ControlDir, Branch and Repository at the url 'base'.
628
629
        This will use the current default ControlDirFormat unless one is
630
        specified, and use whatever
6207.3.3 by jelmer at samba
Fix tests and the like.
631
        repository format that that uses via controldir.create_branch and
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
632
        create_repository. If a shared repository is available that is used
633
        preferentially.
634
635
        The created Branch object is returned.
636
637
        :param base: The URL to create the branch at.
638
        :param force_new_repo: If True a new repository is always created.
639
        :param format: If supplied, the format of branch to create.  If not
640
            supplied, the default is used.
641
        """
6207.3.6 by Jelmer Vernooij
use klass rather than cls everywhere for consistency
642
        controldir = klass.create(base, format)
6207.3.3 by jelmer at samba
Fix tests and the like.
643
        controldir._find_or_create_repository(force_new_repo)
644
        return controldir.create_branch()
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
645
646
    @classmethod
6207.3.6 by Jelmer Vernooij
use klass rather than cls everywhere for consistency
647
    def create_branch_convenience(klass, base, force_new_repo=False,
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
648
                                  force_new_tree=None, format=None,
649
                                  possible_transports=None):
650
        """Create a new ControlDir, Branch and Repository at the url 'base'.
651
652
        This is a convenience function - it will use an existing repository
653
        if possible, can be told explicitly whether to create a working tree or
654
        not.
655
656
        This will use the current default ControlDirFormat unless one is
657
        specified, and use whatever
6207.3.3 by jelmer at samba
Fix tests and the like.
658
        repository format that that uses via ControlDir.create_branch and
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
659
        create_repository. If a shared repository is available that is used
660
        preferentially. Whatever repository is used, its tree creation policy
661
        is followed.
662
663
        The created Branch object is returned.
664
        If a working tree cannot be made due to base not being a file:// url,
665
        no error is raised unless force_new_tree is True, in which case no
666
        data is created on disk and NotLocalUrl is raised.
667
668
        :param base: The URL to create the branch at.
669
        :param force_new_repo: If True a new repository is always created.
670
        :param force_new_tree: If True or False force creation of a tree or
671
                               prevent such creation respectively.
6207.3.3 by jelmer at samba
Fix tests and the like.
672
        :param format: Override for the controldir format to create.
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
673
        :param possible_transports: An optional reusable transports list.
674
        """
675
        if force_new_tree:
676
            # check for non local urls
677
            t = _mod_transport.get_transport(base, possible_transports)
678
            if not isinstance(t, local.LocalTransport):
679
                raise errors.NotLocalUrl(base)
6207.3.6 by Jelmer Vernooij
use klass rather than cls everywhere for consistency
680
        controldir = klass.create(base, format, possible_transports)
6207.3.3 by jelmer at samba
Fix tests and the like.
681
        repo = controldir._find_or_create_repository(force_new_repo)
682
        result = controldir.create_branch()
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
683
        if force_new_tree or (repo.make_working_trees() and
684
                              force_new_tree is None):
685
            try:
6207.3.3 by jelmer at samba
Fix tests and the like.
686
                controldir.create_workingtree()
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
687
            except errors.NotLocalUrl:
688
                pass
689
        return result
690
691
    @classmethod
6207.3.6 by Jelmer Vernooij
use klass rather than cls everywhere for consistency
692
    def create_standalone_workingtree(klass, base, format=None):
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
693
        """Create a new ControlDir, WorkingTree, Branch and Repository at 'base'.
694
695
        'base' must be a local path or a file:// url.
696
697
        This will use the current default ControlDirFormat unless one is
698
        specified, and use whatever
699
        repository format that that uses for bzrdirformat.create_workingtree,
700
        create_branch and create_repository.
701
6207.3.3 by jelmer at samba
Fix tests and the like.
702
        :param format: Override for the controldir format to create.
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
703
        :return: The WorkingTree object.
704
        """
705
        t = _mod_transport.get_transport(base)
706
        if not isinstance(t, local.LocalTransport):
707
            raise errors.NotLocalUrl(base)
6207.3.6 by Jelmer Vernooij
use klass rather than cls everywhere for consistency
708
        controldir = klass.create_branch_and_repo(base,
7143.15.2 by Jelmer Vernooij
Run autopep8.
709
                                                  force_new_repo=True,
710
                                                  format=format).controldir
6207.3.3 by jelmer at samba
Fix tests and the like.
711
        return controldir.create_workingtree()
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
712
713
    @classmethod
6207.3.6 by Jelmer Vernooij
use klass rather than cls everywhere for consistency
714
    def open_unsupported(klass, base):
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
715
        """Open a branch which is not supported."""
6207.3.6 by Jelmer Vernooij
use klass rather than cls everywhere for consistency
716
        return klass.open(base, _unsupported=True)
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
717
718
    @classmethod
6402.3.3 by Jelmer Vernooij
Simplify safe open a bit more.
719
    def open(klass, base, possible_transports=None, probers=None,
720
             _unsupported=False):
6207.3.3 by jelmer at samba
Fix tests and the like.
721
        """Open an existing controldir, rooted at 'base' (url).
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
722
723
        :param _unsupported: a private parameter to the ControlDir class.
724
        """
725
        t = _mod_transport.get_transport(base, possible_transports)
6402.3.3 by Jelmer Vernooij
Simplify safe open a bit more.
726
        return klass.open_from_transport(t, probers=probers,
7143.15.2 by Jelmer Vernooij
Run autopep8.
727
                                         _unsupported=_unsupported)
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
728
729
    @classmethod
6207.3.6 by Jelmer Vernooij
use klass rather than cls everywhere for consistency
730
    def open_from_transport(klass, transport, _unsupported=False,
6402.3.3 by Jelmer Vernooij
Simplify safe open a bit more.
731
                            probers=None):
6207.3.3 by jelmer at samba
Fix tests and the like.
732
        """Open a controldir within a particular directory.
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
733
6207.3.3 by jelmer at samba
Fix tests and the like.
734
        :param transport: Transport containing the controldir.
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
735
        :param _unsupported: private.
736
        """
6207.3.6 by Jelmer Vernooij
use klass rather than cls everywhere for consistency
737
        for hook in klass.hooks['pre_open']:
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
738
            hook(transport)
739
        # Keep initial base since 'transport' may be modified while following
740
        # the redirections.
741
        base = transport.base
7143.15.2 by Jelmer Vernooij
Run autopep8.
742
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
743
        def find_format(transport):
6402.3.3 by Jelmer Vernooij
Simplify safe open a bit more.
744
            return transport, ControlDirFormat.find_format(transport,
7143.15.2 by Jelmer Vernooij
Run autopep8.
745
                                                           probers=probers)
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
746
747
        def redirected(transport, e, redirection_notice):
748
            redirected_transport = transport._redirected_to(e.source, e.target)
749
            if redirected_transport is None:
750
                raise errors.NotBranchError(base)
6207.3.7 by Jelmer Vernooij
Fix import of trace.note and gettext.
751
            trace.note(gettext('{0} is{1} redirected to {2}').format(
7143.15.2 by Jelmer Vernooij
Run autopep8.
752
                transport.base, e.permanently, redirected_transport.base))
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
753
            return redirected_transport
754
755
        try:
756
            transport, format = _mod_transport.do_catching_redirections(
757
                find_format, transport, redirected)
758
        except errors.TooManyRedirections:
759
            raise errors.NotBranchError(base)
760
761
        format.check_support_status(_unsupported)
762
        return format.open(transport, _found=True)
763
764
    @classmethod
6207.3.6 by Jelmer Vernooij
use klass rather than cls everywhere for consistency
765
    def open_containing(klass, url, possible_transports=None):
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
766
        """Open an existing branch which contains url.
767
768
        :param url: url to search from.
769
770
        See open_containing_from_transport for more detail.
771
        """
772
        transport = _mod_transport.get_transport(url, possible_transports)
6207.3.6 by Jelmer Vernooij
use klass rather than cls everywhere for consistency
773
        return klass.open_containing_from_transport(transport)
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
774
775
    @classmethod
6207.3.6 by Jelmer Vernooij
use klass rather than cls everywhere for consistency
776
    def open_containing_from_transport(klass, a_transport):
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
777
        """Open an existing branch which contains a_transport.base.
778
779
        This probes for a branch at a_transport, and searches upwards from there.
780
781
        Basically we keep looking up until we find the control directory or
782
        run into the root.  If there isn't one, raises NotBranchError.
783
        If there is one and it is either an unrecognised format or an unsupported
784
        format, UnknownFormatError or UnsupportedFormatError are raised.
785
        If there is one, it is returned, along with the unused portion of url.
786
787
        :return: The ControlDir that contains the path, and a Unicode path
788
                for the rest of the URL.
789
        """
790
        # this gets the normalised url back. I.e. '.' -> the full path.
791
        url = a_transport.base
792
        while True:
793
            try:
6207.3.6 by Jelmer Vernooij
use klass rather than cls everywhere for consistency
794
                result = klass.open_from_transport(a_transport)
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
795
                return result, urlutils.unescape(a_transport.relpath(url))
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
796
            except errors.NotBranchError:
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
797
                pass
6379.6.1 by Jelmer Vernooij
Import absolute_import in a few places.
798
            except errors.PermissionDenied:
799
                pass
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
800
            try:
801
                new_t = a_transport.clone('..')
6729.6.1 by Jelmer Vernooij
Move urlutils errors.
802
            except urlutils.InvalidURLJoin:
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
803
                # reached the root, whatever that may be
804
                raise errors.NotBranchError(path=url)
805
            if new_t.base == a_transport.base:
806
                # reached the root, whatever that may be
807
                raise errors.NotBranchError(path=url)
808
            a_transport = new_t
809
810
    @classmethod
811
    def open_tree_or_branch(klass, location):
812
        """Return the branch and working tree at a location.
813
814
        If there is no tree at the location, tree will be None.
815
        If there is no branch at the location, an exception will be
816
        raised
817
        :return: (tree, branch)
818
        """
6207.3.3 by jelmer at samba
Fix tests and the like.
819
        controldir = klass.open(location)
820
        return controldir._get_tree_branch()
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
821
822
    @classmethod
6437.16.1 by Jelmer Vernooij
Fix 'bzr send' in treeless branches.
823
    def open_containing_tree_or_branch(klass, location,
7143.15.2 by Jelmer Vernooij
Run autopep8.
824
                                       possible_transports=None):
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
825
        """Return the branch and working tree contained by a location.
826
827
        Returns (tree, branch, relpath).
828
        If there is no tree at containing the location, tree will be None.
829
        If there is no branch containing the location, an exception will be
830
        raised
831
        relpath is the portion of the path that is contained by the branch.
832
        """
6437.16.1 by Jelmer Vernooij
Fix 'bzr send' in treeless branches.
833
        controldir, relpath = klass.open_containing(location,
7143.15.2 by Jelmer Vernooij
Run autopep8.
834
                                                    possible_transports=possible_transports)
6207.3.3 by jelmer at samba
Fix tests and the like.
835
        tree, branch = controldir._get_tree_branch()
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
836
        return tree, branch, relpath
837
838
    @classmethod
839
    def open_containing_tree_branch_or_repository(klass, location):
840
        """Return the working tree, branch and repo contained by a location.
841
842
        Returns (tree, branch, repository, relpath).
843
        If there is no tree containing the location, tree will be None.
844
        If there is no branch containing the location, branch will be None.
845
        If there is no repository containing the location, repository will be
846
        None.
847
        relpath is the portion of the path that is contained by the innermost
848
        ControlDir.
849
850
        If no tree, branch or repository is found, a NotBranchError is raised.
851
        """
6207.3.3 by jelmer at samba
Fix tests and the like.
852
        controldir, relpath = klass.open_containing(location)
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
853
        try:
6207.3.3 by jelmer at samba
Fix tests and the like.
854
            tree, branch = controldir._get_tree_branch()
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
855
        except errors.NotBranchError:
856
            try:
6207.3.3 by jelmer at samba
Fix tests and the like.
857
                repo = controldir.find_repository()
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
858
                return None, None, repo, relpath
859
            except (errors.NoRepositoryPresent):
860
                raise errors.NotBranchError(location)
861
        return tree, branch, branch.repository, relpath
862
863
    @classmethod
6207.3.6 by Jelmer Vernooij
use klass rather than cls everywhere for consistency
864
    def create(klass, base, format=None, possible_transports=None):
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
865
        """Create a new ControlDir at the url 'base'.
866
867
        :param format: If supplied, the format of branch to create.  If not
868
            supplied, the default is used.
869
        :param possible_transports: If supplied, a list of transports that
870
            can be reused to share a remote connection.
871
        """
6207.3.6 by Jelmer Vernooij
use klass rather than cls everywhere for consistency
872
        if klass is not ControlDir:
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
873
            raise AssertionError("ControlDir.create always creates the"
7143.15.2 by Jelmer Vernooij
Run autopep8.
874
                                 "default format, not one of %r" % klass)
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
875
        t = _mod_transport.get_transport(base, possible_transports)
876
        t.ensure_base()
877
        if format is None:
878
            format = ControlDirFormat.get_default_format()
879
        return format.initialize_on_transport(t)
880
881
882
class ControlDirHooks(hooks.Hooks):
883
    """Hooks for ControlDir operations."""
884
885
    def __init__(self):
886
        """Create the default hooks."""
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
887
        hooks.Hooks.__init__(self, "breezy.controldir", "ControlDir.hooks")
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
888
        self.add_hook('pre_open',
7143.15.2 by Jelmer Vernooij
Run autopep8.
889
                      "Invoked before attempting to open a ControlDir with the transport "
890
                      "that the open will use.", (1, 14))
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
891
        self.add_hook('post_repo_init',
7143.15.2 by Jelmer Vernooij
Run autopep8.
892
                      "Invoked after a repository has been initialized. "
893
                      "post_repo_init is called with a "
894
                      "breezy.controldir.RepoInitHookParams.",
895
                      (2, 2))
896
6207.3.2 by jelmer at samba
Move convenience methods to ControlDir.
897
898
# install the default hooks
899
ControlDir.hooks = ControlDirHooks()
900
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
901
5669.3.9 by Jelmer Vernooij
Consistent naming.
902
class ControlComponentFormat(object):
6213.1.24 by Jelmer Vernooij
More refactoring.
903
    """A component that can live inside of a control directory."""
5669.3.8 by Jelmer Vernooij
Refactor, move to bzrlib.controldir.
904
5717.1.1 by Jelmer Vernooij
Support overriding check_supported.
905
    upgrade_recommended = False
906
5669.3.9 by Jelmer Vernooij
Consistent naming.
907
    def get_format_description(self):
908
        """Return the short description for this format."""
909
        raise NotImplementedError(self.get_format_description)
910
5717.1.1 by Jelmer Vernooij
Support overriding check_supported.
911
    def is_supported(self):
912
        """Is this format supported?
913
914
        Supported formats must be initializable and openable.
915
        Unsupported formats may not support initialization or committing or
916
        some other features depending on the reason for not being supported.
917
        """
5717.1.4 by Jelmer Vernooij
Test default control component format implementation.
918
        return True
5717.1.1 by Jelmer Vernooij
Support overriding check_supported.
919
5717.1.7 by Jelmer Vernooij
Rename check_status -> check_support_status.
920
    def check_support_status(self, allow_unsupported, recommend_upgrade=True,
7143.15.2 by Jelmer Vernooij
Run autopep8.
921
                             basedir=None):
5717.1.1 by Jelmer Vernooij
Support overriding check_supported.
922
        """Give an error or warning on old formats.
923
924
        :param allow_unsupported: If true, allow opening
925
            formats that are strongly deprecated, and which may
926
            have limited functionality.
927
928
        :param recommend_upgrade: If true (default), warn
929
            the user through the ui object that they may wish
930
            to upgrade the object.
931
        """
932
        if not allow_unsupported and not self.is_supported():
933
            # see open_downlevel to open legacy branches.
5717.1.11 by Jelmer Vernooij
Fix format in exception.
934
            raise errors.UnsupportedFormatError(format=self)
5717.1.1 by Jelmer Vernooij
Support overriding check_supported.
935
        if recommend_upgrade and self.upgrade_recommended:
936
            ui.ui_factory.recommend_upgrade(
937
                self.get_format_description(), basedir)
938
6349.2.2 by Jelmer Vernooij
Fix remaining tests.
939
    @classmethod
940
    def get_format_string(cls):
941
        raise NotImplementedError(cls.get_format_string)
942
5669.3.9 by Jelmer Vernooij
Consistent naming.
943
944
class ControlComponentFormatRegistry(registry.FormatRegistry):
945
    """A registry for control components (branch, workingtree, repository)."""
5669.3.8 by Jelmer Vernooij
Refactor, move to bzrlib.controldir.
946
947
    def __init__(self, other_registry=None):
5669.3.9 by Jelmer Vernooij
Consistent naming.
948
        super(ControlComponentFormatRegistry, self).__init__(other_registry)
5669.3.8 by Jelmer Vernooij
Refactor, move to bzrlib.controldir.
949
        self._extra_formats = []
950
951
    def register(self, format):
952
        """Register a new format."""
5669.3.9 by Jelmer Vernooij
Consistent naming.
953
        super(ControlComponentFormatRegistry, self).register(
5669.3.8 by Jelmer Vernooij
Refactor, move to bzrlib.controldir.
954
            format.get_format_string(), format)
955
956
    def remove(self, format):
957
        """Remove a registered format."""
5669.3.9 by Jelmer Vernooij
Consistent naming.
958
        super(ControlComponentFormatRegistry, self).remove(
5669.3.8 by Jelmer Vernooij
Refactor, move to bzrlib.controldir.
959
            format.get_format_string())
960
961
    def register_extra(self, format):
962
        """Register a format that can not be used in a metadir.
963
964
        This is mainly useful to allow custom repository formats, such as older
965
        Bazaar formats and foreign formats, to be tested.
966
        """
967
        self._extra_formats.append(registry._ObjectGetter(format))
968
969
    def remove_extra(self, format):
970
        """Remove an extra format.
971
        """
972
        self._extra_formats.remove(registry._ObjectGetter(format))
973
974
    def register_extra_lazy(self, module_name, member_name):
975
        """Register a format lazily.
976
        """
977
        self._extra_formats.append(
978
            registry._LazyObjectGetter(module_name, member_name))
979
980
    def _get_extra(self):
7002.1.1 by Martin
Avoid import error from test_inv without dulwich
981
        """Return getters for extra formats, not usable in meta directories."""
982
        return [getter.get_obj for getter in self._extra_formats]
983
984
    def _get_all_lazy(self):
985
        """Return getters for all formats, even those not usable in metadirs."""
986
        result = [self._dict[name].get_obj for name in self.keys()]
987
        result.extend(self._get_extra())
5669.3.8 by Jelmer Vernooij
Refactor, move to bzrlib.controldir.
988
        return result
989
990
    def _get_all(self):
7002.1.1 by Martin
Avoid import error from test_inv without dulwich
991
        """Return all formats, even those not usable in metadirs."""
5669.3.8 by Jelmer Vernooij
Refactor, move to bzrlib.controldir.
992
        result = []
7002.1.1 by Martin
Avoid import error from test_inv without dulwich
993
        for getter in self._get_all_lazy():
994
            fmt = getter()
5669.3.8 by Jelmer Vernooij
Refactor, move to bzrlib.controldir.
995
            if callable(fmt):
996
                fmt = fmt()
997
            result.append(fmt)
7002.1.1 by Martin
Avoid import error from test_inv without dulwich
998
        return result
5669.3.8 by Jelmer Vernooij
Refactor, move to bzrlib.controldir.
999
5676.1.6 by Jelmer Vernooij
Add _ObjGetter.get_module.
1000
    def _get_all_modules(self):
1001
        """Return a set of the modules providing objects."""
1002
        modules = set()
1003
        for name in self.keys():
1004
            modules.add(self._get_module(name))
1005
        for getter in self._extra_formats:
1006
            modules.add(getter.get_module())
1007
        return modules
1008
5669.3.8 by Jelmer Vernooij
Refactor, move to bzrlib.controldir.
1009
5692.1.1 by Jelmer Vernooij
Move Converter (which is generic) from bzrlib.bzrdir to bzrlib.controldir.
1010
class Converter(object):
1011
    """Converts a disk format object from one format to another."""
1012
1013
    def convert(self, to_convert, pb):
1014
        """Perform the conversion of to_convert, giving feedback via pb.
1015
1016
        :param to_convert: The disk object to convert.
1017
        :param pb: a progress bar to use for progress information.
1018
        """
1019
1020
    def step(self, message):
1021
        """Update the pb by a step."""
7143.15.2 by Jelmer Vernooij
Run autopep8.
1022
        self.count += 1
5692.1.1 by Jelmer Vernooij
Move Converter (which is generic) from bzrlib.bzrdir to bzrlib.controldir.
1023
        self.pb.update(message, self.count, self.total)
1024
1025
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
1026
class ControlDirFormat(object):
1027
    """An encapsulation of the initialization and open routines for a format.
1028
1029
    Formats provide three things:
1030
     * An initialization routine,
1031
     * a format string,
1032
     * an open routine.
1033
1034
    Formats are placed in a dict by their format string for reference
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
1035
    during controldir opening. These should be subclasses of ControlDirFormat
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
1036
    for consistency.
1037
1038
    Once a format is deprecated, just deprecate the initialize and open
1039
    methods on the format class. Do not deprecate the object, as the
1040
    object will be created every system load.
1041
1042
    :cvar colocated_branches: Whether this formats supports colocated branches.
5393.4.3 by Jelmer Vernooij
Consistent spelling.
1043
    :cvar supports_workingtrees: This control directory can co-exist with a
5393.4.2 by Jelmer Vernooij
Use cvar.
1044
        working tree.
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
1045
    """
1046
1047
    _default_format = None
5363.2.4 by Jelmer Vernooij
Introduce probers, use controldir in a couple more places.
1048
    """The default format used for new control directories."""
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
1049
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
1050
    _probers = []
1051
    """The registered format probers, e.g. BzrProber.
1052
1053
    This is a list of Prober-derived classes.
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
1054
    """
1055
1056
    colocated_branches = False
1057
    """Whether co-located branches are supported for this control dir format.
1058
    """
1059
5393.4.3 by Jelmer Vernooij
Consistent spelling.
1060
    supports_workingtrees = True
5669.1.1 by Jelmer Vernooij
Remove some dependencies on weave formats from bt.test_bzrdir.
1061
    """Whether working trees can exist in control directories of this format.
1062
    """
5393.4.1 by Jelmer Vernooij
Add ControlDirFormat.supports_workingtrees.
1063
5673.1.3 by Jelmer Vernooij
Change flexible_components to fixed_components.
1064
    fixed_components = False
1065
    """Whether components can not change format independent of the control dir.
5673.1.1 by Jelmer Vernooij
Add flexible_components boolean to ControlDir if the
1066
    """
1067
5717.1.1 by Jelmer Vernooij
Support overriding check_supported.
1068
    upgrade_recommended = False
1069
    """Whether an upgrade from this format is recommended."""
1070
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
1071
    def get_format_description(self):
1072
        """Return the short description for this format."""
1073
        raise NotImplementedError(self.get_format_description)
1074
1075
    def get_converter(self, format=None):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
1076
        """Return the converter to use to convert controldirs needing converts.
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
1077
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1078
        This returns a breezy.controldir.Converter object.
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
1079
1080
        This should return the best upgrader to step this format towards the
1081
        current default format. In the case of plugins we can/should provide
1082
        some means for them to extend the range of returnable converters.
1083
1084
        :param format: Optional format to override the default format of the
1085
                       library.
1086
        """
1087
        raise NotImplementedError(self.get_converter)
1088
1089
    def is_supported(self):
1090
        """Is this format supported?
1091
6162.3.4 by Jelmer Vernooij
Use TestNotApplicable rather than returning directly.
1092
        Supported formats must be openable.
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
1093
        Unsupported formats may not support initialization or committing or
1094
        some other features depending on the reason for not being supported.
1095
        """
1096
        return True
1097
6162.3.4 by Jelmer Vernooij
Use TestNotApplicable rather than returning directly.
1098
    def is_initializable(self):
1099
        """Whether new control directories of this format can be initialized.
1100
        """
1101
        return self.is_supported()
1102
5717.1.7 by Jelmer Vernooij
Rename check_status -> check_support_status.
1103
    def check_support_status(self, allow_unsupported, recommend_upgrade=True,
7143.15.2 by Jelmer Vernooij
Run autopep8.
1104
                             basedir=None):
5717.1.1 by Jelmer Vernooij
Support overriding check_supported.
1105
        """Give an error or warning on old formats.
1106
1107
        :param allow_unsupported: If true, allow opening
1108
            formats that are strongly deprecated, and which may
1109
            have limited functionality.
1110
1111
        :param recommend_upgrade: If true (default), warn
1112
            the user through the ui object that they may wish
1113
            to upgrade the object.
1114
        """
1115
        if not allow_unsupported and not self.is_supported():
1116
            # see open_downlevel to open legacy branches.
5717.1.11 by Jelmer Vernooij
Fix format in exception.
1117
            raise errors.UnsupportedFormatError(format=self)
5717.1.1 by Jelmer Vernooij
Support overriding check_supported.
1118
        if recommend_upgrade and self.upgrade_recommended:
1119
            ui.ui_factory.recommend_upgrade(
1120
                self.get_format_description(), basedir)
1121
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
1122
    def same_model(self, target_format):
1123
        return (self.repository_format.rich_root_data ==
7143.15.2 by Jelmer Vernooij
Run autopep8.
1124
                target_format.rich_root_data)
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
1125
1126
    @classmethod
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
1127
    def register_prober(klass, prober):
1128
        """Register a prober that can look for a control dir.
1129
1130
        """
1131
        klass._probers.append(prober)
1132
1133
    @classmethod
1134
    def unregister_prober(klass, prober):
1135
        """Unregister a prober.
1136
1137
        """
1138
        klass._probers.remove(prober)
1139
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
1140
    def __str__(self):
1141
        # Trim the newline
1142
        return self.get_format_description().rstrip()
1143
1144
    @classmethod
6402.3.1 by Jelmer Vernooij
Add safe_open class to bzr.
1145
    def all_probers(klass):
7413.6.1 by Jelmer Vernooij
Add an optional priority field for probers.
1146
        return klass._probers
6402.3.1 by Jelmer Vernooij
Add safe_open class to bzr.
1147
1148
    @classmethod
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
1149
    def known_formats(klass):
1150
        """Return all the known formats.
1151
        """
6973.12.9 by Jelmer Vernooij
More fixes.
1152
        result = []
6402.3.1 by Jelmer Vernooij
Add safe_open class to bzr.
1153
        for prober_kls in klass.all_probers():
6973.12.9 by Jelmer Vernooij
More fixes.
1154
            result.extend(prober_kls.known_formats())
5712.3.14 by Jelmer Vernooij
Add Prober.known_formats.
1155
        return result
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
1156
1157
    @classmethod
6402.3.3 by Jelmer Vernooij
Simplify safe open a bit more.
1158
    def find_format(klass, transport, probers=None):
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
1159
        """Return the format present at transport."""
6402.3.3 by Jelmer Vernooij
Simplify safe open a bit more.
1160
        if probers is None:
7413.6.1 by Jelmer Vernooij
Add an optional priority field for probers.
1161
            probers = sorted(
1162
                klass.all_probers(),
1163
                key=lambda prober: prober.priority(transport))
6402.3.3 by Jelmer Vernooij
Simplify safe open a bit more.
1164
        for prober_kls in probers:
5363.2.4 by Jelmer Vernooij
Introduce probers, use controldir in a couple more places.
1165
            prober = prober_kls()
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
1166
            try:
5363.2.4 by Jelmer Vernooij
Introduce probers, use controldir in a couple more places.
1167
                return prober.probe_transport(transport)
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
1168
            except errors.NotBranchError:
1169
                # this format does not find a control dir here.
1170
                pass
1171
        raise errors.NotBranchError(path=transport.base)
1172
5363.2.4 by Jelmer Vernooij
Introduce probers, use controldir in a couple more places.
1173
    def initialize(self, url, possible_transports=None):
1174
        """Create a control dir at this url and return an opened copy.
1175
1176
        While not deprecated, this method is very specific and its use will
1177
        lead to many round trips to setup a working environment. See
1178
        initialize_on_transport_ex for a [nearly] all-in-one method.
1179
1180
        Subclasses should typically override initialize_on_transport
1181
        instead of this method.
1182
        """
5609.9.1 by Martin
Blindly change all users of get_transport to address the function via the transport module
1183
        return self.initialize_on_transport(
1184
            _mod_transport.get_transport(url, possible_transports))
1185
5363.2.4 by Jelmer Vernooij
Introduce probers, use controldir in a couple more places.
1186
    def initialize_on_transport(self, transport):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
1187
        """Initialize a new controldir in the base directory of a Transport."""
5363.2.4 by Jelmer Vernooij
Introduce probers, use controldir in a couple more places.
1188
        raise NotImplementedError(self.initialize_on_transport)
1189
1190
    def initialize_on_transport_ex(self, transport, use_existing_dir=False,
7143.15.2 by Jelmer Vernooij
Run autopep8.
1191
                                   create_prefix=False, force_new_repo=False, stacked_on=None,
1192
                                   stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
1193
                                   shared_repo=False, vfs_only=False):
5363.2.4 by Jelmer Vernooij
Introduce probers, use controldir in a couple more places.
1194
        """Create this format on transport.
1195
1196
        The directory to initialize will be created.
1197
1198
        :param force_new_repo: Do not use a shared repository for the target,
1199
                               even if one is available.
1200
        :param create_prefix: Create any missing directories leading up to
1201
            to_transport.
1202
        :param use_existing_dir: Use an existing directory if one exists.
1203
        :param stacked_on: A url to stack any created branch on, None to follow
1204
            any target stacking policy.
1205
        :param stack_on_pwd: If stack_on is relative, the location it is
1206
            relative to.
1207
        :param repo_format_name: If non-None, a repository will be
1208
            made-or-found. Should none be found, or if force_new_repo is True
1209
            the repo_format_name is used to select the format of repository to
1210
            create.
1211
        :param make_working_trees: Control the setting of make_working_trees
1212
            for a new shared repository when one is made. None to use whatever
1213
            default the format has.
1214
        :param shared_repo: Control whether made repositories are shared or
1215
            not.
1216
        :param vfs_only: If True do not attempt to use a smart server
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
1217
        :return: repo, controldir, require_stacking, repository_policy. repo is
1218
            None if none was created or found, controldir is always valid.
5363.2.4 by Jelmer Vernooij
Introduce probers, use controldir in a couple more places.
1219
            require_stacking is the result of examining the stacked_on
1220
            parameter and any stacking policy found for the target.
1221
        """
1222
        raise NotImplementedError(self.initialize_on_transport_ex)
1223
1224
    def network_name(self):
1225
        """A simple byte string uniquely identifying this format for RPC calls.
1226
1227
        Bzr control formats use this disk format string to identify the format
1228
        over the wire. Its possible that other control formats have more
1229
        complex detection requirements, so we permit them to use any unique and
1230
        immutable string they desire.
1231
        """
1232
        raise NotImplementedError(self.network_name)
1233
1234
    def open(self, transport, _found=False):
1235
        """Return an instance of this format for the dir transport points at.
1236
        """
1237
        raise NotImplementedError(self.open)
1238
1239
    @classmethod
1240
    def _set_default_format(klass, format):
1241
        """Set default format (for testing behavior of defaults only)"""
1242
        klass._default_format = format
1243
1244
    @classmethod
1245
    def get_default_format(klass):
1246
        """Return the current default format."""
1247
        return klass._default_format
1248
6205.3.1 by Jelmer Vernooij
Add ControlDirFormat.supports_transport.
1249
    def supports_transport(self, transport):
1250
        """Check if this format can be opened over a particular transport.
1251
        """
1252
        raise NotImplementedError(self.supports_transport)
1253
7311.2.1 by Jelmer Vernooij
Move is_control_filename onto ControlDirFormat.
1254
    @classmethod
1255
    def is_control_filename(klass, filename):
7311.2.2 by Jelmer Vernooij
Add ControlDirFormat.is_control_filename.
1256
        """True if filename is the name of a path which is reserved for
1257
        controldirs.
1258
1259
        :param filename: A filename within the root transport of this
1260
            controldir.
1261
1262
        This is true IF and ONLY IF the filename is part of the namespace reserved
1263
        for bzr control dirs. Currently this is the '.bzr' directory in the root
1264
        of the root_transport. it is expected that plugins will need to extend
1265
        this in the future - for instance to make bzr talk with svn working
1266
        trees.
1267
        """
1268
        raise NotImplementedError(self.is_control_filename)
7311.2.1 by Jelmer Vernooij
Move is_control_filename onto ControlDirFormat.
1269
5363.2.4 by Jelmer Vernooij
Introduce probers, use controldir in a couple more places.
1270
1271
class Prober(object):
5712.3.22 by Jelmer Vernooij
Add some notes about probers.
1272
    """Abstract class that can be used to detect a particular kind of
5363.2.8 by Jelmer Vernooij
Docstrings.
1273
    control directory.
1274
5712.3.22 by Jelmer Vernooij
Add some notes about probers.
1275
    At the moment this just contains a single method to probe a particular
1276
    transport, but it may be extended in the future to e.g. avoid
5363.2.8 by Jelmer Vernooij
Docstrings.
1277
    multiple levels of probing for Subversion repositories.
5712.3.22 by Jelmer Vernooij
Add some notes about probers.
1278
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1279
    See BzrProber and RemoteBzrProber in breezy.bzrdir for the
5712.3.22 by Jelmer Vernooij
Add some notes about probers.
1280
    probers that detect .bzr/ directories and Bazaar smart servers,
1281
    respectively.
1282
7413.6.1 by Jelmer Vernooij
Add an optional priority field for probers.
1283
    Probers should be registered using the register_prober methods on
1284
    ControlDirFormat.
5363.2.8 by Jelmer Vernooij
Docstrings.
1285
    """
5363.2.4 by Jelmer Vernooij
Introduce probers, use controldir in a couple more places.
1286
1287
    def probe_transport(self, transport):
5363.2.8 by Jelmer Vernooij
Docstrings.
1288
        """Return the controldir style format present in a directory.
1289
1290
        :raise UnknownFormatError: If a control dir was found but is
1291
            in an unknown format.
1292
        :raise NotBranchError: If no control directory was found.
1293
        :return: A ControlDirFormat instance.
1294
        """
5363.2.5 by Jelmer Vernooij
Add dummy foreign prober.
1295
        raise NotImplementedError(self.probe_transport)
5363.2.4 by Jelmer Vernooij
Introduce probers, use controldir in a couple more places.
1296
5712.3.15 by Jelmer Vernooij
Remove unused register format functions.
1297
    @classmethod
6207.3.6 by Jelmer Vernooij
use klass rather than cls everywhere for consistency
1298
    def known_formats(klass):
5712.3.13 by Jelmer Vernooij
Add Prober.known_formats().
1299
        """Return the control dir formats known by this prober.
1300
5712.3.21 by Jelmer Vernooij
Add note about sets.
1301
        Multiple probers can return the same formats, so this should
1302
        return a set.
1303
5712.3.13 by Jelmer Vernooij
Add Prober.known_formats().
1304
        :return: A set of known formats.
1305
        """
6207.3.6 by Jelmer Vernooij
use klass rather than cls everywhere for consistency
1306
        raise NotImplementedError(klass.known_formats)
5712.3.13 by Jelmer Vernooij
Add Prober.known_formats().
1307
7413.6.1 by Jelmer Vernooij
Add an optional priority field for probers.
1308
    @classmethod
1309
    def priority(klass, transport):
1310
        """Priority of this prober.
1311
1312
        A lower value means the prober gets checked first.
1313
1314
        Other conventions:
1315
1316
        -10: This is a "server" prober
1317
        0: No priority set
1318
        10: This is a regular file-based prober
1319
        100: This is a prober for an unsupported format
1320
        """
1321
        return 0
1322
5363.2.4 by Jelmer Vernooij
Introduce probers, use controldir in a couple more places.
1323
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
1324
class ControlDirFormatInfo(object):
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
1325
1326
    def __init__(self, native, deprecated, hidden, experimental):
1327
        self.deprecated = deprecated
1328
        self.native = native
1329
        self.hidden = hidden
1330
        self.experimental = experimental
1331
1332
1333
class ControlDirFormatRegistry(registry.Registry):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
1334
    """Registry of user-selectable ControlDir subformats.
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
1335
1336
    Differs from ControlDirFormat._formats in that it provides sub-formats,
5669.3.8 by Jelmer Vernooij
Refactor, move to bzrlib.controldir.
1337
    e.g. BzrDirMeta1 with weave repository.  Also, it's more user-oriented.
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
1338
    """
1339
1340
    def __init__(self):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
1341
        """Create a ControlDirFormatRegistry."""
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
1342
        self._registration_order = list()
1343
        super(ControlDirFormatRegistry, self).__init__()
1344
1345
    def register(self, key, factory, help, native=True, deprecated=False,
6929.10.2 by Jelmer Vernooij
Add register_alias option.
1346
                 hidden=False, experimental=False):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
1347
        """Register a ControlDirFormat factory.
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
1348
1349
        The factory must be a callable that takes one parameter: the key.
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
1350
        It must produce an instance of the ControlDirFormat when called.
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
1351
1352
        This function mainly exists to prevent the info object from being
1353
        supplied directly.
1354
        """
1355
        registry.Registry.register(self, key, factory, help,
7143.15.2 by Jelmer Vernooij
Run autopep8.
1356
                                   ControlDirFormatInfo(native, deprecated, hidden, experimental))
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
1357
        self._registration_order.append(key)
1358
6929.10.4 by Jelmer Vernooij
Add FormatRegistryOption.
1359
    def register_alias(self, key, target, hidden=False):
6929.10.5 by Jelmer Vernooij
simplify aliases
1360
        """Register a format alias.
1361
1362
        :param key: Alias name
1363
        :param target: Target format
1364
        :param hidden: Whether the alias is hidden
1365
        """
6929.10.2 by Jelmer Vernooij
Add register_alias option.
1366
        info = self.get_info(target)
6929.10.5 by Jelmer Vernooij
simplify aliases
1367
        registry.Registry.register_alias(self, key, target,
7143.15.2 by Jelmer Vernooij
Run autopep8.
1368
                                         ControlDirFormatInfo(
1369
                                             native=info.native, deprecated=info.deprecated,
1370
                                             hidden=hidden, experimental=info.experimental))
6929.10.2 by Jelmer Vernooij
Add register_alias option.
1371
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
1372
    def register_lazy(self, key, module_name, member_name, help, native=True,
7143.15.2 by Jelmer Vernooij
Run autopep8.
1373
                      deprecated=False, hidden=False, experimental=False):
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
1374
        registry.Registry.register_lazy(self, key, module_name, member_name,
7143.15.2 by Jelmer Vernooij
Run autopep8.
1375
                                        help, ControlDirFormatInfo(native, deprecated, hidden, experimental))
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
1376
        self._registration_order.append(key)
1377
1378
    def set_default(self, key):
1379
        """Set the 'default' key to be a clone of the supplied key.
1380
1381
        This method must be called once and only once.
1382
        """
6929.10.3 by Jelmer Vernooij
Simply alias registration.
1383
        self.register_alias('default', key)
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
1384
1385
    def set_default_repository(self, key):
1386
        """Set the FormatRegistry default and Repository default.
1387
1388
        This is a transitional method while Repository.set_default_format
1389
        is deprecated.
1390
        """
1391
        if 'default' in self:
1392
            self.remove('default')
1393
        self.set_default(key)
1394
        format = self.get('default')()
1395
6653.6.5 by Jelmer Vernooij
Rename make_bzrdir to make_controldir.
1396
    def make_controldir(self, key):
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
1397
        return self.get(key)()
1398
1399
    def help_topic(self, topic):
1400
        output = ""
1401
        default_realkey = None
1402
        default_help = self.get_help('default')
1403
        help_pairs = []
1404
        for key in self._registration_order:
1405
            if key == 'default':
1406
                continue
1407
            help = self.get_help(key)
1408
            if help == default_help:
1409
                default_realkey = key
1410
            else:
1411
                help_pairs.append((key, help))
1412
1413
        def wrapped(key, help, info):
1414
            if info.native:
1415
                help = '(native) ' + help
1416
            return ':%s:\n%s\n\n' % (key,
7143.15.2 by Jelmer Vernooij
Run autopep8.
1417
                                     textwrap.fill(help, initial_indent='    ',
1418
                                                   subsequent_indent='    ',
1419
                                                   break_long_words=False))
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
1420
        if default_realkey is not None:
1421
            output += wrapped(default_realkey, '(default) %s' % default_help,
1422
                              self.get_info('default'))
1423
        deprecated_pairs = []
1424
        experimental_pairs = []
1425
        for key, help in help_pairs:
1426
            info = self.get_info(key)
1427
            if info.hidden:
1428
                continue
1429
            elif info.deprecated:
1430
                deprecated_pairs.append((key, help))
1431
            elif info.experimental:
1432
                experimental_pairs.append((key, help))
1433
            else:
1434
                output += wrapped(key, help, info)
1435
        output += "\nSee :doc:`formats-help` for more about storage formats."
1436
        other_output = ""
1437
        if len(experimental_pairs) > 0:
1438
            other_output += "Experimental formats are shown below.\n\n"
1439
            for key, help in experimental_pairs:
1440
                info = self.get_info(key)
1441
                other_output += wrapped(key, help, info)
1442
        else:
1443
            other_output += \
1444
                "No experimental formats are available.\n\n"
1445
        if len(deprecated_pairs) > 0:
1446
            other_output += "\nDeprecated formats are shown below.\n\n"
1447
            for key, help in deprecated_pairs:
1448
                info = self.get_info(key)
1449
                other_output += wrapped(key, help, info)
1450
        else:
1451
            other_output += \
1452
                "\nNo deprecated formats are available.\n\n"
1453
        other_output += \
7143.15.2 by Jelmer Vernooij
Run autopep8.
1454
            "\nSee :doc:`formats-help` for more about storage formats."
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
1455
1456
        if topic == 'other-formats':
1457
            return other_output
1458
        else:
1459
            return output
1460
1461
6207.3.3 by jelmer at samba
Fix tests and the like.
1462
class RepoInitHookParams(object):
1463
    """Object holding parameters passed to `*_repo_init` hooks.
1464
1465
    There are 4 fields that hooks may wish to access:
1466
1467
    :ivar repository: Repository created
1468
    :ivar format: Repository format
1469
    :ivar bzrdir: The controldir for the repository
1470
    :ivar shared: The repository is shared
1471
    """
1472
1473
    def __init__(self, repository, format, controldir, shared):
1474
        """Create a group of RepoInitHook parameters.
1475
1476
        :param repository: Repository created
1477
        :param format: Repository format
1478
        :param controldir: The controldir for the repository
1479
        :param shared: The repository is shared
1480
        """
1481
        self.repository = repository
1482
        self.format = format
6653.6.1 by Jelmer Vernooij
Rename a number of attributes from bzrdir to controldir.
1483
        self.controldir = controldir
6207.3.3 by jelmer at samba
Fix tests and the like.
1484
        self.shared = shared
1485
1486
    def __eq__(self, other):
1487
        return self.__dict__ == other.__dict__
1488
1489
    def __repr__(self):
1490
        if self.repository:
1491
            return "<%s for %s>" % (self.__class__.__name__,
7143.15.2 by Jelmer Vernooij
Run autopep8.
1492
                                    self.repository)
6207.3.3 by jelmer at samba
Fix tests and the like.
1493
        else:
1494
            return "<%s for %s>" % (self.__class__.__name__,
7143.15.2 by Jelmer Vernooij
Run autopep8.
1495
                                    self.controldir)
6207.3.3 by jelmer at samba
Fix tests and the like.
1496
1497
7311.2.3 by Jelmer Vernooij
Drop find_trees.
1498
def is_control_filename(filename):
1499
    """Check if filename is used for control directories."""
1500
    # TODO(jelmer): Instead, have a function that returns all control
1501
    # filenames.
7311.2.6 by Jelmer Vernooij
Fix test.
1502
    for key, format in format_registry.items():
1503
        if format().is_control_filename(filename):
7311.2.3 by Jelmer Vernooij
Drop find_trees.
1504
            return True
1505
    else:
1506
        return False
1507
1508
6825.1.1 by Jelmer Vernooij
Move acquisition policy to breezy.controldir.
1509
class RepositoryAcquisitionPolicy(object):
1510
    """Abstract base class for repository acquisition policies.
1511
1512
    A repository acquisition policy decides how a ControlDir acquires a repository
1513
    for a branch that is being created.  The most basic policy decision is
1514
    whether to create a new repository or use an existing one.
1515
    """
7143.15.2 by Jelmer Vernooij
Run autopep8.
1516
6825.1.1 by Jelmer Vernooij
Move acquisition policy to breezy.controldir.
1517
    def __init__(self, stack_on, stack_on_pwd, require_stacking):
1518
        """Constructor.
1519
1520
        :param stack_on: A location to stack on
1521
        :param stack_on_pwd: If stack_on is relative, the location it is
1522
            relative to.
1523
        :param require_stacking: If True, it is a failure to not stack.
1524
        """
1525
        self._stack_on = stack_on
1526
        self._stack_on_pwd = stack_on_pwd
1527
        self._require_stacking = require_stacking
1528
1529
    def configure_branch(self, branch):
1530
        """Apply any configuration data from this policy to the branch.
1531
1532
        Default implementation sets repository stacking.
1533
        """
1534
        if self._stack_on is None:
1535
            return
1536
        if self._stack_on_pwd is None:
1537
            stack_on = self._stack_on
1538
        else:
1539
            try:
1540
                stack_on = urlutils.rebase_url(self._stack_on,
7143.15.2 by Jelmer Vernooij
Run autopep8.
1541
                                               self._stack_on_pwd,
1542
                                               branch.user_url)
6825.1.1 by Jelmer Vernooij
Move acquisition policy to breezy.controldir.
1543
            except urlutils.InvalidRebaseURLs:
1544
                stack_on = self._get_full_stack_on()
1545
        try:
1546
            branch.set_stacked_on_url(stack_on)
1547
        except (_mod_branch.UnstackableBranchFormat,
1548
                errors.UnstackableRepositoryFormat):
1549
            if self._require_stacking:
1550
                raise
1551
1552
    def requires_stacking(self):
1553
        """Return True if this policy requires stacking."""
1554
        return self._stack_on is not None and self._require_stacking
1555
1556
    def _get_full_stack_on(self):
1557
        """Get a fully-qualified URL for the stack_on location."""
1558
        if self._stack_on is None:
1559
            return None
1560
        if self._stack_on_pwd is None:
1561
            return self._stack_on
1562
        else:
1563
            return urlutils.join(self._stack_on_pwd, self._stack_on)
1564
1565
    def _add_fallback(self, repository, possible_transports=None):
1566
        """Add a fallback to the supplied repository, if stacking is set."""
1567
        stack_on = self._get_full_stack_on()
1568
        if stack_on is None:
1569
            return
1570
        try:
1571
            stacked_dir = ControlDir.open(
7143.15.2 by Jelmer Vernooij
Run autopep8.
1572
                stack_on, possible_transports=possible_transports)
6825.1.1 by Jelmer Vernooij
Move acquisition policy to breezy.controldir.
1573
        except errors.JailBreak:
1574
            # We keep the stacking details, but we are in the server code so
1575
            # actually stacking is not needed.
1576
            return
1577
        try:
1578
            stacked_repo = stacked_dir.open_branch().repository
1579
        except errors.NotBranchError:
1580
            stacked_repo = stacked_dir.open_repository()
1581
        try:
1582
            repository.add_fallback_repository(stacked_repo)
1583
        except errors.UnstackableRepositoryFormat:
1584
            if self._require_stacking:
1585
                raise
1586
        else:
1587
            self._require_stacking = True
1588
1589
    def acquire_repository(self, make_working_trees=None, shared=False,
7143.15.2 by Jelmer Vernooij
Run autopep8.
1590
                           possible_transports=None):
6825.1.1 by Jelmer Vernooij
Move acquisition policy to breezy.controldir.
1591
        """Acquire a repository for this controlrdir.
1592
1593
        Implementations may create a new repository or use a pre-exising
1594
        repository.
1595
1596
        :param make_working_trees: If creating a repository, set
1597
            make_working_trees to this value (if non-None)
1598
        :param shared: If creating a repository, make it shared if True
1599
        :return: A repository, is_new_flag (True if the repository was
1600
            created).
1601
        """
7143.15.2 by Jelmer Vernooij
Run autopep8.
1602
        raise NotImplementedError(
1603
            RepositoryAcquisitionPolicy.acquire_repository)
6825.1.1 by Jelmer Vernooij
Move acquisition policy to breezy.controldir.
1604
1605
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
1606
# Please register new formats after old formats so that formats
1607
# appear in chronological order and format descriptions can build
1608
# on previous ones.
1609
format_registry = ControlDirFormatRegistry()
5363.2.23 by Jelmer Vernooij
Move network_format_registry to bzrlib.controldir.
1610
1611
network_format_registry = registry.FormatRegistry()
1612
"""Registry of formats indexed by their network name.
1613
1614
The network name for a ControlDirFormat is an identifier that can be used when
1615
referring to formats with smart server operations. See
1616
ControlDirFormat.network_name() for more detail.
1617
"""