/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 breezy/controldir.py

  • Committer: Martin
  • Date: 2017-11-12 13:53:51 UTC
  • mto: This revision was merged to the branch mainline in revision 6810.
  • Revision ID: gzlist@googlemail.com-20171112135351-uyr1ncw7visg62c2
Apply 2to3 ws_comma fixer

Show diffs side-by-side

added added

removed removed

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