/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: 2018-05-07 15:27:39 UTC
  • mto: This revision was merged to the branch mainline in revision 6958.
  • Revision ID: jelmer@jelmer.uk-20180507152739-fuv9z9r0yzi7ln3t
Specify source in .coveragerc.

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