/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/controldir.py

  • Committer: Vincent Ladeuil
  • Date: 2011-12-15 14:47:22 UTC
  • mto: This revision was merged to the branch mainline in revision 6377.
  • Revision ID: v.ladeuil+lp@free.fr-20111215144722-fie3up92mth126r5
Relax constraints on bzr log -rX..Y by falling back to the slower implementation when needed

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