/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to breezy/controldir.py

  • Committer: Robert Collins
  • Date: 2005-10-19 10:11:57 UTC
  • mfrom: (1185.16.78)
  • mto: This revision was merged to the branch mainline in revision 1470.
  • Revision ID: robertc@robertcollins.net-20051019101157-17438d311e746b4f
mergeĀ fromĀ upstream

Show diffs side-by-side

added added

removed removed

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