/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/controldir.py

  • Committer: jelmer at samba
  • Date: 2011-10-11 10:21:35 UTC
  • mto: This revision was merged to the branch mainline in revision 6214.
  • Revision ID: jelmer@samba.org-20111011102135-0wuzm1stjwxehkft
Move convenience methods to ControlDir.

Show diffs side-by-side

added added

removed removed

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