/brz/remove-bazaar

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