/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5557.1.7 by John Arbash Meinel
Merge in the bzr.dev 5582
1
# Copyright (C) 2010, 2011 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,
5363.2.1 by Jelmer Vernooij
Add controldir file.
21
see bzrlib.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
25
from bzrlib.lazy_import import lazy_import
26
lazy_import(globals(), """
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
27
import textwrap
28
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
29
from bzrlib import (
5536.1.1 by Andrew Bennetts
Avoid reopening (and relocking) the same branches/repositories in ControlDir.sprout. Still a few rough edges, but the tests I've run are passing.
30
    cleanup,
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
31
    errors,
5535.4.23 by Andrew Bennetts
Move FetchSpecFactory and TargetRepoKinds to bzrlib.fetch (from bzrlib.controldir).
32
    fetch,
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
33
    revision as _mod_revision,
5609.9.1 by Martin
Blindly change all users of get_transport to address the function via the transport module
34
    transport as _mod_transport,
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
35
    urlutils,
36
    )
37
from bzrlib.push import (
38
    PushResult,
39
    )
40
from bzrlib.trace import (
41
    mutter,
42
    )
43
from bzrlib.transport import (
44
    local,
45
    )
46
47
""")
48
5536.1.8 by Andrew Bennetts
Garden the imports in controldir.py.
49
from bzrlib import registry
50
5363.2.10 by Jelmer Vernooij
base ControlDir on ControlComponent.
51
52
class ControlComponent(object):
53
    """Abstract base class for control directory components.
54
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
55
    This provides interfaces that are common across controldirs,
5363.2.10 by Jelmer Vernooij
base ControlDir on ControlComponent.
56
    repositories, branches, and workingtree control directories.
57
58
    They all expose two urls and transports: the *user* URL is the
59
    one that stops above the control directory (eg .bzr) and that
60
    should normally be used in messages, and the *control* URL is
61
    under that in eg .bzr/checkout and is used to read the control
62
    files.
63
64
    This can be used as a mixin and is intended to fit with
65
    foreign formats.
66
    """
67
68
    @property
69
    def control_transport(self):
70
        raise NotImplementedError
71
72
    @property
73
    def control_url(self):
74
        return self.control_transport.base
75
76
    @property
77
    def user_transport(self):
78
        raise NotImplementedError
79
80
    @property
81
    def user_url(self):
82
        return self.user_transport.base
83
84
85
class ControlDir(ControlComponent):
5363.2.21 by Jelmer Vernooij
Update comments.
86
    """A control directory.
87
88
    While this represents a generic control directory, there are a few
89
    features that are present in this interface that are currently only
90
    supported by one of its implementations, BzrDir.
91
92
    These features (bound branches, stacked branches) are currently only
93
    supported by Bazaar, but could be supported by other version control
94
    systems as well. Implementations are required to raise the appropriate
95
    exceptions when an operation is requested that is not supported.
96
97
    This also makes life easier for API users who can rely on the
98
    implementation always allowing a particular feature to be requested but
99
    raising an exception when it is not supported, rather than requiring the
100
    API users to check for magic attributes to see what features are supported.
101
    """
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
102
103
    def can_convert_format(self):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
104
        """Return true if this controldir is one whose format we can convert
105
        from."""
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
106
        return True
107
108
    def list_branches(self):
109
        """Return a sequence of all branches local to this control directory.
110
111
        """
112
        try:
113
            return [self.open_branch()]
114
        except (errors.NotBranchError, errors.NoRepositoryPresent):
115
            return []
116
117
    def is_control_filename(self, filename):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
118
        """True if filename is the name of a path which is reserved for
119
        controldirs.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
120
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
121
        :param filename: A filename within the root transport of this
122
            controldir.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
123
124
        This is true IF and ONLY IF the filename is part of the namespace reserved
125
        for bzr control dirs. Currently this is the '.bzr' directory in the root
126
        of the root_transport. it is expected that plugins will need to extend
127
        this in the future - for instance to make bzr talk with svn working
128
        trees.
129
        """
130
        raise NotImplementedError(self.is_control_filename)
131
132
    def needs_format_conversion(self, format=None):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
133
        """Return true if this controldir needs convert_format run on it.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
134
135
        For instance, if the repository format is out of date but the
136
        branch and working tree are not, this should return True.
137
138
        :param format: Optional parameter indicating a specific desired
139
                       format we plan to arrive at.
140
        """
141
        raise NotImplementedError(self.needs_format_conversion)
142
5688.1.1 by Jelmer Vernooij
Add a stub for ControlDir.create_repository.
143
    def create_repository(self, shared=False):
144
        """Create a new repository in this control directory.
145
146
        :param shared: If a shared repository should be created
147
        :return: The newly created repository
148
        """
149
        raise NotImplementedError(self.create_repository)
150
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
151
    def destroy_repository(self):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
152
        """Destroy the repository in this ControlDir."""
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
153
        raise NotImplementedError(self.destroy_repository)
154
5536.1.1 by Andrew Bennetts
Avoid reopening (and relocking) the same branches/repositories in ControlDir.sprout. Still a few rough edges, but the tests I've run are passing.
155
    def create_branch(self, name=None, repository=None):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
156
        """Create a branch in this ControlDir.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
157
158
        :param name: Name of the colocated branch to create, None for
159
            the default branch.
160
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
161
        The controldirs format will control what branch format is created.
162
        For more control see BranchFormatXX.create(a_controldir).
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
163
        """
164
        raise NotImplementedError(self.create_branch)
165
166
    def destroy_branch(self, name=None):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
167
        """Destroy a branch in this ControlDir.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
168
169
        :param name: Name of the branch to destroy, None for the default 
170
            branch.
171
        """
172
        raise NotImplementedError(self.destroy_branch)
173
174
    def create_workingtree(self, revision_id=None, from_branch=None,
175
        accelerator_tree=None, hardlink=False):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
176
        """Create a working tree at this ControlDir.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
177
178
        :param revision_id: create it as of this revision id.
5363.2.17 by Jelmer Vernooij
merge bzr.dev.
179
        :param from_branch: override controldir branch 
180
            (for lightweight checkouts)
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
181
        :param accelerator_tree: A tree which can be used for retrieving file
182
            contents more quickly than the revision tree, i.e. a workingtree.
183
            The revision tree will be used for cases where accelerator_tree's
184
            content is different.
185
        """
186
        raise NotImplementedError(self.create_workingtree)
187
188
    def destroy_workingtree(self):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
189
        """Destroy the working tree at this ControlDir.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
190
191
        Formats that do not support this may raise UnsupportedOperation.
192
        """
193
        raise NotImplementedError(self.destroy_workingtree)
194
195
    def destroy_workingtree_metadata(self):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
196
        """Destroy the control files for the working tree at this ControlDir.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
197
198
        The contents of working tree files are not affected.
199
        Formats that do not support this may raise UnsupportedOperation.
200
        """
201
        raise NotImplementedError(self.destroy_workingtree_metadata)
202
203
    def get_branch_reference(self, name=None):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
204
        """Return the referenced URL for the branch in this controldir.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
205
206
        :param name: Optional colocated branch name
207
        :raises NotBranchError: If there is no Branch.
208
        :raises NoColocatedBranchSupport: If a branch name was specified
209
            but colocated branches are not supported.
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
210
        :return: The URL the branch in this controldir references if it is a
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
211
            reference branch, or None for regular branches.
212
        """
213
        if name is not None:
214
            raise errors.NoColocatedBranchSupport(self)
215
        return None
216
217
    def open_branch(self, name=None, unsupported=False,
218
                    ignore_fallbacks=False):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
219
        """Open the branch object at this ControlDir if one is present.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
220
221
        If unsupported is True, then no longer supported branch formats can
222
        still be opened.
223
224
        TODO: static convenience version of this?
225
        """
226
        raise NotImplementedError(self.open_branch)
227
228
    def open_repository(self, _unsupported=False):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
229
        """Open the repository object at this ControlDir if one is present.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
230
231
        This will not follow the Branch object pointer - it's strictly a direct
232
        open facility. Most client code should use open_branch().repository to
233
        get at a repository.
234
235
        :param _unsupported: a private parameter, not part of the api.
236
        TODO: static convenience version of this?
237
        """
238
        raise NotImplementedError(self.open_repository)
239
240
    def find_repository(self):
241
        """Find the repository that should be used.
242
243
        This does not require a branch as we use it to find the repo for
244
        new branches as well as to hook existing branches up to their
245
        repository.
246
        """
247
        raise NotImplementedError(self.find_repository)
248
249
    def open_workingtree(self, _unsupported=False,
250
                         recommend_upgrade=True, from_branch=None):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
251
        """Open the workingtree object at this ControlDir if one is present.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
252
253
        :param recommend_upgrade: Optional keyword parameter, when True (the
254
            default), emit through the ui module a recommendation that the user
255
            upgrade the working tree when the workingtree being opened is old
256
            (but still fully supported).
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
257
        :param from_branch: override controldir branch (for lightweight
258
            checkouts)
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
259
        """
260
        raise NotImplementedError(self.open_workingtree)
261
262
    def has_branch(self, name=None):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
263
        """Tell if this controldir contains a branch.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
264
265
        Note: if you're going to open the branch, you should just go ahead
266
        and try, and not ask permission first.  (This method just opens the
267
        branch and discards it, and that's somewhat expensive.)
268
        """
269
        try:
270
            self.open_branch(name)
271
            return True
272
        except errors.NotBranchError:
273
            return False
274
275
    def has_workingtree(self):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
276
        """Tell if this controldir contains a working tree.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
277
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
278
        This will still raise an exception if the controldir has a workingtree
279
        that is remote & inaccessible.
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
280
281
        Note: if you're going to open the working tree, you should just go ahead
282
        and try, and not ask permission first.  (This method just opens the
283
        workingtree and discards it, and that's somewhat expensive.)
284
        """
285
        try:
286
            self.open_workingtree(recommend_upgrade=False)
287
            return True
288
        except errors.NoWorkingTree:
289
            return False
290
291
    def cloning_metadir(self, require_stacking=False):
292
        """Produce a metadir suitable for cloning or sprouting with.
293
294
        These operations may produce workingtrees (yes, even though they're
295
        "cloning" something that doesn't have a tree), so a viable workingtree
296
        format must be selected.
297
298
        :require_stacking: If True, non-stackable formats will be upgraded
299
            to similar stackable formats.
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
300
        :returns: a ControlDirFormat with all component formats either set
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
301
            appropriately or set to None if that component should not be
302
            created.
303
        """
304
        raise NotImplementedError(self.cloning_metadir)
305
306
    def checkout_metadir(self):
307
        """Produce a metadir suitable for checkouts of this controldir."""
308
        return self.cloning_metadir()
309
310
    def sprout(self, url, revision_id=None, force_new_repo=False,
311
               recurse='down', possible_transports=None,
312
               accelerator_tree=None, hardlink=False, stacked=False,
313
               source_branch=None, create_tree_if_local=True):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
314
        """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.
315
        development.
316
317
        If url's last component does not exist, it will be created.
318
319
        Attributes related to the identity of the source branch like
320
        branch nickname will be cleaned, a working tree is created
321
        whether one existed before or not; and a local branch is always
322
        created.
323
324
        if revision_id is not None, then the clone operation may tune
325
            itself to download less data.
326
        :param accelerator_tree: A tree which can be used for retrieving file
327
            contents more quickly than the revision tree, i.e. a workingtree.
328
            The revision tree will be used for cases where accelerator_tree's
329
            content is different.
330
        :param hardlink: If true, hard-link files from accelerator_tree,
331
            where possible.
332
        :param stacked: If true, create a stacked branch referring to the
333
            location of this control directory.
334
        :param create_tree_if_local: If true, a working-tree will be created
335
            when working locally.
336
        """
5536.1.1 by Andrew Bennetts
Avoid reopening (and relocking) the same branches/repositories in ControlDir.sprout. Still a few rough edges, but the tests I've run are passing.
337
        operation = cleanup.OperationWithCleanups(self._sprout)
338
        return operation.run(url, revision_id=revision_id,
339
            force_new_repo=force_new_repo, recurse=recurse,
340
            possible_transports=possible_transports,
341
            accelerator_tree=accelerator_tree, hardlink=hardlink,
342
            stacked=stacked, source_branch=source_branch,
343
            create_tree_if_local=create_tree_if_local)
344
345
    def _sprout(self, op, url, revision_id=None, force_new_repo=False,
346
               recurse='down', possible_transports=None,
347
               accelerator_tree=None, hardlink=False, stacked=False,
348
               source_branch=None, create_tree_if_local=True):
349
        add_cleanup = op.add_cleanup
5535.4.23 by Andrew Bennetts
Move FetchSpecFactory and TargetRepoKinds to bzrlib.fetch (from bzrlib.controldir).
350
        fetch_spec_factory = fetch.FetchSpecFactory()
5535.3.10 by Andrew Bennetts
Refactor a little bit of complexity out of sprout into a new object.
351
        if revision_id is not None:
352
            fetch_spec_factory.add_revision_ids([revision_id])
5535.4.18 by Andrew Bennetts
Rename source_branch_stop_revision to source_branch_stop_revision_id.
353
            fetch_spec_factory.source_branch_stop_revision_id = revision_id
5609.9.1 by Martin
Blindly change all users of get_transport to address the function via the transport module
354
        target_transport = _mod_transport.get_transport(url,
355
            possible_transports)
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
356
        target_transport.ensure_base()
357
        cloning_format = self.cloning_metadir(stacked)
358
        # Create/update the result branch
359
        result = cloning_format.initialize_on_transport(target_transport)
5535.3.12 by Andrew Bennetts
Shift more complexity out of sprout.
360
        source_branch, source_repository = self._find_source_repo(
361
            add_cleanup, source_branch)
5535.4.10 by Andrew Bennetts
Add a test, fix a bug and XXX it covers.
362
        fetch_spec_factory.source_branch = source_branch
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
363
        # if a stacked branch wasn't requested, we don't create one
364
        # even if the origin was stacked
5535.3.12 by Andrew Bennetts
Shift more complexity out of sprout.
365
        if stacked and source_branch is not None:
366
            stacked_branch_url = self.root_transport.base
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
367
        else:
5535.3.12 by Andrew Bennetts
Shift more complexity out of sprout.
368
            stacked_branch_url = None
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
369
        repository_policy = result.determine_repository_policy(
370
            force_new_repo, stacked_branch_url, require_stacking=stacked)
371
        result_repo, is_new_repo = repository_policy.acquire_repository()
5536.1.1 by Andrew Bennetts
Avoid reopening (and relocking) the same branches/repositories in ControlDir.sprout. Still a few rough edges, but the tests I've run are passing.
372
        add_cleanup(result_repo.lock_write().unlock)
5535.3.12 by Andrew Bennetts
Shift more complexity out of sprout.
373
        fetch_spec_factory.source_repo = source_repository
5535.3.10 by Andrew Bennetts
Refactor a little bit of complexity out of sprout into a new object.
374
        fetch_spec_factory.target_repo = result_repo
5535.3.12 by Andrew Bennetts
Shift more complexity out of sprout.
375
        if stacked or (len(result_repo._fallback_repositories) != 0):
5535.4.23 by Andrew Bennetts
Move FetchSpecFactory and TargetRepoKinds to bzrlib.fetch (from bzrlib.controldir).
376
            target_repo_kind = fetch.TargetRepoKinds.STACKED
5535.3.10 by Andrew Bennetts
Refactor a little bit of complexity out of sprout into a new object.
377
        elif is_new_repo:
5535.4.23 by Andrew Bennetts
Move FetchSpecFactory and TargetRepoKinds to bzrlib.fetch (from bzrlib.controldir).
378
            target_repo_kind = fetch.TargetRepoKinds.EMPTY
5535.3.1 by Andrew Bennetts
Initial hack to make 'bzr branch' (and BzrDir.sprout) fetch all tags, not just branch tip.
379
        else:
5535.4.23 by Andrew Bennetts
Move FetchSpecFactory and TargetRepoKinds to bzrlib.fetch (from bzrlib.controldir).
380
            target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
381
        fetch_spec_factory.target_repo_kind = target_repo_kind
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
382
        if source_repository is not None:
5535.3.10 by Andrew Bennetts
Refactor a little bit of complexity out of sprout into a new object.
383
            fetch_spec = fetch_spec_factory.make_fetch_spec()
5535.3.11 by Andrew Bennetts
Move some more complexity out of sprout.
384
            result_repo.fetch(source_repository, fetch_spec=fetch_spec)
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
385
386
        if source_branch is None:
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
387
            # this is for sprouting a controldir without a branch; is that
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
388
            # actually useful?
389
            # Not especially, but it's part of the contract.
390
            result_branch = result.create_branch()
391
        else:
392
            result_branch = source_branch.sprout(result,
5536.1.1 by Andrew Bennetts
Avoid reopening (and relocking) the same branches/repositories in ControlDir.sprout. Still a few rough edges, but the tests I've run are passing.
393
                revision_id=revision_id, repository_policy=repository_policy,
394
                repository=result_repo)
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
395
        mutter("created new branch %r" % (result_branch,))
396
397
        # Create/update the result working tree
398
        if (create_tree_if_local and
399
            isinstance(target_transport, local.LocalTransport) and
400
            (result_repo is None or result_repo.make_working_trees())):
401
            wt = result.create_workingtree(accelerator_tree=accelerator_tree,
5536.1.1 by Andrew Bennetts
Avoid reopening (and relocking) the same branches/repositories in ControlDir.sprout. Still a few rough edges, but the tests I've run are passing.
402
                hardlink=hardlink, from_branch=result_branch)
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
403
            wt.lock_write()
404
            try:
405
                if wt.path2id('') is None:
406
                    try:
407
                        wt.set_root_id(self.open_workingtree.get_root_id())
408
                    except errors.NoWorkingTree:
409
                        pass
410
            finally:
411
                wt.unlock()
412
        else:
413
            wt = None
414
        if recurse == 'down':
5535.3.8 by Andrew Bennetts
Remove a little repetition from sprout.
415
            basis = None
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
416
            if wt is not None:
417
                basis = wt.basis_tree()
418
            elif result_branch is not None:
419
                basis = result_branch.basis_tree()
420
            elif source_branch is not None:
421
                basis = source_branch.basis_tree()
5535.3.8 by Andrew Bennetts
Remove a little repetition from sprout.
422
            if basis is not None:
423
                add_cleanup(basis.lock_read().unlock)
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
424
                subtrees = basis.iter_references()
425
            else:
426
                subtrees = []
5535.3.8 by Andrew Bennetts
Remove a little repetition from sprout.
427
            for path, file_id in subtrees:
428
                target = urlutils.join(url, urlutils.escape(path))
429
                sublocation = source_branch.reference_parent(file_id, path)
430
                sublocation.bzrdir.sprout(target,
431
                    basis.get_reference_revision(file_id, path),
432
                    force_new_repo=force_new_repo, recurse=recurse,
433
                    stacked=stacked)
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
434
        return result
435
5535.3.12 by Andrew Bennetts
Shift more complexity out of sprout.
436
    def _find_source_repo(self, add_cleanup, source_branch):
437
        """Find the source branch and repo for a sprout operation.
438
        
439
        This is helper intended for use by _sprout.
440
441
        :returns: (source_branch, source_repository).  Either or both may be
442
            None.  If not None, they will be read-locked (and their unlock(s)
443
            scheduled via the add_cleanup param).
444
        """
445
        if source_branch is not None:
446
            add_cleanup(source_branch.lock_read().unlock)
5535.4.9 by Andrew Bennetts
Simplify code slightly.
447
            return source_branch, source_branch.repository
448
        try:
449
            source_branch = self.open_branch()
5535.3.12 by Andrew Bennetts
Shift more complexity out of sprout.
450
            source_repository = source_branch.repository
5535.4.9 by Andrew Bennetts
Simplify code slightly.
451
        except errors.NotBranchError:
452
            source_branch = None
5535.3.12 by Andrew Bennetts
Shift more complexity out of sprout.
453
            try:
5535.4.9 by Andrew Bennetts
Simplify code slightly.
454
                source_repository = self.open_repository()
455
            except errors.NoRepositoryPresent:
456
                source_repository = None
5535.3.12 by Andrew Bennetts
Shift more complexity out of sprout.
457
            else:
5535.4.9 by Andrew Bennetts
Simplify code slightly.
458
                add_cleanup(source_repository.lock_read().unlock)
459
        else:
460
            add_cleanup(source_branch.lock_read().unlock)
5535.3.12 by Andrew Bennetts
Shift more complexity out of sprout.
461
        return source_branch, source_repository
462
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
463
    def push_branch(self, source, revision_id=None, overwrite=False, 
464
        remember=False, create_prefix=False):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
465
        """Push the source branch into this ControlDir."""
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
466
        br_to = None
467
        # If we can open a branch, use its direct repository, otherwise see
468
        # if there is a repository without a branch.
469
        try:
470
            br_to = self.open_branch()
471
        except errors.NotBranchError:
472
            # Didn't find a branch, can we find a repository?
473
            repository_to = self.find_repository()
474
        else:
475
            # Found a branch, so we must have found a repository
476
            repository_to = br_to.repository
477
478
        push_result = PushResult()
479
        push_result.source_branch = source
480
        if br_to is None:
481
            # We have a repository but no branch, copy the revisions, and then
482
            # create a branch.
483
            repository_to.fetch(source.repository, revision_id=revision_id)
484
            br_to = source.clone(self, revision_id=revision_id)
485
            if source.get_push_location() is None or remember:
486
                source.set_push_location(br_to.base)
487
            push_result.stacked_on = None
488
            push_result.branch_push_result = None
489
            push_result.old_revno = None
490
            push_result.old_revid = _mod_revision.NULL_REVISION
491
            push_result.target_branch = br_to
492
            push_result.master_branch = None
493
            push_result.workingtree_updated = False
494
        else:
495
            # We have successfully opened the branch, remember if necessary:
496
            if source.get_push_location() is None or remember:
497
                source.set_push_location(br_to.base)
498
            try:
499
                tree_to = self.open_workingtree()
500
            except errors.NotLocalUrl:
501
                push_result.branch_push_result = source.push(br_to, 
502
                    overwrite, stop_revision=revision_id)
503
                push_result.workingtree_updated = False
504
            except errors.NoWorkingTree:
505
                push_result.branch_push_result = source.push(br_to,
506
                    overwrite, stop_revision=revision_id)
507
                push_result.workingtree_updated = None # Not applicable
508
            else:
509
                tree_to.lock_write()
510
                try:
511
                    push_result.branch_push_result = source.push(
512
                        tree_to.branch, overwrite, stop_revision=revision_id)
513
                    tree_to.update()
514
                finally:
515
                    tree_to.unlock()
516
                push_result.workingtree_updated = True
517
            push_result.old_revno = push_result.branch_push_result.old_revno
518
            push_result.old_revid = push_result.branch_push_result.old_revid
519
            push_result.target_branch = \
520
                push_result.branch_push_result.target_branch
521
        return push_result
522
5363.2.19 by Jelmer Vernooij
Put _get_tree_branch onto ControlDir.
523
    def _get_tree_branch(self, name=None):
524
        """Return the branch and tree, if any, for this bzrdir.
525
526
        :param name: Name of colocated branch to open.
527
528
        Return None for tree if not present or inaccessible.
529
        Raise NotBranchError if no branch is present.
530
        :return: (tree, branch)
531
        """
532
        try:
533
            tree = self.open_workingtree()
534
        except (errors.NoWorkingTree, errors.NotLocalUrl):
535
            tree = None
536
            branch = self.open_branch(name=name)
537
        else:
538
            if name is not None:
539
                branch = self.open_branch(name=name)
540
            else:
541
                branch = tree.branch
542
        return tree, branch
543
5363.2.24 by Jelmer Vernooij
Move get_config to ControlDir.
544
    def get_config(self):
545
        """Get configuration for this ControlDir."""
546
        raise NotImplementedError(self.get_config)
5363.2.19 by Jelmer Vernooij
Put _get_tree_branch onto ControlDir.
547
5363.2.28 by Jelmer Vernooij
Move clone() onto ControlDir.clone(), add ControlDir.clone_on_transport() stub.
548
    def check_conversion_target(self, target_format):
549
        """Check that a bzrdir as a whole can be converted to a new format."""
550
        raise NotImplementedError(self.check_conversion_target)
551
552
    def clone(self, url, revision_id=None, force_new_repo=False,
553
              preserve_stacking=False):
554
        """Clone this bzrdir and its contents to url verbatim.
555
556
        :param url: The url create the clone at.  If url's last component does
557
            not exist, it will be created.
558
        :param revision_id: The tip revision-id to use for any branch or
559
            working tree.  If not None, then the clone operation may tune
560
            itself to download less data.
561
        :param force_new_repo: Do not use a shared repository for the target
562
                               even if one is available.
563
        :param preserve_stacking: When cloning a stacked branch, stack the
564
            new branch on top of the other branch's stacked-on branch.
565
        """
5609.9.1 by Martin
Blindly change all users of get_transport to address the function via the transport module
566
        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.
567
                                       revision_id=revision_id,
568
                                       force_new_repo=force_new_repo,
569
                                       preserve_stacking=preserve_stacking)
570
571
    def clone_on_transport(self, transport, revision_id=None,
572
        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.
573
        create_prefix=False, use_existing_dir=True, no_tree=False):
5363.2.28 by Jelmer Vernooij
Move clone() onto ControlDir.clone(), add ControlDir.clone_on_transport() stub.
574
        """Clone this bzrdir and its contents to transport verbatim.
575
576
        :param transport: The transport for the location to produce the clone
577
            at.  If the target directory does not exist, it will be created.
578
        :param revision_id: The tip revision-id to use for any branch or
579
            working tree.  If not None, then the clone operation may tune
580
            itself to download less data.
581
        :param force_new_repo: Do not use a shared repository for the target,
582
                               even if one is available.
583
        :param preserve_stacking: When cloning a stacked branch, stack the
584
            new branch on top of the other branch's stacked-on branch.
585
        :param create_prefix: Create any missing directories leading up to
586
            to_transport.
587
        :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.
588
        :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.
589
        """
590
        raise NotImplementedError(self.clone_on_transport)
591
5363.2.2 by Jelmer Vernooij
Rename per_bzrdir => per_controldir.
592
5669.3.9 by Jelmer Vernooij
Consistent naming.
593
class ControlComponentFormat(object):
5669.3.8 by Jelmer Vernooij
Refactor, move to bzrlib.controldir.
594
    """A component that can live inside of a .bzr meta directory."""
595
596
    def get_format_string(self):
5669.3.9 by Jelmer Vernooij
Consistent naming.
597
        """Return the format of this format, if usable in meta directories."""
5669.3.8 by Jelmer Vernooij
Refactor, move to bzrlib.controldir.
598
        raise NotImplementedError(self.get_format_string)
599
5669.3.9 by Jelmer Vernooij
Consistent naming.
600
    def get_format_description(self):
601
        """Return the short description for this format."""
602
        raise NotImplementedError(self.get_format_description)
603
604
605
class ControlComponentFormatRegistry(registry.FormatRegistry):
606
    """A registry for control components (branch, workingtree, repository)."""
5669.3.8 by Jelmer Vernooij
Refactor, move to bzrlib.controldir.
607
608
    def __init__(self, other_registry=None):
5669.3.9 by Jelmer Vernooij
Consistent naming.
609
        super(ControlComponentFormatRegistry, self).__init__(other_registry)
5669.3.8 by Jelmer Vernooij
Refactor, move to bzrlib.controldir.
610
        self._extra_formats = []
611
612
    def register(self, format):
613
        """Register a new format."""
5669.3.9 by Jelmer Vernooij
Consistent naming.
614
        super(ControlComponentFormatRegistry, self).register(
5669.3.8 by Jelmer Vernooij
Refactor, move to bzrlib.controldir.
615
            format.get_format_string(), format)
616
617
    def remove(self, format):
618
        """Remove a registered format."""
5669.3.9 by Jelmer Vernooij
Consistent naming.
619
        super(ControlComponentFormatRegistry, self).remove(
5669.3.8 by Jelmer Vernooij
Refactor, move to bzrlib.controldir.
620
            format.get_format_string())
621
622
    def register_extra(self, format):
623
        """Register a format that can not be used in a metadir.
624
625
        This is mainly useful to allow custom repository formats, such as older
626
        Bazaar formats and foreign formats, to be tested.
627
        """
628
        self._extra_formats.append(registry._ObjectGetter(format))
629
630
    def remove_extra(self, format):
631
        """Remove an extra format.
632
        """
633
        self._extra_formats.remove(registry._ObjectGetter(format))
634
635
    def register_extra_lazy(self, module_name, member_name):
636
        """Register a format lazily.
637
        """
638
        self._extra_formats.append(
639
            registry._LazyObjectGetter(module_name, member_name))
640
641
    def _get_extra(self):
642
        """Return all "extra" formats, not usable in meta directories."""
643
        result = []
644
        for getter in self._extra_formats:
645
            f = getter.get_obj()
646
            if callable(f):
647
                f = f()
648
            result.append(f)
649
        return result
650
651
    def _get_all(self):
652
        """Return all formats, even those not usable in metadirs.
653
        """
654
        result = []
655
        for name in self.keys():
656
            fmt = self.get(name)
657
            if callable(fmt):
658
                fmt = fmt()
659
            result.append(fmt)
660
        return result + self._get_extra()
661
5676.1.6 by Jelmer Vernooij
Add _ObjGetter.get_module.
662
    def _get_all_modules(self):
663
        """Return a set of the modules providing objects."""
664
        modules = set()
665
        for name in self.keys():
666
            modules.add(self._get_module(name))
667
        for getter in self._extra_formats:
668
            modules.add(getter.get_module())
669
        return modules
670
5669.3.8 by Jelmer Vernooij
Refactor, move to bzrlib.controldir.
671
5692.1.1 by Jelmer Vernooij
Move Converter (which is generic) from bzrlib.bzrdir to bzrlib.controldir.
672
class Converter(object):
673
    """Converts a disk format object from one format to another."""
674
675
    def convert(self, to_convert, pb):
676
        """Perform the conversion of to_convert, giving feedback via pb.
677
678
        :param to_convert: The disk object to convert.
679
        :param pb: a progress bar to use for progress information.
680
        """
681
682
    def step(self, message):
683
        """Update the pb by a step."""
684
        self.count +=1
685
        self.pb.update(message, self.count, self.total)
686
687
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
688
class ControlDirFormat(object):
689
    """An encapsulation of the initialization and open routines for a format.
690
691
    Formats provide three things:
692
     * An initialization routine,
693
     * a format string,
694
     * an open routine.
695
696
    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.
697
    during controldir opening. These should be subclasses of ControlDirFormat
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
698
    for consistency.
699
700
    Once a format is deprecated, just deprecate the initialize and open
701
    methods on the format class. Do not deprecate the object, as the
702
    object will be created every system load.
703
704
    :cvar colocated_branches: Whether this formats supports colocated branches.
5393.4.3 by Jelmer Vernooij
Consistent spelling.
705
    :cvar supports_workingtrees: This control directory can co-exist with a
5393.4.2 by Jelmer Vernooij
Use cvar.
706
        working tree.
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
707
    """
708
709
    _default_format = None
5363.2.4 by Jelmer Vernooij
Introduce probers, use controldir in a couple more places.
710
    """The default format used for new control directories."""
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
711
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
712
    _server_probers = []
713
    """The registered server format probers, e.g. RemoteBzrProber.
714
715
    This is a list of Prober-derived classes.
716
    """
717
718
    _probers = []
719
    """The registered format probers, e.g. BzrProber.
720
721
    This is a list of Prober-derived classes.
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
722
    """
723
724
    colocated_branches = False
725
    """Whether co-located branches are supported for this control dir format.
726
    """
727
5393.4.3 by Jelmer Vernooij
Consistent spelling.
728
    supports_workingtrees = True
5669.1.1 by Jelmer Vernooij
Remove some dependencies on weave formats from bt.test_bzrdir.
729
    """Whether working trees can exist in control directories of this format.
730
    """
5393.4.1 by Jelmer Vernooij
Add ControlDirFormat.supports_workingtrees.
731
5673.1.3 by Jelmer Vernooij
Change flexible_components to fixed_components.
732
    fixed_components = False
733
    """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
734
    """
735
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
736
    def get_format_description(self):
737
        """Return the short description for this format."""
738
        raise NotImplementedError(self.get_format_description)
739
740
    def get_converter(self, format=None):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
741
        """Return the converter to use to convert controldirs needing converts.
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
742
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
743
        This returns a bzrlib.controldir.Converter object.
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
744
745
        This should return the best upgrader to step this format towards the
746
        current default format. In the case of plugins we can/should provide
747
        some means for them to extend the range of returnable converters.
748
749
        :param format: Optional format to override the default format of the
750
                       library.
751
        """
752
        raise NotImplementedError(self.get_converter)
753
754
    def is_supported(self):
755
        """Is this format supported?
756
757
        Supported formats must be initializable and openable.
758
        Unsupported formats may not support initialization or committing or
759
        some other features depending on the reason for not being supported.
760
        """
761
        return True
762
763
    def same_model(self, target_format):
764
        return (self.repository_format.rich_root_data ==
765
            target_format.rich_root_data)
766
767
    @classmethod
5712.3.19 by Jelmer Vernooij
Raise exception from ControlDirFormat.register_format.
768
    def register_format(klass, format):
769
        """Register a format that does not use '.bzr' for its control dir.
770
771
        """
772
        raise errors.BzrError("ControlDirFormat.register_format() has been "
773
            "removed in Bazaar 2.4. Please upgrade your plugins.")
774
775
    @classmethod
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
776
    def register_prober(klass, prober):
777
        """Register a prober that can look for a control dir.
778
779
        """
780
        klass._probers.append(prober)
781
782
    @classmethod
783
    def unregister_prober(klass, prober):
784
        """Unregister a prober.
785
786
        """
787
        klass._probers.remove(prober)
788
789
    @classmethod
790
    def register_server_prober(klass, prober):
791
        """Register a control format prober for client-server environments.
792
793
        These probers will be used before ones registered with
794
        register_prober.  This gives implementations that decide to the
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
795
        chance to grab it before anything looks at the contents of the format
796
        file.
797
        """
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
798
        klass._server_probers.append(prober)
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
799
800
    def __str__(self):
801
        # Trim the newline
802
        return self.get_format_description().rstrip()
803
804
    @classmethod
805
    def known_formats(klass):
806
        """Return all the known formats.
807
        """
5712.3.14 by Jelmer Vernooij
Add Prober.known_formats.
808
        result = set()
5712.3.15 by Jelmer Vernooij
Remove unused register format functions.
809
        for prober_kls in klass._probers + klass._server_probers:
810
            result.update(prober_kls.known_formats())
5712.3.14 by Jelmer Vernooij
Add Prober.known_formats.
811
        return result
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
812
813
    @classmethod
814
    def find_format(klass, transport, _server_formats=True):
815
        """Return the format present at transport."""
816
        if _server_formats:
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
817
            _probers = klass._server_probers + klass._probers
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
818
        else:
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
819
            _probers = klass._probers
5363.2.4 by Jelmer Vernooij
Introduce probers, use controldir in a couple more places.
820
        for prober_kls in _probers:
821
            prober = prober_kls()
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
822
            try:
5363.2.4 by Jelmer Vernooij
Introduce probers, use controldir in a couple more places.
823
                return prober.probe_transport(transport)
5363.2.3 by Jelmer Vernooij
Add ControlDirFormat.
824
            except errors.NotBranchError:
825
                # this format does not find a control dir here.
826
                pass
827
        raise errors.NotBranchError(path=transport.base)
828
5363.2.4 by Jelmer Vernooij
Introduce probers, use controldir in a couple more places.
829
    def initialize(self, url, possible_transports=None):
830
        """Create a control dir at this url and return an opened copy.
831
832
        While not deprecated, this method is very specific and its use will
833
        lead to many round trips to setup a working environment. See
834
        initialize_on_transport_ex for a [nearly] all-in-one method.
835
836
        Subclasses should typically override initialize_on_transport
837
        instead of this method.
838
        """
5609.9.1 by Martin
Blindly change all users of get_transport to address the function via the transport module
839
        return self.initialize_on_transport(
840
            _mod_transport.get_transport(url, possible_transports))
841
5363.2.4 by Jelmer Vernooij
Introduce probers, use controldir in a couple more places.
842
    def initialize_on_transport(self, transport):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
843
        """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.
844
        raise NotImplementedError(self.initialize_on_transport)
845
846
    def initialize_on_transport_ex(self, transport, use_existing_dir=False,
847
        create_prefix=False, force_new_repo=False, stacked_on=None,
848
        stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
849
        shared_repo=False, vfs_only=False):
850
        """Create this format on transport.
851
852
        The directory to initialize will be created.
853
854
        :param force_new_repo: Do not use a shared repository for the target,
855
                               even if one is available.
856
        :param create_prefix: Create any missing directories leading up to
857
            to_transport.
858
        :param use_existing_dir: Use an existing directory if one exists.
859
        :param stacked_on: A url to stack any created branch on, None to follow
860
            any target stacking policy.
861
        :param stack_on_pwd: If stack_on is relative, the location it is
862
            relative to.
863
        :param repo_format_name: If non-None, a repository will be
864
            made-or-found. Should none be found, or if force_new_repo is True
865
            the repo_format_name is used to select the format of repository to
866
            create.
867
        :param make_working_trees: Control the setting of make_working_trees
868
            for a new shared repository when one is made. None to use whatever
869
            default the format has.
870
        :param shared_repo: Control whether made repositories are shared or
871
            not.
872
        :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.
873
        :return: repo, controldir, require_stacking, repository_policy. repo is
874
            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.
875
            require_stacking is the result of examining the stacked_on
876
            parameter and any stacking policy found for the target.
877
        """
878
        raise NotImplementedError(self.initialize_on_transport_ex)
879
880
    def network_name(self):
881
        """A simple byte string uniquely identifying this format for RPC calls.
882
883
        Bzr control formats use this disk format string to identify the format
884
        over the wire. Its possible that other control formats have more
885
        complex detection requirements, so we permit them to use any unique and
886
        immutable string they desire.
887
        """
888
        raise NotImplementedError(self.network_name)
889
890
    def open(self, transport, _found=False):
891
        """Return an instance of this format for the dir transport points at.
892
        """
893
        raise NotImplementedError(self.open)
894
895
    @classmethod
896
    def _set_default_format(klass, format):
897
        """Set default format (for testing behavior of defaults only)"""
898
        klass._default_format = format
899
900
    @classmethod
901
    def get_default_format(klass):
902
        """Return the current default format."""
903
        return klass._default_format
904
905
906
class Prober(object):
5712.3.22 by Jelmer Vernooij
Add some notes about probers.
907
    """Abstract class that can be used to detect a particular kind of
5363.2.8 by Jelmer Vernooij
Docstrings.
908
    control directory.
909
5712.3.22 by Jelmer Vernooij
Add some notes about probers.
910
    At the moment this just contains a single method to probe a particular
911
    transport, but it may be extended in the future to e.g. avoid
5363.2.8 by Jelmer Vernooij
Docstrings.
912
    multiple levels of probing for Subversion repositories.
5712.3.22 by Jelmer Vernooij
Add some notes about probers.
913
914
    See BzrProber and RemoteBzrProber in bzrlib.bzrdir for the
915
    probers that detect .bzr/ directories and Bazaar smart servers,
916
    respectively.
917
918
    Probers should be registered using the register_server_prober or
919
    register_prober methods on ControlDirFormat.
5363.2.8 by Jelmer Vernooij
Docstrings.
920
    """
5363.2.4 by Jelmer Vernooij
Introduce probers, use controldir in a couple more places.
921
922
    def probe_transport(self, transport):
5363.2.8 by Jelmer Vernooij
Docstrings.
923
        """Return the controldir style format present in a directory.
924
925
        :raise UnknownFormatError: If a control dir was found but is
926
            in an unknown format.
927
        :raise NotBranchError: If no control directory was found.
928
        :return: A ControlDirFormat instance.
929
        """
5363.2.5 by Jelmer Vernooij
Add dummy foreign prober.
930
        raise NotImplementedError(self.probe_transport)
5363.2.4 by Jelmer Vernooij
Introduce probers, use controldir in a couple more places.
931
5712.3.15 by Jelmer Vernooij
Remove unused register format functions.
932
    @classmethod
933
    def known_formats(cls):
5712.3.13 by Jelmer Vernooij
Add Prober.known_formats().
934
        """Return the control dir formats known by this prober.
935
5712.3.21 by Jelmer Vernooij
Add note about sets.
936
        Multiple probers can return the same formats, so this should
937
        return a set.
938
5712.3.13 by Jelmer Vernooij
Add Prober.known_formats().
939
        :return: A set of known formats.
940
        """
5712.3.15 by Jelmer Vernooij
Remove unused register format functions.
941
        raise NotImplementedError(cls.known_formats)
5712.3.13 by Jelmer Vernooij
Add Prober.known_formats().
942
5363.2.4 by Jelmer Vernooij
Introduce probers, use controldir in a couple more places.
943
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
944
class ControlDirFormatInfo(object):
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
945
946
    def __init__(self, native, deprecated, hidden, experimental):
947
        self.deprecated = deprecated
948
        self.native = native
949
        self.hidden = hidden
950
        self.experimental = experimental
951
952
953
class ControlDirFormatRegistry(registry.Registry):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
954
    """Registry of user-selectable ControlDir subformats.
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
955
956
    Differs from ControlDirFormat._formats in that it provides sub-formats,
5669.3.8 by Jelmer Vernooij
Refactor, move to bzrlib.controldir.
957
    e.g. BzrDirMeta1 with weave repository.  Also, it's more user-oriented.
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
958
    """
959
960
    def __init__(self):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
961
        """Create a ControlDirFormatRegistry."""
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
962
        self._aliases = set()
963
        self._registration_order = list()
964
        super(ControlDirFormatRegistry, self).__init__()
965
966
    def aliases(self):
967
        """Return a set of the format names which are aliases."""
968
        return frozenset(self._aliases)
969
970
    def register(self, key, factory, help, native=True, deprecated=False,
971
                 hidden=False, experimental=False, alias=False):
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
972
        """Register a ControlDirFormat factory.
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
973
974
        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.
975
        It must produce an instance of the ControlDirFormat when called.
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
976
977
        This function mainly exists to prevent the info object from being
978
        supplied directly.
979
        """
980
        registry.Registry.register(self, key, factory, help,
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
981
            ControlDirFormatInfo(native, deprecated, hidden, experimental))
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
982
        if alias:
983
            self._aliases.add(key)
984
        self._registration_order.append(key)
985
986
    def register_lazy(self, key, module_name, member_name, help, native=True,
987
        deprecated=False, hidden=False, experimental=False, alias=False):
988
        registry.Registry.register_lazy(self, key, module_name, member_name,
5363.2.16 by Jelmer Vernooij
Switch naming in a couple more places.
989
            help, ControlDirFormatInfo(native, deprecated, hidden, experimental))
5363.2.6 by Jelmer Vernooij
Add ControlDirFormat.{un,}register_{server_,}prober.
990
        if alias:
991
            self._aliases.add(key)
992
        self._registration_order.append(key)
993
994
    def set_default(self, key):
995
        """Set the 'default' key to be a clone of the supplied key.
996
997
        This method must be called once and only once.
998
        """
999
        registry.Registry.register(self, 'default', self.get(key),
1000
            self.get_help(key), info=self.get_info(key))
1001
        self._aliases.add('default')
1002
1003
    def set_default_repository(self, key):
1004
        """Set the FormatRegistry default and Repository default.
1005
1006
        This is a transitional method while Repository.set_default_format
1007
        is deprecated.
1008
        """
1009
        if 'default' in self:
1010
            self.remove('default')
1011
        self.set_default(key)
1012
        format = self.get('default')()
1013
1014
    def make_bzrdir(self, key):
1015
        return self.get(key)()
1016
1017
    def help_topic(self, topic):
1018
        output = ""
1019
        default_realkey = None
1020
        default_help = self.get_help('default')
1021
        help_pairs = []
1022
        for key in self._registration_order:
1023
            if key == 'default':
1024
                continue
1025
            help = self.get_help(key)
1026
            if help == default_help:
1027
                default_realkey = key
1028
            else:
1029
                help_pairs.append((key, help))
1030
1031
        def wrapped(key, help, info):
1032
            if info.native:
1033
                help = '(native) ' + help
1034
            return ':%s:\n%s\n\n' % (key,
1035
                textwrap.fill(help, initial_indent='    ',
1036
                    subsequent_indent='    ',
1037
                    break_long_words=False))
1038
        if default_realkey is not None:
1039
            output += wrapped(default_realkey, '(default) %s' % default_help,
1040
                              self.get_info('default'))
1041
        deprecated_pairs = []
1042
        experimental_pairs = []
1043
        for key, help in help_pairs:
1044
            info = self.get_info(key)
1045
            if info.hidden:
1046
                continue
1047
            elif info.deprecated:
1048
                deprecated_pairs.append((key, help))
1049
            elif info.experimental:
1050
                experimental_pairs.append((key, help))
1051
            else:
1052
                output += wrapped(key, help, info)
1053
        output += "\nSee :doc:`formats-help` for more about storage formats."
1054
        other_output = ""
1055
        if len(experimental_pairs) > 0:
1056
            other_output += "Experimental formats are shown below.\n\n"
1057
            for key, help in experimental_pairs:
1058
                info = self.get_info(key)
1059
                other_output += wrapped(key, help, info)
1060
        else:
1061
            other_output += \
1062
                "No experimental formats are available.\n\n"
1063
        if len(deprecated_pairs) > 0:
1064
            other_output += "\nDeprecated formats are shown below.\n\n"
1065
            for key, help in deprecated_pairs:
1066
                info = self.get_info(key)
1067
                other_output += wrapped(key, help, info)
1068
        else:
1069
            other_output += \
1070
                "\nNo deprecated formats are available.\n\n"
1071
        other_output += \
1072
                "\nSee :doc:`formats-help` for more about storage formats."
1073
1074
        if topic == 'other-formats':
1075
            return other_output
1076
        else:
1077
            return output
1078
1079
1080
# Please register new formats after old formats so that formats
1081
# appear in chronological order and format descriptions can build
1082
# on previous ones.
1083
format_registry = ControlDirFormatRegistry()
5363.2.23 by Jelmer Vernooij
Move network_format_registry to bzrlib.controldir.
1084
1085
network_format_registry = registry.FormatRegistry()
1086
"""Registry of formats indexed by their network name.
1087
1088
The network name for a ControlDirFormat is an identifier that can be used when
1089
referring to formats with smart server operations. See
1090
ControlDirFormat.network_name() for more detail.
1091
"""