/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: Jelmer Vernooij
  • Date: 2020-03-22 01:35:14 UTC
  • mfrom: (7490.7.6 work)
  • mto: This revision was merged to the branch mainline in revision 7499.
  • Revision ID: jelmer@jelmer.uk-20200322013514-7vw1ntwho04rcuj3
merge lp:brz/3.1.

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