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