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