/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 bzrlib/controldir.py

Merge fetch-spec-everything-not-in-other.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2010, 2011 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
"""ControlDir is the basic control directory class.
 
18
 
 
19
The ControlDir class is the base for the control directory used
 
20
by all bzr and foreign formats. For the ".bzr" implementation,
 
21
see bzrlib.bzrdir.BzrDir.
 
22
 
 
23
"""
 
24
 
 
25
from bzrlib.lazy_import import lazy_import
 
26
lazy_import(globals(), """
 
27
import textwrap
 
28
 
 
29
from bzrlib import (
 
30
    cleanup,
 
31
    errors,
 
32
    fetch,
 
33
    graph,
 
34
    revision as _mod_revision,
 
35
    urlutils,
 
36
    )
 
37
from bzrlib.push import (
 
38
    PushResult,
 
39
    )
 
40
from bzrlib.trace import (
 
41
    mutter,
 
42
    )
 
43
from bzrlib.transport import (
 
44
    get_transport,
 
45
    local,
 
46
    )
 
47
 
 
48
""")
 
49
 
 
50
from bzrlib import registry
 
51
 
 
52
 
 
53
class ControlComponent(object):
 
54
    """Abstract base class for control directory components.
 
55
 
 
56
    This provides interfaces that are common across controldirs,
 
57
    repositories, branches, and workingtree control directories.
 
58
 
 
59
    They all expose two urls and transports: the *user* URL is the
 
60
    one that stops above the control directory (eg .bzr) and that
 
61
    should normally be used in messages, and the *control* URL is
 
62
    under that in eg .bzr/checkout and is used to read the control
 
63
    files.
 
64
 
 
65
    This can be used as a mixin and is intended to fit with
 
66
    foreign formats.
 
67
    """
 
68
 
 
69
    @property
 
70
    def control_transport(self):
 
71
        raise NotImplementedError
 
72
 
 
73
    @property
 
74
    def control_url(self):
 
75
        return self.control_transport.base
 
76
 
 
77
    @property
 
78
    def user_transport(self):
 
79
        raise NotImplementedError
 
80
 
 
81
    @property
 
82
    def user_url(self):
 
83
        return self.user_transport.base
 
84
 
 
85
 
 
86
class ControlDir(ControlComponent):
 
87
    """A control directory.
 
88
 
 
89
    While this represents a generic control directory, there are a few
 
90
    features that are present in this interface that are currently only
 
91
    supported by one of its implementations, BzrDir.
 
92
 
 
93
    These features (bound branches, stacked branches) are currently only
 
94
    supported by Bazaar, but could be supported by other version control
 
95
    systems as well. Implementations are required to raise the appropriate
 
96
    exceptions when an operation is requested that is not supported.
 
97
 
 
98
    This also makes life easier for API users who can rely on the
 
99
    implementation always allowing a particular feature to be requested but
 
100
    raising an exception when it is not supported, rather than requiring the
 
101
    API users to check for magic attributes to see what features are supported.
 
102
    """
 
103
 
 
104
    def can_convert_format(self):
 
105
        """Return true if this controldir is one whose format we can convert
 
106
        from."""
 
107
        return True
 
108
 
 
109
    def list_branches(self):
 
110
        """Return a sequence of all branches local to this control directory.
 
111
 
 
112
        """
 
113
        try:
 
114
            return [self.open_branch()]
 
115
        except (errors.NotBranchError, errors.NoRepositoryPresent):
 
116
            return []
 
117
 
 
118
    def is_control_filename(self, filename):
 
119
        """True if filename is the name of a path which is reserved for
 
120
        controldirs.
 
121
 
 
122
        :param filename: A filename within the root transport of this
 
123
            controldir.
 
124
 
 
125
        This is true IF and ONLY IF the filename is part of the namespace reserved
 
126
        for bzr control dirs. Currently this is the '.bzr' directory in the root
 
127
        of the root_transport. it is expected that plugins will need to extend
 
128
        this in the future - for instance to make bzr talk with svn working
 
129
        trees.
 
130
        """
 
131
        raise NotImplementedError(self.is_control_filename)
 
132
 
 
133
    def needs_format_conversion(self, format=None):
 
134
        """Return true if this controldir needs convert_format run on it.
 
135
 
 
136
        For instance, if the repository format is out of date but the
 
137
        branch and working tree are not, this should return True.
 
138
 
 
139
        :param format: Optional parameter indicating a specific desired
 
140
                       format we plan to arrive at.
 
141
        """
 
142
        raise NotImplementedError(self.needs_format_conversion)
 
143
 
 
144
    def destroy_repository(self):
 
145
        """Destroy the repository in this ControlDir."""
 
146
        raise NotImplementedError(self.destroy_repository)
 
147
 
 
148
    def create_branch(self, name=None, repository=None):
 
149
        """Create a branch in this ControlDir.
 
150
 
 
151
        :param name: Name of the colocated branch to create, None for
 
152
            the default branch.
 
153
 
 
154
        The controldirs format will control what branch format is created.
 
155
        For more control see BranchFormatXX.create(a_controldir).
 
156
        """
 
157
        raise NotImplementedError(self.create_branch)
 
158
 
 
159
    def destroy_branch(self, name=None):
 
160
        """Destroy a branch in this ControlDir.
 
161
 
 
162
        :param name: Name of the branch to destroy, None for the default 
 
163
            branch.
 
164
        """
 
165
        raise NotImplementedError(self.destroy_branch)
 
166
 
 
167
    def create_workingtree(self, revision_id=None, from_branch=None,
 
168
        accelerator_tree=None, hardlink=False):
 
169
        """Create a working tree at this ControlDir.
 
170
 
 
171
        :param revision_id: create it as of this revision id.
 
172
        :param from_branch: override controldir branch 
 
173
            (for lightweight checkouts)
 
174
        :param accelerator_tree: A tree which can be used for retrieving file
 
175
            contents more quickly than the revision tree, i.e. a workingtree.
 
176
            The revision tree will be used for cases where accelerator_tree's
 
177
            content is different.
 
178
        """
 
179
        raise NotImplementedError(self.create_workingtree)
 
180
 
 
181
    def destroy_workingtree(self):
 
182
        """Destroy the working tree at this ControlDir.
 
183
 
 
184
        Formats that do not support this may raise UnsupportedOperation.
 
185
        """
 
186
        raise NotImplementedError(self.destroy_workingtree)
 
187
 
 
188
    def destroy_workingtree_metadata(self):
 
189
        """Destroy the control files for the working tree at this ControlDir.
 
190
 
 
191
        The contents of working tree files are not affected.
 
192
        Formats that do not support this may raise UnsupportedOperation.
 
193
        """
 
194
        raise NotImplementedError(self.destroy_workingtree_metadata)
 
195
 
 
196
    def get_branch_reference(self, name=None):
 
197
        """Return the referenced URL for the branch in this controldir.
 
198
 
 
199
        :param name: Optional colocated branch name
 
200
        :raises NotBranchError: If there is no Branch.
 
201
        :raises NoColocatedBranchSupport: If a branch name was specified
 
202
            but colocated branches are not supported.
 
203
        :return: The URL the branch in this controldir references if it is a
 
204
            reference branch, or None for regular branches.
 
205
        """
 
206
        if name is not None:
 
207
            raise errors.NoColocatedBranchSupport(self)
 
208
        return None
 
209
 
 
210
    def get_branch_transport(self, branch_format, name=None):
 
211
        """Get the transport for use by branch format in this ControlDir.
 
212
 
 
213
        Note that bzr dirs that do not support format strings will raise
 
214
        IncompatibleFormat if the branch format they are given has
 
215
        a format string, and vice versa.
 
216
 
 
217
        If branch_format is None, the transport is returned with no
 
218
        checking. If it is not None, then the returned transport is
 
219
        guaranteed to point to an existing directory ready for use.
 
220
        """
 
221
        raise NotImplementedError(self.get_branch_transport)
 
222
 
 
223
    def get_repository_transport(self, repository_format):
 
224
        """Get the transport for use by repository format in this ControlDir.
 
225
 
 
226
        Note that bzr dirs that do not support format strings will raise
 
227
        IncompatibleFormat if the repository format they are given has
 
228
        a format string, and vice versa.
 
229
 
 
230
        If repository_format is None, the transport is returned with no
 
231
        checking. If it is not None, then the returned transport is
 
232
        guaranteed to point to an existing directory ready for use.
 
233
        """
 
234
        raise NotImplementedError(self.get_repository_transport)
 
235
 
 
236
    def get_workingtree_transport(self, tree_format):
 
237
        """Get the transport for use by workingtree format in this ControlDir.
 
238
 
 
239
        Note that bzr dirs that do not support format strings will raise
 
240
        IncompatibleFormat if the workingtree format they are given has a
 
241
        format string, and vice versa.
 
242
 
 
243
        If workingtree_format is None, the transport is returned with no
 
244
        checking. If it is not None, then the returned transport is
 
245
        guaranteed to point to an existing directory ready for use.
 
246
        """
 
247
        raise NotImplementedError(self.get_workingtree_transport)
 
248
 
 
249
    def open_branch(self, name=None, unsupported=False,
 
250
                    ignore_fallbacks=False):
 
251
        """Open the branch object at this ControlDir if one is present.
 
252
 
 
253
        If unsupported is True, then no longer supported branch formats can
 
254
        still be opened.
 
255
 
 
256
        TODO: static convenience version of this?
 
257
        """
 
258
        raise NotImplementedError(self.open_branch)
 
259
 
 
260
    def open_repository(self, _unsupported=False):
 
261
        """Open the repository object at this ControlDir if one is present.
 
262
 
 
263
        This will not follow the Branch object pointer - it's strictly a direct
 
264
        open facility. Most client code should use open_branch().repository to
 
265
        get at a repository.
 
266
 
 
267
        :param _unsupported: a private parameter, not part of the api.
 
268
        TODO: static convenience version of this?
 
269
        """
 
270
        raise NotImplementedError(self.open_repository)
 
271
 
 
272
    def find_repository(self):
 
273
        """Find the repository that should be used.
 
274
 
 
275
        This does not require a branch as we use it to find the repo for
 
276
        new branches as well as to hook existing branches up to their
 
277
        repository.
 
278
        """
 
279
        raise NotImplementedError(self.find_repository)
 
280
 
 
281
    def open_workingtree(self, _unsupported=False,
 
282
                         recommend_upgrade=True, from_branch=None):
 
283
        """Open the workingtree object at this ControlDir if one is present.
 
284
 
 
285
        :param recommend_upgrade: Optional keyword parameter, when True (the
 
286
            default), emit through the ui module a recommendation that the user
 
287
            upgrade the working tree when the workingtree being opened is old
 
288
            (but still fully supported).
 
289
        :param from_branch: override controldir branch (for lightweight
 
290
            checkouts)
 
291
        """
 
292
        raise NotImplementedError(self.open_workingtree)
 
293
 
 
294
    def has_branch(self, name=None):
 
295
        """Tell if this controldir contains a branch.
 
296
 
 
297
        Note: if you're going to open the branch, you should just go ahead
 
298
        and try, and not ask permission first.  (This method just opens the
 
299
        branch and discards it, and that's somewhat expensive.)
 
300
        """
 
301
        try:
 
302
            self.open_branch(name)
 
303
            return True
 
304
        except errors.NotBranchError:
 
305
            return False
 
306
 
 
307
    def has_workingtree(self):
 
308
        """Tell if this controldir contains a working tree.
 
309
 
 
310
        This will still raise an exception if the controldir has a workingtree
 
311
        that is remote & inaccessible.
 
312
 
 
313
        Note: if you're going to open the working tree, you should just go ahead
 
314
        and try, and not ask permission first.  (This method just opens the
 
315
        workingtree and discards it, and that's somewhat expensive.)
 
316
        """
 
317
        try:
 
318
            self.open_workingtree(recommend_upgrade=False)
 
319
            return True
 
320
        except errors.NoWorkingTree:
 
321
            return False
 
322
 
 
323
    def cloning_metadir(self, require_stacking=False):
 
324
        """Produce a metadir suitable for cloning or sprouting with.
 
325
 
 
326
        These operations may produce workingtrees (yes, even though they're
 
327
        "cloning" something that doesn't have a tree), so a viable workingtree
 
328
        format must be selected.
 
329
 
 
330
        :require_stacking: If True, non-stackable formats will be upgraded
 
331
            to similar stackable formats.
 
332
        :returns: a ControlDirFormat with all component formats either set
 
333
            appropriately or set to None if that component should not be
 
334
            created.
 
335
        """
 
336
        raise NotImplementedError(self.cloning_metadir)
 
337
 
 
338
    def checkout_metadir(self):
 
339
        """Produce a metadir suitable for checkouts of this controldir."""
 
340
        return self.cloning_metadir()
 
341
 
 
342
    def sprout(self, url, revision_id=None, force_new_repo=False,
 
343
               recurse='down', possible_transports=None,
 
344
               accelerator_tree=None, hardlink=False, stacked=False,
 
345
               source_branch=None, create_tree_if_local=True):
 
346
        """Create a copy of this controldir prepared for use as a new line of
 
347
        development.
 
348
 
 
349
        If url's last component does not exist, it will be created.
 
350
 
 
351
        Attributes related to the identity of the source branch like
 
352
        branch nickname will be cleaned, a working tree is created
 
353
        whether one existed before or not; and a local branch is always
 
354
        created.
 
355
 
 
356
        if revision_id is not None, then the clone operation may tune
 
357
            itself to download less data.
 
358
        :param accelerator_tree: A tree which can be used for retrieving file
 
359
            contents more quickly than the revision tree, i.e. a workingtree.
 
360
            The revision tree will be used for cases where accelerator_tree's
 
361
            content is different.
 
362
        :param hardlink: If true, hard-link files from accelerator_tree,
 
363
            where possible.
 
364
        :param stacked: If true, create a stacked branch referring to the
 
365
            location of this control directory.
 
366
        :param create_tree_if_local: If true, a working-tree will be created
 
367
            when working locally.
 
368
        """
 
369
        operation = cleanup.OperationWithCleanups(self._sprout)
 
370
        return operation.run(url, revision_id=revision_id,
 
371
            force_new_repo=force_new_repo, recurse=recurse,
 
372
            possible_transports=possible_transports,
 
373
            accelerator_tree=accelerator_tree, hardlink=hardlink,
 
374
            stacked=stacked, source_branch=source_branch,
 
375
            create_tree_if_local=create_tree_if_local)
 
376
 
 
377
    def _sprout(self, op, url, revision_id=None, force_new_repo=False,
 
378
               recurse='down', possible_transports=None,
 
379
               accelerator_tree=None, hardlink=False, stacked=False,
 
380
               source_branch=None, create_tree_if_local=True):
 
381
        add_cleanup = op.add_cleanup
 
382
        fetch_spec_factory = fetch.FetchSpecFactory()
 
383
        if revision_id is not None:
 
384
            fetch_spec_factory.add_revision_ids([revision_id])
 
385
            fetch_spec_factory.source_branch_stop_revision_id = revision_id
 
386
        target_transport = get_transport(url, possible_transports)
 
387
        target_transport.ensure_base()
 
388
        cloning_format = self.cloning_metadir(stacked)
 
389
        # Create/update the result branch
 
390
        result = cloning_format.initialize_on_transport(target_transport)
 
391
        source_branch, source_repository = self._find_source_repo(
 
392
            add_cleanup, source_branch)
 
393
        fetch_spec_factory.source_branch = source_branch
 
394
        # if a stacked branch wasn't requested, we don't create one
 
395
        # even if the origin was stacked
 
396
        if stacked and source_branch is not None:
 
397
            stacked_branch_url = self.root_transport.base
 
398
        else:
 
399
            stacked_branch_url = None
 
400
        repository_policy = result.determine_repository_policy(
 
401
            force_new_repo, stacked_branch_url, require_stacking=stacked)
 
402
        result_repo, is_new_repo = repository_policy.acquire_repository()
 
403
        add_cleanup(result_repo.lock_write().unlock)
 
404
        fetch_spec_factory.source_repo = source_repository
 
405
        fetch_spec_factory.target_repo = result_repo
 
406
        if stacked or (len(result_repo._fallback_repositories) != 0):
 
407
            target_repo_kind = fetch.TargetRepoKinds.STACKED
 
408
        elif is_new_repo:
 
409
            target_repo_kind = fetch.TargetRepoKinds.EMPTY
 
410
        else:
 
411
            target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
 
412
        fetch_spec_factory.target_repo_kind = target_repo_kind
 
413
        if source_repository is not None:
 
414
            fetch_spec = fetch_spec_factory.make_fetch_spec()
 
415
            result_repo.fetch(source_repository, fetch_spec=fetch_spec)
 
416
 
 
417
        if source_branch is None:
 
418
            # this is for sprouting a controldir without a branch; is that
 
419
            # actually useful?
 
420
            # Not especially, but it's part of the contract.
 
421
            result_branch = result.create_branch()
 
422
        else:
 
423
            result_branch = source_branch.sprout(result,
 
424
                revision_id=revision_id, repository_policy=repository_policy,
 
425
                repository=result_repo)
 
426
        mutter("created new branch %r" % (result_branch,))
 
427
 
 
428
        # Create/update the result working tree
 
429
        if (create_tree_if_local and
 
430
            isinstance(target_transport, local.LocalTransport) and
 
431
            (result_repo is None or result_repo.make_working_trees())):
 
432
            wt = result.create_workingtree(accelerator_tree=accelerator_tree,
 
433
                hardlink=hardlink, from_branch=result_branch)
 
434
            wt.lock_write()
 
435
            try:
 
436
                if wt.path2id('') is None:
 
437
                    try:
 
438
                        wt.set_root_id(self.open_workingtree.get_root_id())
 
439
                    except errors.NoWorkingTree:
 
440
                        pass
 
441
            finally:
 
442
                wt.unlock()
 
443
        else:
 
444
            wt = None
 
445
        if recurse == 'down':
 
446
            basis = None
 
447
            if wt is not None:
 
448
                basis = wt.basis_tree()
 
449
            elif result_branch is not None:
 
450
                basis = result_branch.basis_tree()
 
451
            elif source_branch is not None:
 
452
                basis = source_branch.basis_tree()
 
453
            if basis is not None:
 
454
                add_cleanup(basis.lock_read().unlock)
 
455
                subtrees = basis.iter_references()
 
456
            else:
 
457
                subtrees = []
 
458
            for path, file_id in subtrees:
 
459
                target = urlutils.join(url, urlutils.escape(path))
 
460
                sublocation = source_branch.reference_parent(file_id, path)
 
461
                sublocation.bzrdir.sprout(target,
 
462
                    basis.get_reference_revision(file_id, path),
 
463
                    force_new_repo=force_new_repo, recurse=recurse,
 
464
                    stacked=stacked)
 
465
        return result
 
466
 
 
467
    def _find_source_repo(self, add_cleanup, source_branch):
 
468
        """Find the source branch and repo for a sprout operation.
 
469
        
 
470
        This is helper intended for use by _sprout.
 
471
 
 
472
        :returns: (source_branch, source_repository).  Either or both may be
 
473
            None.  If not None, they will be read-locked (and their unlock(s)
 
474
            scheduled via the add_cleanup param).
 
475
        """
 
476
        if source_branch is not None:
 
477
            add_cleanup(source_branch.lock_read().unlock)
 
478
            return source_branch, source_branch.repository
 
479
        try:
 
480
            source_branch = self.open_branch()
 
481
            source_repository = source_branch.repository
 
482
        except errors.NotBranchError:
 
483
            source_branch = None
 
484
            try:
 
485
                source_repository = self.open_repository()
 
486
            except errors.NoRepositoryPresent:
 
487
                source_repository = None
 
488
            else:
 
489
                add_cleanup(source_repository.lock_read().unlock)
 
490
        else:
 
491
            add_cleanup(source_branch.lock_read().unlock)
 
492
        return source_branch, source_repository
 
493
 
 
494
    def push_branch(self, source, revision_id=None, overwrite=False, 
 
495
        remember=False, create_prefix=False):
 
496
        """Push the source branch into this ControlDir."""
 
497
        br_to = None
 
498
        # If we can open a branch, use its direct repository, otherwise see
 
499
        # if there is a repository without a branch.
 
500
        try:
 
501
            br_to = self.open_branch()
 
502
        except errors.NotBranchError:
 
503
            # Didn't find a branch, can we find a repository?
 
504
            repository_to = self.find_repository()
 
505
        else:
 
506
            # Found a branch, so we must have found a repository
 
507
            repository_to = br_to.repository
 
508
 
 
509
        push_result = PushResult()
 
510
        push_result.source_branch = source
 
511
        if br_to is None:
 
512
            # We have a repository but no branch, copy the revisions, and then
 
513
            # create a branch.
 
514
            repository_to.fetch(source.repository, revision_id=revision_id)
 
515
            br_to = source.clone(self, revision_id=revision_id)
 
516
            if source.get_push_location() is None or remember:
 
517
                source.set_push_location(br_to.base)
 
518
            push_result.stacked_on = None
 
519
            push_result.branch_push_result = None
 
520
            push_result.old_revno = None
 
521
            push_result.old_revid = _mod_revision.NULL_REVISION
 
522
            push_result.target_branch = br_to
 
523
            push_result.master_branch = None
 
524
            push_result.workingtree_updated = False
 
525
        else:
 
526
            # We have successfully opened the branch, remember if necessary:
 
527
            if source.get_push_location() is None or remember:
 
528
                source.set_push_location(br_to.base)
 
529
            try:
 
530
                tree_to = self.open_workingtree()
 
531
            except errors.NotLocalUrl:
 
532
                push_result.branch_push_result = source.push(br_to, 
 
533
                    overwrite, stop_revision=revision_id)
 
534
                push_result.workingtree_updated = False
 
535
            except errors.NoWorkingTree:
 
536
                push_result.branch_push_result = source.push(br_to,
 
537
                    overwrite, stop_revision=revision_id)
 
538
                push_result.workingtree_updated = None # Not applicable
 
539
            else:
 
540
                tree_to.lock_write()
 
541
                try:
 
542
                    push_result.branch_push_result = source.push(
 
543
                        tree_to.branch, overwrite, stop_revision=revision_id)
 
544
                    tree_to.update()
 
545
                finally:
 
546
                    tree_to.unlock()
 
547
                push_result.workingtree_updated = True
 
548
            push_result.old_revno = push_result.branch_push_result.old_revno
 
549
            push_result.old_revid = push_result.branch_push_result.old_revid
 
550
            push_result.target_branch = \
 
551
                push_result.branch_push_result.target_branch
 
552
        return push_result
 
553
 
 
554
    def _get_tree_branch(self, name=None):
 
555
        """Return the branch and tree, if any, for this bzrdir.
 
556
 
 
557
        :param name: Name of colocated branch to open.
 
558
 
 
559
        Return None for tree if not present or inaccessible.
 
560
        Raise NotBranchError if no branch is present.
 
561
        :return: (tree, branch)
 
562
        """
 
563
        try:
 
564
            tree = self.open_workingtree()
 
565
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
566
            tree = None
 
567
            branch = self.open_branch(name=name)
 
568
        else:
 
569
            if name is not None:
 
570
                branch = self.open_branch(name=name)
 
571
            else:
 
572
                branch = tree.branch
 
573
        return tree, branch
 
574
 
 
575
    def get_config(self):
 
576
        """Get configuration for this ControlDir."""
 
577
        raise NotImplementedError(self.get_config)
 
578
 
 
579
    def check_conversion_target(self, target_format):
 
580
        """Check that a bzrdir as a whole can be converted to a new format."""
 
581
        raise NotImplementedError(self.check_conversion_target)
 
582
 
 
583
    def clone(self, url, revision_id=None, force_new_repo=False,
 
584
              preserve_stacking=False):
 
585
        """Clone this bzrdir and its contents to url verbatim.
 
586
 
 
587
        :param url: The url create the clone at.  If url's last component does
 
588
            not exist, it will be created.
 
589
        :param revision_id: The tip revision-id to use for any branch or
 
590
            working tree.  If not None, then the clone operation may tune
 
591
            itself to download less data.
 
592
        :param force_new_repo: Do not use a shared repository for the target
 
593
                               even if one is available.
 
594
        :param preserve_stacking: When cloning a stacked branch, stack the
 
595
            new branch on top of the other branch's stacked-on branch.
 
596
        """
 
597
        return self.clone_on_transport(get_transport(url),
 
598
                                       revision_id=revision_id,
 
599
                                       force_new_repo=force_new_repo,
 
600
                                       preserve_stacking=preserve_stacking)
 
601
 
 
602
    def clone_on_transport(self, transport, revision_id=None,
 
603
        force_new_repo=False, preserve_stacking=False, stacked_on=None,
 
604
        create_prefix=False, use_existing_dir=True):
 
605
        """Clone this bzrdir and its contents to transport verbatim.
 
606
 
 
607
        :param transport: The transport for the location to produce the clone
 
608
            at.  If the target directory does not exist, it will be created.
 
609
        :param revision_id: The tip revision-id to use for any branch or
 
610
            working tree.  If not None, then the clone operation may tune
 
611
            itself to download less data.
 
612
        :param force_new_repo: Do not use a shared repository for the target,
 
613
                               even if one is available.
 
614
        :param preserve_stacking: When cloning a stacked branch, stack the
 
615
            new branch on top of the other branch's stacked-on branch.
 
616
        :param create_prefix: Create any missing directories leading up to
 
617
            to_transport.
 
618
        :param use_existing_dir: Use an existing directory if one exists.
 
619
        """
 
620
        raise NotImplementedError(self.clone_on_transport)
 
621
 
 
622
 
 
623
class ControlDirFormat(object):
 
624
    """An encapsulation of the initialization and open routines for a format.
 
625
 
 
626
    Formats provide three things:
 
627
     * An initialization routine,
 
628
     * a format string,
 
629
     * an open routine.
 
630
 
 
631
    Formats are placed in a dict by their format string for reference
 
632
    during controldir opening. These should be subclasses of ControlDirFormat
 
633
    for consistency.
 
634
 
 
635
    Once a format is deprecated, just deprecate the initialize and open
 
636
    methods on the format class. Do not deprecate the object, as the
 
637
    object will be created every system load.
 
638
 
 
639
    :cvar colocated_branches: Whether this formats supports colocated branches.
 
640
    :cvar supports_workingtrees: This control directory can co-exist with a
 
641
        working tree.
 
642
    """
 
643
 
 
644
    _default_format = None
 
645
    """The default format used for new control directories."""
 
646
 
 
647
    _formats = []
 
648
    """The registered control formats - .bzr, ....
 
649
 
 
650
    This is a list of ControlDirFormat objects.
 
651
    """
 
652
 
 
653
    _server_probers = []
 
654
    """The registered server format probers, e.g. RemoteBzrProber.
 
655
 
 
656
    This is a list of Prober-derived classes.
 
657
    """
 
658
 
 
659
    _probers = []
 
660
    """The registered format probers, e.g. BzrProber.
 
661
 
 
662
    This is a list of Prober-derived classes.
 
663
    """
 
664
 
 
665
    colocated_branches = False
 
666
    """Whether co-located branches are supported for this control dir format.
 
667
    """
 
668
 
 
669
    supports_workingtrees = True
 
670
 
 
671
    def get_format_description(self):
 
672
        """Return the short description for this format."""
 
673
        raise NotImplementedError(self.get_format_description)
 
674
 
 
675
    def get_converter(self, format=None):
 
676
        """Return the converter to use to convert controldirs needing converts.
 
677
 
 
678
        This returns a bzrlib.controldir.Converter object.
 
679
 
 
680
        This should return the best upgrader to step this format towards the
 
681
        current default format. In the case of plugins we can/should provide
 
682
        some means for them to extend the range of returnable converters.
 
683
 
 
684
        :param format: Optional format to override the default format of the
 
685
                       library.
 
686
        """
 
687
        raise NotImplementedError(self.get_converter)
 
688
 
 
689
    def is_supported(self):
 
690
        """Is this format supported?
 
691
 
 
692
        Supported formats must be initializable and openable.
 
693
        Unsupported formats may not support initialization or committing or
 
694
        some other features depending on the reason for not being supported.
 
695
        """
 
696
        return True
 
697
 
 
698
    def same_model(self, target_format):
 
699
        return (self.repository_format.rich_root_data ==
 
700
            target_format.rich_root_data)
 
701
 
 
702
    @classmethod
 
703
    def register_format(klass, format):
 
704
        """Register a format that does not use '.bzr' for its control dir.
 
705
 
 
706
        """
 
707
        klass._formats.append(format)
 
708
 
 
709
    @classmethod
 
710
    def register_prober(klass, prober):
 
711
        """Register a prober that can look for a control dir.
 
712
 
 
713
        """
 
714
        klass._probers.append(prober)
 
715
 
 
716
    @classmethod
 
717
    def unregister_prober(klass, prober):
 
718
        """Unregister a prober.
 
719
 
 
720
        """
 
721
        klass._probers.remove(prober)
 
722
 
 
723
    @classmethod
 
724
    def register_server_prober(klass, prober):
 
725
        """Register a control format prober for client-server environments.
 
726
 
 
727
        These probers will be used before ones registered with
 
728
        register_prober.  This gives implementations that decide to the
 
729
        chance to grab it before anything looks at the contents of the format
 
730
        file.
 
731
        """
 
732
        klass._server_probers.append(prober)
 
733
 
 
734
    def __str__(self):
 
735
        # Trim the newline
 
736
        return self.get_format_description().rstrip()
 
737
 
 
738
    @classmethod
 
739
    def unregister_format(klass, format):
 
740
        klass._formats.remove(format)
 
741
 
 
742
    @classmethod
 
743
    def known_formats(klass):
 
744
        """Return all the known formats.
 
745
        """
 
746
        return set(klass._formats)
 
747
 
 
748
    @classmethod
 
749
    def find_format(klass, transport, _server_formats=True):
 
750
        """Return the format present at transport."""
 
751
        if _server_formats:
 
752
            _probers = klass._server_probers + klass._probers
 
753
        else:
 
754
            _probers = klass._probers
 
755
        for prober_kls in _probers:
 
756
            prober = prober_kls()
 
757
            try:
 
758
                return prober.probe_transport(transport)
 
759
            except errors.NotBranchError:
 
760
                # this format does not find a control dir here.
 
761
                pass
 
762
        raise errors.NotBranchError(path=transport.base)
 
763
 
 
764
    def initialize(self, url, possible_transports=None):
 
765
        """Create a control dir at this url and return an opened copy.
 
766
 
 
767
        While not deprecated, this method is very specific and its use will
 
768
        lead to many round trips to setup a working environment. See
 
769
        initialize_on_transport_ex for a [nearly] all-in-one method.
 
770
 
 
771
        Subclasses should typically override initialize_on_transport
 
772
        instead of this method.
 
773
        """
 
774
        return self.initialize_on_transport(get_transport(url,
 
775
                                                          possible_transports))
 
776
    def initialize_on_transport(self, transport):
 
777
        """Initialize a new controldir in the base directory of a Transport."""
 
778
        raise NotImplementedError(self.initialize_on_transport)
 
779
 
 
780
    def initialize_on_transport_ex(self, transport, use_existing_dir=False,
 
781
        create_prefix=False, force_new_repo=False, stacked_on=None,
 
782
        stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
 
783
        shared_repo=False, vfs_only=False):
 
784
        """Create this format on transport.
 
785
 
 
786
        The directory to initialize will be created.
 
787
 
 
788
        :param force_new_repo: Do not use a shared repository for the target,
 
789
                               even if one is available.
 
790
        :param create_prefix: Create any missing directories leading up to
 
791
            to_transport.
 
792
        :param use_existing_dir: Use an existing directory if one exists.
 
793
        :param stacked_on: A url to stack any created branch on, None to follow
 
794
            any target stacking policy.
 
795
        :param stack_on_pwd: If stack_on is relative, the location it is
 
796
            relative to.
 
797
        :param repo_format_name: If non-None, a repository will be
 
798
            made-or-found. Should none be found, or if force_new_repo is True
 
799
            the repo_format_name is used to select the format of repository to
 
800
            create.
 
801
        :param make_working_trees: Control the setting of make_working_trees
 
802
            for a new shared repository when one is made. None to use whatever
 
803
            default the format has.
 
804
        :param shared_repo: Control whether made repositories are shared or
 
805
            not.
 
806
        :param vfs_only: If True do not attempt to use a smart server
 
807
        :return: repo, controldir, require_stacking, repository_policy. repo is
 
808
            None if none was created or found, controldir is always valid.
 
809
            require_stacking is the result of examining the stacked_on
 
810
            parameter and any stacking policy found for the target.
 
811
        """
 
812
        raise NotImplementedError(self.initialize_on_transport_ex)
 
813
 
 
814
    def network_name(self):
 
815
        """A simple byte string uniquely identifying this format for RPC calls.
 
816
 
 
817
        Bzr control formats use this disk format string to identify the format
 
818
        over the wire. Its possible that other control formats have more
 
819
        complex detection requirements, so we permit them to use any unique and
 
820
        immutable string they desire.
 
821
        """
 
822
        raise NotImplementedError(self.network_name)
 
823
 
 
824
    def open(self, transport, _found=False):
 
825
        """Return an instance of this format for the dir transport points at.
 
826
        """
 
827
        raise NotImplementedError(self.open)
 
828
 
 
829
    @classmethod
 
830
    def _set_default_format(klass, format):
 
831
        """Set default format (for testing behavior of defaults only)"""
 
832
        klass._default_format = format
 
833
 
 
834
    @classmethod
 
835
    def get_default_format(klass):
 
836
        """Return the current default format."""
 
837
        return klass._default_format
 
838
 
 
839
 
 
840
class Prober(object):
 
841
    """Abstract class that can be used to detect a particular kind of 
 
842
    control directory.
 
843
 
 
844
    At the moment this just contains a single method to probe a particular 
 
845
    transport, but it may be extended in the future to e.g. avoid 
 
846
    multiple levels of probing for Subversion repositories.
 
847
    """
 
848
 
 
849
    def probe_transport(self, transport):
 
850
        """Return the controldir style format present in a directory.
 
851
 
 
852
        :raise UnknownFormatError: If a control dir was found but is
 
853
            in an unknown format.
 
854
        :raise NotBranchError: If no control directory was found.
 
855
        :return: A ControlDirFormat instance.
 
856
        """
 
857
        raise NotImplementedError(self.probe_transport)
 
858
 
 
859
 
 
860
class ControlDirFormatInfo(object):
 
861
 
 
862
    def __init__(self, native, deprecated, hidden, experimental):
 
863
        self.deprecated = deprecated
 
864
        self.native = native
 
865
        self.hidden = hidden
 
866
        self.experimental = experimental
 
867
 
 
868
 
 
869
class ControlDirFormatRegistry(registry.Registry):
 
870
    """Registry of user-selectable ControlDir subformats.
 
871
 
 
872
    Differs from ControlDirFormat._formats in that it provides sub-formats,
 
873
    e.g. ControlDirMeta1 with weave repository.  Also, it's more user-oriented.
 
874
    """
 
875
 
 
876
    def __init__(self):
 
877
        """Create a ControlDirFormatRegistry."""
 
878
        self._aliases = set()
 
879
        self._registration_order = list()
 
880
        super(ControlDirFormatRegistry, self).__init__()
 
881
 
 
882
    def aliases(self):
 
883
        """Return a set of the format names which are aliases."""
 
884
        return frozenset(self._aliases)
 
885
 
 
886
    def register(self, key, factory, help, native=True, deprecated=False,
 
887
                 hidden=False, experimental=False, alias=False):
 
888
        """Register a ControlDirFormat factory.
 
889
 
 
890
        The factory must be a callable that takes one parameter: the key.
 
891
        It must produce an instance of the ControlDirFormat when called.
 
892
 
 
893
        This function mainly exists to prevent the info object from being
 
894
        supplied directly.
 
895
        """
 
896
        registry.Registry.register(self, key, factory, help,
 
897
            ControlDirFormatInfo(native, deprecated, hidden, experimental))
 
898
        if alias:
 
899
            self._aliases.add(key)
 
900
        self._registration_order.append(key)
 
901
 
 
902
    def register_lazy(self, key, module_name, member_name, help, native=True,
 
903
        deprecated=False, hidden=False, experimental=False, alias=False):
 
904
        registry.Registry.register_lazy(self, key, module_name, member_name,
 
905
            help, ControlDirFormatInfo(native, deprecated, hidden, experimental))
 
906
        if alias:
 
907
            self._aliases.add(key)
 
908
        self._registration_order.append(key)
 
909
 
 
910
    def set_default(self, key):
 
911
        """Set the 'default' key to be a clone of the supplied key.
 
912
 
 
913
        This method must be called once and only once.
 
914
        """
 
915
        registry.Registry.register(self, 'default', self.get(key),
 
916
            self.get_help(key), info=self.get_info(key))
 
917
        self._aliases.add('default')
 
918
 
 
919
    def set_default_repository(self, key):
 
920
        """Set the FormatRegistry default and Repository default.
 
921
 
 
922
        This is a transitional method while Repository.set_default_format
 
923
        is deprecated.
 
924
        """
 
925
        if 'default' in self:
 
926
            self.remove('default')
 
927
        self.set_default(key)
 
928
        format = self.get('default')()
 
929
 
 
930
    def make_bzrdir(self, key):
 
931
        return self.get(key)()
 
932
 
 
933
    def help_topic(self, topic):
 
934
        output = ""
 
935
        default_realkey = None
 
936
        default_help = self.get_help('default')
 
937
        help_pairs = []
 
938
        for key in self._registration_order:
 
939
            if key == 'default':
 
940
                continue
 
941
            help = self.get_help(key)
 
942
            if help == default_help:
 
943
                default_realkey = key
 
944
            else:
 
945
                help_pairs.append((key, help))
 
946
 
 
947
        def wrapped(key, help, info):
 
948
            if info.native:
 
949
                help = '(native) ' + help
 
950
            return ':%s:\n%s\n\n' % (key,
 
951
                textwrap.fill(help, initial_indent='    ',
 
952
                    subsequent_indent='    ',
 
953
                    break_long_words=False))
 
954
        if default_realkey is not None:
 
955
            output += wrapped(default_realkey, '(default) %s' % default_help,
 
956
                              self.get_info('default'))
 
957
        deprecated_pairs = []
 
958
        experimental_pairs = []
 
959
        for key, help in help_pairs:
 
960
            info = self.get_info(key)
 
961
            if info.hidden:
 
962
                continue
 
963
            elif info.deprecated:
 
964
                deprecated_pairs.append((key, help))
 
965
            elif info.experimental:
 
966
                experimental_pairs.append((key, help))
 
967
            else:
 
968
                output += wrapped(key, help, info)
 
969
        output += "\nSee :doc:`formats-help` for more about storage formats."
 
970
        other_output = ""
 
971
        if len(experimental_pairs) > 0:
 
972
            other_output += "Experimental formats are shown below.\n\n"
 
973
            for key, help in experimental_pairs:
 
974
                info = self.get_info(key)
 
975
                other_output += wrapped(key, help, info)
 
976
        else:
 
977
            other_output += \
 
978
                "No experimental formats are available.\n\n"
 
979
        if len(deprecated_pairs) > 0:
 
980
            other_output += "\nDeprecated formats are shown below.\n\n"
 
981
            for key, help in deprecated_pairs:
 
982
                info = self.get_info(key)
 
983
                other_output += wrapped(key, help, info)
 
984
        else:
 
985
            other_output += \
 
986
                "\nNo deprecated formats are available.\n\n"
 
987
        other_output += \
 
988
                "\nSee :doc:`formats-help` for more about storage formats."
 
989
 
 
990
        if topic == 'other-formats':
 
991
            return other_output
 
992
        else:
 
993
            return output
 
994
 
 
995
 
 
996
# Please register new formats after old formats so that formats
 
997
# appear in chronological order and format descriptions can build
 
998
# on previous ones.
 
999
format_registry = ControlDirFormatRegistry()
 
1000
 
 
1001
network_format_registry = registry.FormatRegistry()
 
1002
"""Registry of formats indexed by their network name.
 
1003
 
 
1004
The network name for a ControlDirFormat is an identifier that can be used when
 
1005
referring to formats with smart server operations. See
 
1006
ControlDirFormat.network_name() for more detail.
 
1007
"""