~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/controldir.py

Major code cleanup.

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