/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to breezy/controldir.py

  • Committer: Robert Collins
  • Date: 2010-05-06 11:08:10 UTC
  • mto: This revision was merged to the branch mainline in revision 5223.
  • Revision ID: robertc@robertcollins.net-20100506110810-h3j07fh5gmw54s25
Cleaner matcher matching revised unlocking protocol.

Show diffs side-by-side

added added

removed removed

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