/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

Use global osutils, otherwise it creates a local var.

Which works, but causes us to run the import on every call.

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