/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/controldir.py

  • Committer: Vincent Ladeuil
  • Date: 2012-01-18 14:09:19 UTC
  • mto: This revision was merged to the branch mainline in revision 6468.
  • Revision ID: v.ladeuil+lp@free.fr-20120118140919-rlvdrhpc0nq1lbwi
Change set/remove to require a lock for the branch config files.

This means that tests (or any plugin for that matter) do not requires an
explicit lock on the branch anymore to change a single option. This also
means the optimisation becomes "opt-in" and as such won't be as
spectacular as it may be and/or harder to get right (nothing fails
anymore).

This reduces the diff by ~300 lines.

Code/tests that were updating more than one config option is still taking
a lock to at least avoid some IOs and demonstrate the benefits through
the decreased number of hpss calls.

The duplication between BranchStack and BranchOnlyStack will be removed
once the same sharing is in place for local config files, at which point
the Stack class itself may be able to host the changes.

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