~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/controldir.py

  • Committer: Martin Pool
  • Date: 2005-04-28 07:24:55 UTC
  • Revision ID: mbp@sourcefrog.net-20050428072453-7b99afa993a1e549
todo

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