/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: Andrew Bennetts
  • Date: 2011-03-15 07:54:39 UTC
  • mfrom: (0.38.5 trunk)
  • mto: This revision was merged to the branch mainline in revision 5726.
  • Revision ID: andrew.bennetts@canonical.com-20110315075439-nzm293joz143cx0k
Merge bzr-changelog-merge plugin.

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