~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/controldir.py

  • Committer: Vincent Ladeuil
  • Date: 2012-01-16 14:45:48 UTC
  • mto: (6437.35.1 2.5.0-dev)
  • mto: This revision was merged to the branch mainline in revision 6439.
  • Revision ID: v.ladeuil+lp@free.fr-20120116144548-48mob8d7dee824uc
Tags: bzr-2.5b5
ReleaseĀ 2.5b5

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