~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/controldir.py

  • Committer: Jonathan Riddell
  • Date: 2011-09-20 11:01:37 UTC
  • mto: This revision was merged to the branch mainline in revision 6153.
  • Revision ID: jriddell@canonical.com-20110920110137-mrps089ulocx1skd
gettext() in plugin.py and hooks.py

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