~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/controldir.py

  • Committer: Jonathan Riddell
  • Date: 2011-05-16 11:27:37 UTC
  • mto: This revision was merged to the branch mainline in revision 5869.
  • Revision ID: jriddell@canonical.com-20110516112737-gep642p24rtzp3jt
userĀ guideĀ licence

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