~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/controldir.py

  • Committer: John Arbash Meinel
  • Author(s): Mark Hammond
  • Date: 2008-09-09 17:02:21 UTC
  • mto: This revision was merged to the branch mainline in revision 3697.
  • Revision ID: john@arbash-meinel.com-20080909170221-svim3jw2mrz0amp3
An updated transparent icon for bzr.

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