/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

  • Committer: Jelmer Vernooij
  • Date: 2011-02-25 15:24:22 UTC
  • mto: This revision was merged to the branch mainline in revision 5690.
  • Revision ID: jelmer@samba.org-20110225152422-d1pjdfnzsw5ufe2x
Fix tests on Debian GNU/kFreeBSD by treating it like other FreeBSD-kernel-based systems.

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
    transport as _mod_transport,
 
36
    urlutils,
 
37
    )
 
38
from bzrlib.push import (
 
39
    PushResult,
 
40
    )
 
41
from bzrlib.trace import (
 
42
    mutter,
 
43
    )
 
44
from bzrlib.transport import (
 
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 = _mod_transport.get_transport(url,
 
387
            possible_transports)
 
388
        target_transport.ensure_base()
 
389
        cloning_format = self.cloning_metadir(stacked)
 
390
        # Create/update the result branch
 
391
        result = cloning_format.initialize_on_transport(target_transport)
 
392
        source_branch, source_repository = self._find_source_repo(
 
393
            add_cleanup, source_branch)
 
394
        fetch_spec_factory.source_branch = source_branch
 
395
        # if a stacked branch wasn't requested, we don't create one
 
396
        # even if the origin was stacked
 
397
        if stacked and source_branch is not None:
 
398
            stacked_branch_url = self.root_transport.base
 
399
        else:
 
400
            stacked_branch_url = None
 
401
        repository_policy = result.determine_repository_policy(
 
402
            force_new_repo, stacked_branch_url, require_stacking=stacked)
 
403
        result_repo, is_new_repo = repository_policy.acquire_repository()
 
404
        add_cleanup(result_repo.lock_write().unlock)
 
405
        fetch_spec_factory.source_repo = source_repository
 
406
        fetch_spec_factory.target_repo = result_repo
 
407
        if stacked or (len(result_repo._fallback_repositories) != 0):
 
408
            target_repo_kind = fetch.TargetRepoKinds.STACKED
 
409
        elif is_new_repo:
 
410
            target_repo_kind = fetch.TargetRepoKinds.EMPTY
 
411
        else:
 
412
            target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
 
413
        fetch_spec_factory.target_repo_kind = target_repo_kind
 
414
        if source_repository is not None:
 
415
            fetch_spec = fetch_spec_factory.make_fetch_spec()
 
416
            result_repo.fetch(source_repository, fetch_spec=fetch_spec)
 
417
 
 
418
        if source_branch is None:
 
419
            # this is for sprouting a controldir without a branch; is that
 
420
            # actually useful?
 
421
            # Not especially, but it's part of the contract.
 
422
            result_branch = result.create_branch()
 
423
        else:
 
424
            result_branch = source_branch.sprout(result,
 
425
                revision_id=revision_id, repository_policy=repository_policy,
 
426
                repository=result_repo)
 
427
        mutter("created new branch %r" % (result_branch,))
 
428
 
 
429
        # Create/update the result working tree
 
430
        if (create_tree_if_local and
 
431
            isinstance(target_transport, local.LocalTransport) and
 
432
            (result_repo is None or result_repo.make_working_trees())):
 
433
            wt = result.create_workingtree(accelerator_tree=accelerator_tree,
 
434
                hardlink=hardlink, from_branch=result_branch)
 
435
            wt.lock_write()
 
436
            try:
 
437
                if wt.path2id('') is None:
 
438
                    try:
 
439
                        wt.set_root_id(self.open_workingtree.get_root_id())
 
440
                    except errors.NoWorkingTree:
 
441
                        pass
 
442
            finally:
 
443
                wt.unlock()
 
444
        else:
 
445
            wt = None
 
446
        if recurse == 'down':
 
447
            basis = None
 
448
            if wt is not None:
 
449
                basis = wt.basis_tree()
 
450
            elif result_branch is not None:
 
451
                basis = result_branch.basis_tree()
 
452
            elif source_branch is not None:
 
453
                basis = source_branch.basis_tree()
 
454
            if basis is not None:
 
455
                add_cleanup(basis.lock_read().unlock)
 
456
                subtrees = basis.iter_references()
 
457
            else:
 
458
                subtrees = []
 
459
            for path, file_id in subtrees:
 
460
                target = urlutils.join(url, urlutils.escape(path))
 
461
                sublocation = source_branch.reference_parent(file_id, path)
 
462
                sublocation.bzrdir.sprout(target,
 
463
                    basis.get_reference_revision(file_id, path),
 
464
                    force_new_repo=force_new_repo, recurse=recurse,
 
465
                    stacked=stacked)
 
466
        return result
 
467
 
 
468
    def _find_source_repo(self, add_cleanup, source_branch):
 
469
        """Find the source branch and repo for a sprout operation.
 
470
        
 
471
        This is helper intended for use by _sprout.
 
472
 
 
473
        :returns: (source_branch, source_repository).  Either or both may be
 
474
            None.  If not None, they will be read-locked (and their unlock(s)
 
475
            scheduled via the add_cleanup param).
 
476
        """
 
477
        if source_branch is not None:
 
478
            add_cleanup(source_branch.lock_read().unlock)
 
479
            return source_branch, source_branch.repository
 
480
        try:
 
481
            source_branch = self.open_branch()
 
482
            source_repository = source_branch.repository
 
483
        except errors.NotBranchError:
 
484
            source_branch = None
 
485
            try:
 
486
                source_repository = self.open_repository()
 
487
            except errors.NoRepositoryPresent:
 
488
                source_repository = None
 
489
            else:
 
490
                add_cleanup(source_repository.lock_read().unlock)
 
491
        else:
 
492
            add_cleanup(source_branch.lock_read().unlock)
 
493
        return source_branch, source_repository
 
494
 
 
495
    def push_branch(self, source, revision_id=None, overwrite=False, 
 
496
        remember=False, create_prefix=False):
 
497
        """Push the source branch into this ControlDir."""
 
498
        br_to = None
 
499
        # If we can open a branch, use its direct repository, otherwise see
 
500
        # if there is a repository without a branch.
 
501
        try:
 
502
            br_to = self.open_branch()
 
503
        except errors.NotBranchError:
 
504
            # Didn't find a branch, can we find a repository?
 
505
            repository_to = self.find_repository()
 
506
        else:
 
507
            # Found a branch, so we must have found a repository
 
508
            repository_to = br_to.repository
 
509
 
 
510
        push_result = PushResult()
 
511
        push_result.source_branch = source
 
512
        if br_to is None:
 
513
            # We have a repository but no branch, copy the revisions, and then
 
514
            # create a branch.
 
515
            repository_to.fetch(source.repository, revision_id=revision_id)
 
516
            br_to = source.clone(self, revision_id=revision_id)
 
517
            if source.get_push_location() is None or remember:
 
518
                source.set_push_location(br_to.base)
 
519
            push_result.stacked_on = None
 
520
            push_result.branch_push_result = None
 
521
            push_result.old_revno = None
 
522
            push_result.old_revid = _mod_revision.NULL_REVISION
 
523
            push_result.target_branch = br_to
 
524
            push_result.master_branch = None
 
525
            push_result.workingtree_updated = False
 
526
        else:
 
527
            # We have successfully opened the branch, remember if necessary:
 
528
            if source.get_push_location() is None or remember:
 
529
                source.set_push_location(br_to.base)
 
530
            try:
 
531
                tree_to = self.open_workingtree()
 
532
            except errors.NotLocalUrl:
 
533
                push_result.branch_push_result = source.push(br_to, 
 
534
                    overwrite, stop_revision=revision_id)
 
535
                push_result.workingtree_updated = False
 
536
            except errors.NoWorkingTree:
 
537
                push_result.branch_push_result = source.push(br_to,
 
538
                    overwrite, stop_revision=revision_id)
 
539
                push_result.workingtree_updated = None # Not applicable
 
540
            else:
 
541
                tree_to.lock_write()
 
542
                try:
 
543
                    push_result.branch_push_result = source.push(
 
544
                        tree_to.branch, overwrite, stop_revision=revision_id)
 
545
                    tree_to.update()
 
546
                finally:
 
547
                    tree_to.unlock()
 
548
                push_result.workingtree_updated = True
 
549
            push_result.old_revno = push_result.branch_push_result.old_revno
 
550
            push_result.old_revid = push_result.branch_push_result.old_revid
 
551
            push_result.target_branch = \
 
552
                push_result.branch_push_result.target_branch
 
553
        return push_result
 
554
 
 
555
    def _get_tree_branch(self, name=None):
 
556
        """Return the branch and tree, if any, for this bzrdir.
 
557
 
 
558
        :param name: Name of colocated branch to open.
 
559
 
 
560
        Return None for tree if not present or inaccessible.
 
561
        Raise NotBranchError if no branch is present.
 
562
        :return: (tree, branch)
 
563
        """
 
564
        try:
 
565
            tree = self.open_workingtree()
 
566
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
567
            tree = None
 
568
            branch = self.open_branch(name=name)
 
569
        else:
 
570
            if name is not None:
 
571
                branch = self.open_branch(name=name)
 
572
            else:
 
573
                branch = tree.branch
 
574
        return tree, branch
 
575
 
 
576
    def get_config(self):
 
577
        """Get configuration for this ControlDir."""
 
578
        raise NotImplementedError(self.get_config)
 
579
 
 
580
    def check_conversion_target(self, target_format):
 
581
        """Check that a bzrdir as a whole can be converted to a new format."""
 
582
        raise NotImplementedError(self.check_conversion_target)
 
583
 
 
584
    def clone(self, url, revision_id=None, force_new_repo=False,
 
585
              preserve_stacking=False):
 
586
        """Clone this bzrdir and its contents to url verbatim.
 
587
 
 
588
        :param url: The url create the clone at.  If url's last component does
 
589
            not exist, it will be created.
 
590
        :param revision_id: The tip revision-id to use for any branch or
 
591
            working tree.  If not None, then the clone operation may tune
 
592
            itself to download less data.
 
593
        :param force_new_repo: Do not use a shared repository for the target
 
594
                               even if one is available.
 
595
        :param preserve_stacking: When cloning a stacked branch, stack the
 
596
            new branch on top of the other branch's stacked-on branch.
 
597
        """
 
598
        return self.clone_on_transport(_mod_transport.get_transport(url),
 
599
                                       revision_id=revision_id,
 
600
                                       force_new_repo=force_new_repo,
 
601
                                       preserve_stacking=preserve_stacking)
 
602
 
 
603
    def clone_on_transport(self, transport, revision_id=None,
 
604
        force_new_repo=False, preserve_stacking=False, stacked_on=None,
 
605
        create_prefix=False, use_existing_dir=True, no_tree=False):
 
606
        """Clone this bzrdir and its contents to transport verbatim.
 
607
 
 
608
        :param transport: The transport for the location to produce the clone
 
609
            at.  If the target directory does not exist, it will be created.
 
610
        :param revision_id: The tip revision-id to use for any branch or
 
611
            working tree.  If not None, then the clone operation may tune
 
612
            itself to download less data.
 
613
        :param force_new_repo: Do not use a shared repository for the target,
 
614
                               even if one is available.
 
615
        :param preserve_stacking: When cloning a stacked branch, stack the
 
616
            new branch on top of the other branch's stacked-on branch.
 
617
        :param create_prefix: Create any missing directories leading up to
 
618
            to_transport.
 
619
        :param use_existing_dir: Use an existing directory if one exists.
 
620
        :param no_tree: If set to true prevents creation of a working tree.
 
621
        """
 
622
        raise NotImplementedError(self.clone_on_transport)
 
623
 
 
624
 
 
625
class ControlComponentFormat(object):
 
626
    """A component that can live inside of a .bzr meta directory."""
 
627
 
 
628
    def get_format_string(self):
 
629
        """Return the format of this format, if usable in meta directories."""
 
630
        raise NotImplementedError(self.get_format_string)
 
631
 
 
632
    def get_format_description(self):
 
633
        """Return the short description for this format."""
 
634
        raise NotImplementedError(self.get_format_description)
 
635
 
 
636
 
 
637
class ControlComponentFormatRegistry(registry.FormatRegistry):
 
638
    """A registry for control components (branch, workingtree, repository)."""
 
639
 
 
640
    def __init__(self, other_registry=None):
 
641
        super(ControlComponentFormatRegistry, self).__init__(other_registry)
 
642
        self._extra_formats = []
 
643
 
 
644
    def register(self, format):
 
645
        """Register a new format."""
 
646
        super(ControlComponentFormatRegistry, self).register(
 
647
            format.get_format_string(), format)
 
648
 
 
649
    def remove(self, format):
 
650
        """Remove a registered format."""
 
651
        super(ControlComponentFormatRegistry, self).remove(
 
652
            format.get_format_string())
 
653
 
 
654
    def register_extra(self, format):
 
655
        """Register a format that can not be used in a metadir.
 
656
 
 
657
        This is mainly useful to allow custom repository formats, such as older
 
658
        Bazaar formats and foreign formats, to be tested.
 
659
        """
 
660
        self._extra_formats.append(registry._ObjectGetter(format))
 
661
 
 
662
    def remove_extra(self, format):
 
663
        """Remove an extra format.
 
664
        """
 
665
        self._extra_formats.remove(registry._ObjectGetter(format))
 
666
 
 
667
    def register_extra_lazy(self, module_name, member_name):
 
668
        """Register a format lazily.
 
669
        """
 
670
        self._extra_formats.append(
 
671
            registry._LazyObjectGetter(module_name, member_name))
 
672
 
 
673
    def _get_extra(self):
 
674
        """Return all "extra" formats, not usable in meta directories."""
 
675
        result = []
 
676
        for getter in self._extra_formats:
 
677
            f = getter.get_obj()
 
678
            if callable(f):
 
679
                f = f()
 
680
            result.append(f)
 
681
        return result
 
682
 
 
683
    def _get_all(self):
 
684
        """Return all formats, even those not usable in metadirs.
 
685
        """
 
686
        result = []
 
687
        for name in self.keys():
 
688
            fmt = self.get(name)
 
689
            if callable(fmt):
 
690
                fmt = fmt()
 
691
            result.append(fmt)
 
692
        return result + self._get_extra()
 
693
 
 
694
    def _get_all_modules(self):
 
695
        """Return a set of the modules providing objects."""
 
696
        modules = set()
 
697
        for name in self.keys():
 
698
            modules.add(self._get_module(name))
 
699
        for getter in self._extra_formats:
 
700
            modules.add(getter.get_module())
 
701
        return modules
 
702
 
 
703
 
 
704
class ControlDirFormat(object):
 
705
    """An encapsulation of the initialization and open routines for a format.
 
706
 
 
707
    Formats provide three things:
 
708
     * An initialization routine,
 
709
     * a format string,
 
710
     * an open routine.
 
711
 
 
712
    Formats are placed in a dict by their format string for reference
 
713
    during controldir opening. These should be subclasses of ControlDirFormat
 
714
    for consistency.
 
715
 
 
716
    Once a format is deprecated, just deprecate the initialize and open
 
717
    methods on the format class. Do not deprecate the object, as the
 
718
    object will be created every system load.
 
719
 
 
720
    :cvar colocated_branches: Whether this formats supports colocated branches.
 
721
    :cvar supports_workingtrees: This control directory can co-exist with a
 
722
        working tree.
 
723
    """
 
724
 
 
725
    _default_format = None
 
726
    """The default format used for new control directories."""
 
727
 
 
728
    _formats = []
 
729
    """The registered control formats - .bzr, ....
 
730
 
 
731
    This is a list of ControlDirFormat objects.
 
732
    """
 
733
 
 
734
    _server_probers = []
 
735
    """The registered server format probers, e.g. RemoteBzrProber.
 
736
 
 
737
    This is a list of Prober-derived classes.
 
738
    """
 
739
 
 
740
    _probers = []
 
741
    """The registered format probers, e.g. BzrProber.
 
742
 
 
743
    This is a list of Prober-derived classes.
 
744
    """
 
745
 
 
746
    colocated_branches = False
 
747
    """Whether co-located branches are supported for this control dir format.
 
748
    """
 
749
 
 
750
    supports_workingtrees = True
 
751
    """Whether working trees can exist in control directories of this format.
 
752
    """
 
753
 
 
754
    fixed_components = False
 
755
    """Whether components can not change format independent of the control dir.
 
756
    """
 
757
 
 
758
    def get_format_description(self):
 
759
        """Return the short description for this format."""
 
760
        raise NotImplementedError(self.get_format_description)
 
761
 
 
762
    def get_converter(self, format=None):
 
763
        """Return the converter to use to convert controldirs needing converts.
 
764
 
 
765
        This returns a bzrlib.controldir.Converter object.
 
766
 
 
767
        This should return the best upgrader to step this format towards the
 
768
        current default format. In the case of plugins we can/should provide
 
769
        some means for them to extend the range of returnable converters.
 
770
 
 
771
        :param format: Optional format to override the default format of the
 
772
                       library.
 
773
        """
 
774
        raise NotImplementedError(self.get_converter)
 
775
 
 
776
    def is_supported(self):
 
777
        """Is this format supported?
 
778
 
 
779
        Supported formats must be initializable and openable.
 
780
        Unsupported formats may not support initialization or committing or
 
781
        some other features depending on the reason for not being supported.
 
782
        """
 
783
        return True
 
784
 
 
785
    def same_model(self, target_format):
 
786
        return (self.repository_format.rich_root_data ==
 
787
            target_format.rich_root_data)
 
788
 
 
789
    @classmethod
 
790
    def register_format(klass, format):
 
791
        """Register a format that does not use '.bzr' for its control dir.
 
792
 
 
793
        """
 
794
        klass._formats.append(format)
 
795
 
 
796
    @classmethod
 
797
    def register_prober(klass, prober):
 
798
        """Register a prober that can look for a control dir.
 
799
 
 
800
        """
 
801
        klass._probers.append(prober)
 
802
 
 
803
    @classmethod
 
804
    def unregister_prober(klass, prober):
 
805
        """Unregister a prober.
 
806
 
 
807
        """
 
808
        klass._probers.remove(prober)
 
809
 
 
810
    @classmethod
 
811
    def register_server_prober(klass, prober):
 
812
        """Register a control format prober for client-server environments.
 
813
 
 
814
        These probers will be used before ones registered with
 
815
        register_prober.  This gives implementations that decide to the
 
816
        chance to grab it before anything looks at the contents of the format
 
817
        file.
 
818
        """
 
819
        klass._server_probers.append(prober)
 
820
 
 
821
    def __str__(self):
 
822
        # Trim the newline
 
823
        return self.get_format_description().rstrip()
 
824
 
 
825
    @classmethod
 
826
    def unregister_format(klass, format):
 
827
        klass._formats.remove(format)
 
828
 
 
829
    @classmethod
 
830
    def known_formats(klass):
 
831
        """Return all the known formats.
 
832
        """
 
833
        return set(klass._formats)
 
834
 
 
835
    @classmethod
 
836
    def find_format(klass, transport, _server_formats=True):
 
837
        """Return the format present at transport."""
 
838
        if _server_formats:
 
839
            _probers = klass._server_probers + klass._probers
 
840
        else:
 
841
            _probers = klass._probers
 
842
        for prober_kls in _probers:
 
843
            prober = prober_kls()
 
844
            try:
 
845
                return prober.probe_transport(transport)
 
846
            except errors.NotBranchError:
 
847
                # this format does not find a control dir here.
 
848
                pass
 
849
        raise errors.NotBranchError(path=transport.base)
 
850
 
 
851
    def initialize(self, url, possible_transports=None):
 
852
        """Create a control dir at this url and return an opened copy.
 
853
 
 
854
        While not deprecated, this method is very specific and its use will
 
855
        lead to many round trips to setup a working environment. See
 
856
        initialize_on_transport_ex for a [nearly] all-in-one method.
 
857
 
 
858
        Subclasses should typically override initialize_on_transport
 
859
        instead of this method.
 
860
        """
 
861
        return self.initialize_on_transport(
 
862
            _mod_transport.get_transport(url, possible_transports))
 
863
 
 
864
    def initialize_on_transport(self, transport):
 
865
        """Initialize a new controldir in the base directory of a Transport."""
 
866
        raise NotImplementedError(self.initialize_on_transport)
 
867
 
 
868
    def initialize_on_transport_ex(self, transport, use_existing_dir=False,
 
869
        create_prefix=False, force_new_repo=False, stacked_on=None,
 
870
        stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
 
871
        shared_repo=False, vfs_only=False):
 
872
        """Create this format on transport.
 
873
 
 
874
        The directory to initialize will be created.
 
875
 
 
876
        :param force_new_repo: Do not use a shared repository for the target,
 
877
                               even if one is available.
 
878
        :param create_prefix: Create any missing directories leading up to
 
879
            to_transport.
 
880
        :param use_existing_dir: Use an existing directory if one exists.
 
881
        :param stacked_on: A url to stack any created branch on, None to follow
 
882
            any target stacking policy.
 
883
        :param stack_on_pwd: If stack_on is relative, the location it is
 
884
            relative to.
 
885
        :param repo_format_name: If non-None, a repository will be
 
886
            made-or-found. Should none be found, or if force_new_repo is True
 
887
            the repo_format_name is used to select the format of repository to
 
888
            create.
 
889
        :param make_working_trees: Control the setting of make_working_trees
 
890
            for a new shared repository when one is made. None to use whatever
 
891
            default the format has.
 
892
        :param shared_repo: Control whether made repositories are shared or
 
893
            not.
 
894
        :param vfs_only: If True do not attempt to use a smart server
 
895
        :return: repo, controldir, require_stacking, repository_policy. repo is
 
896
            None if none was created or found, controldir is always valid.
 
897
            require_stacking is the result of examining the stacked_on
 
898
            parameter and any stacking policy found for the target.
 
899
        """
 
900
        raise NotImplementedError(self.initialize_on_transport_ex)
 
901
 
 
902
    def network_name(self):
 
903
        """A simple byte string uniquely identifying this format for RPC calls.
 
904
 
 
905
        Bzr control formats use this disk format string to identify the format
 
906
        over the wire. Its possible that other control formats have more
 
907
        complex detection requirements, so we permit them to use any unique and
 
908
        immutable string they desire.
 
909
        """
 
910
        raise NotImplementedError(self.network_name)
 
911
 
 
912
    def open(self, transport, _found=False):
 
913
        """Return an instance of this format for the dir transport points at.
 
914
        """
 
915
        raise NotImplementedError(self.open)
 
916
 
 
917
    @classmethod
 
918
    def _set_default_format(klass, format):
 
919
        """Set default format (for testing behavior of defaults only)"""
 
920
        klass._default_format = format
 
921
 
 
922
    @classmethod
 
923
    def get_default_format(klass):
 
924
        """Return the current default format."""
 
925
        return klass._default_format
 
926
 
 
927
 
 
928
class Prober(object):
 
929
    """Abstract class that can be used to detect a particular kind of 
 
930
    control directory.
 
931
 
 
932
    At the moment this just contains a single method to probe a particular 
 
933
    transport, but it may be extended in the future to e.g. avoid 
 
934
    multiple levels of probing for Subversion repositories.
 
935
    """
 
936
 
 
937
    def probe_transport(self, transport):
 
938
        """Return the controldir style format present in a directory.
 
939
 
 
940
        :raise UnknownFormatError: If a control dir was found but is
 
941
            in an unknown format.
 
942
        :raise NotBranchError: If no control directory was found.
 
943
        :return: A ControlDirFormat instance.
 
944
        """
 
945
        raise NotImplementedError(self.probe_transport)
 
946
 
 
947
 
 
948
class ControlDirFormatInfo(object):
 
949
 
 
950
    def __init__(self, native, deprecated, hidden, experimental):
 
951
        self.deprecated = deprecated
 
952
        self.native = native
 
953
        self.hidden = hidden
 
954
        self.experimental = experimental
 
955
 
 
956
 
 
957
class ControlDirFormatRegistry(registry.Registry):
 
958
    """Registry of user-selectable ControlDir subformats.
 
959
 
 
960
    Differs from ControlDirFormat._formats in that it provides sub-formats,
 
961
    e.g. BzrDirMeta1 with weave repository.  Also, it's more user-oriented.
 
962
    """
 
963
 
 
964
    def __init__(self):
 
965
        """Create a ControlDirFormatRegistry."""
 
966
        self._aliases = set()
 
967
        self._registration_order = list()
 
968
        super(ControlDirFormatRegistry, self).__init__()
 
969
 
 
970
    def aliases(self):
 
971
        """Return a set of the format names which are aliases."""
 
972
        return frozenset(self._aliases)
 
973
 
 
974
    def register(self, key, factory, help, native=True, deprecated=False,
 
975
                 hidden=False, experimental=False, alias=False):
 
976
        """Register a ControlDirFormat factory.
 
977
 
 
978
        The factory must be a callable that takes one parameter: the key.
 
979
        It must produce an instance of the ControlDirFormat when called.
 
980
 
 
981
        This function mainly exists to prevent the info object from being
 
982
        supplied directly.
 
983
        """
 
984
        registry.Registry.register(self, key, factory, help,
 
985
            ControlDirFormatInfo(native, deprecated, hidden, experimental))
 
986
        if alias:
 
987
            self._aliases.add(key)
 
988
        self._registration_order.append(key)
 
989
 
 
990
    def register_lazy(self, key, module_name, member_name, help, native=True,
 
991
        deprecated=False, hidden=False, experimental=False, alias=False):
 
992
        registry.Registry.register_lazy(self, key, module_name, member_name,
 
993
            help, ControlDirFormatInfo(native, deprecated, hidden, experimental))
 
994
        if alias:
 
995
            self._aliases.add(key)
 
996
        self._registration_order.append(key)
 
997
 
 
998
    def set_default(self, key):
 
999
        """Set the 'default' key to be a clone of the supplied key.
 
1000
 
 
1001
        This method must be called once and only once.
 
1002
        """
 
1003
        registry.Registry.register(self, 'default', self.get(key),
 
1004
            self.get_help(key), info=self.get_info(key))
 
1005
        self._aliases.add('default')
 
1006
 
 
1007
    def set_default_repository(self, key):
 
1008
        """Set the FormatRegistry default and Repository default.
 
1009
 
 
1010
        This is a transitional method while Repository.set_default_format
 
1011
        is deprecated.
 
1012
        """
 
1013
        if 'default' in self:
 
1014
            self.remove('default')
 
1015
        self.set_default(key)
 
1016
        format = self.get('default')()
 
1017
 
 
1018
    def make_bzrdir(self, key):
 
1019
        return self.get(key)()
 
1020
 
 
1021
    def help_topic(self, topic):
 
1022
        output = ""
 
1023
        default_realkey = None
 
1024
        default_help = self.get_help('default')
 
1025
        help_pairs = []
 
1026
        for key in self._registration_order:
 
1027
            if key == 'default':
 
1028
                continue
 
1029
            help = self.get_help(key)
 
1030
            if help == default_help:
 
1031
                default_realkey = key
 
1032
            else:
 
1033
                help_pairs.append((key, help))
 
1034
 
 
1035
        def wrapped(key, help, info):
 
1036
            if info.native:
 
1037
                help = '(native) ' + help
 
1038
            return ':%s:\n%s\n\n' % (key,
 
1039
                textwrap.fill(help, initial_indent='    ',
 
1040
                    subsequent_indent='    ',
 
1041
                    break_long_words=False))
 
1042
        if default_realkey is not None:
 
1043
            output += wrapped(default_realkey, '(default) %s' % default_help,
 
1044
                              self.get_info('default'))
 
1045
        deprecated_pairs = []
 
1046
        experimental_pairs = []
 
1047
        for key, help in help_pairs:
 
1048
            info = self.get_info(key)
 
1049
            if info.hidden:
 
1050
                continue
 
1051
            elif info.deprecated:
 
1052
                deprecated_pairs.append((key, help))
 
1053
            elif info.experimental:
 
1054
                experimental_pairs.append((key, help))
 
1055
            else:
 
1056
                output += wrapped(key, help, info)
 
1057
        output += "\nSee :doc:`formats-help` for more about storage formats."
 
1058
        other_output = ""
 
1059
        if len(experimental_pairs) > 0:
 
1060
            other_output += "Experimental formats are shown below.\n\n"
 
1061
            for key, help in experimental_pairs:
 
1062
                info = self.get_info(key)
 
1063
                other_output += wrapped(key, help, info)
 
1064
        else:
 
1065
            other_output += \
 
1066
                "No experimental formats are available.\n\n"
 
1067
        if len(deprecated_pairs) > 0:
 
1068
            other_output += "\nDeprecated formats are shown below.\n\n"
 
1069
            for key, help in deprecated_pairs:
 
1070
                info = self.get_info(key)
 
1071
                other_output += wrapped(key, help, info)
 
1072
        else:
 
1073
            other_output += \
 
1074
                "\nNo deprecated formats are available.\n\n"
 
1075
        other_output += \
 
1076
                "\nSee :doc:`formats-help` for more about storage formats."
 
1077
 
 
1078
        if topic == 'other-formats':
 
1079
            return other_output
 
1080
        else:
 
1081
            return output
 
1082
 
 
1083
 
 
1084
# Please register new formats after old formats so that formats
 
1085
# appear in chronological order and format descriptions can build
 
1086
# on previous ones.
 
1087
format_registry = ControlDirFormatRegistry()
 
1088
 
 
1089
network_format_registry = registry.FormatRegistry()
 
1090
"""Registry of formats indexed by their network name.
 
1091
 
 
1092
The network name for a ControlDirFormat is an identifier that can be used when
 
1093
referring to formats with smart server operations. See
 
1094
ControlDirFormat.network_name() for more detail.
 
1095
"""