1
# Copyright (C) 2010, 2011 Canonical Ltd
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.
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.
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
17
"""ControlDir is the basic control directory class.
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.
25
from bzrlib.lazy_import import lazy_import
26
lazy_import(globals(), """
32
revision as _mod_revision,
33
transport as _mod_transport,
38
from bzrlib.transport import local
39
from bzrlib.push import (
43
from bzrlib.i18n import gettext
46
from bzrlib import registry
49
class ControlComponent(object):
50
"""Abstract base class for control directory components.
52
This provides interfaces that are common across controldirs,
53
repositories, branches, and workingtree control directories.
55
They all expose two urls and transports: the *user* URL is the
56
one that stops above the control directory (eg .bzr) and that
57
should normally be used in messages, and the *control* URL is
58
under that in eg .bzr/checkout and is used to read the control
61
This can be used as a mixin and is intended to fit with
66
def control_transport(self):
67
raise NotImplementedError
70
def control_url(self):
71
return self.control_transport.base
74
def user_transport(self):
75
raise NotImplementedError
79
return self.user_transport.base
82
class ControlDir(ControlComponent):
83
"""A control directory.
85
While this represents a generic control directory, there are a few
86
features that are present in this interface that are currently only
87
supported by one of its implementations, BzrDir.
89
These features (bound branches, stacked branches) are currently only
90
supported by Bazaar, but could be supported by other version control
91
systems as well. Implementations are required to raise the appropriate
92
exceptions when an operation is requested that is not supported.
94
This also makes life easier for API users who can rely on the
95
implementation always allowing a particular feature to be requested but
96
raising an exception when it is not supported, rather than requiring the
97
API users to check for magic attributes to see what features are supported.
100
def can_convert_format(self):
101
"""Return true if this controldir is one whose format we can convert
105
def list_branches(self):
106
"""Return a sequence of all branches local to this control directory.
110
return [self.open_branch()]
111
except (errors.NotBranchError, errors.NoRepositoryPresent):
114
def is_control_filename(self, filename):
115
"""True if filename is the name of a path which is reserved for
118
:param filename: A filename within the root transport of this
121
This is true IF and ONLY IF the filename is part of the namespace reserved
122
for bzr control dirs. Currently this is the '.bzr' directory in the root
123
of the root_transport. it is expected that plugins will need to extend
124
this in the future - for instance to make bzr talk with svn working
127
raise NotImplementedError(self.is_control_filename)
129
def needs_format_conversion(self, format=None):
130
"""Return true if this controldir needs convert_format run on it.
132
For instance, if the repository format is out of date but the
133
branch and working tree are not, this should return True.
135
:param format: Optional parameter indicating a specific desired
136
format we plan to arrive at.
138
raise NotImplementedError(self.needs_format_conversion)
140
def create_repository(self, shared=False):
141
"""Create a new repository in this control directory.
143
:param shared: If a shared repository should be created
144
:return: The newly created repository
146
raise NotImplementedError(self.create_repository)
148
def destroy_repository(self):
149
"""Destroy the repository in this ControlDir."""
150
raise NotImplementedError(self.destroy_repository)
152
def create_branch(self, name=None, repository=None,
153
append_revisions_only=None):
154
"""Create a branch in this ControlDir.
156
:param name: Name of the colocated branch to create, None for
158
:param append_revisions_only: Whether this branch should only allow
159
appending new revisions to its history.
161
The controldirs format will control what branch format is created.
162
For more control see BranchFormatXX.create(a_controldir).
164
raise NotImplementedError(self.create_branch)
166
def destroy_branch(self, name=None):
167
"""Destroy a branch in this ControlDir.
169
:param name: Name of the branch to destroy, None for the default
172
raise NotImplementedError(self.destroy_branch)
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.
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.
186
raise NotImplementedError(self.create_workingtree)
188
def destroy_workingtree(self):
189
"""Destroy the working tree at this ControlDir.
191
Formats that do not support this may raise UnsupportedOperation.
193
raise NotImplementedError(self.destroy_workingtree)
195
def destroy_workingtree_metadata(self):
196
"""Destroy the control files for the working tree at this ControlDir.
198
The contents of working tree files are not affected.
199
Formats that do not support this may raise UnsupportedOperation.
201
raise NotImplementedError(self.destroy_workingtree_metadata)
203
def find_branch_format(self, name=None):
204
"""Find the branch 'format' for this controldir.
206
This might be a synthetic object for e.g. RemoteBranch and SVN.
208
raise NotImplementedError(self.find_branch_format)
210
def get_branch_reference(self, name=None):
211
"""Return the referenced URL for the branch in this controldir.
213
:param name: Optional colocated branch name
214
:raises NotBranchError: If there is no Branch.
215
:raises NoColocatedBranchSupport: If a branch name was specified
216
but colocated branches are not supported.
217
:return: The URL the branch in this controldir references if it is a
218
reference branch, or None for regular branches.
221
raise errors.NoColocatedBranchSupport(self)
224
def open_branch(self, name=None, unsupported=False,
225
ignore_fallbacks=False):
226
"""Open the branch object at this ControlDir if one is present.
228
If unsupported is True, then no longer supported branch formats can
231
TODO: static convenience version of this?
233
raise NotImplementedError(self.open_branch)
235
def open_repository(self, _unsupported=False):
236
"""Open the repository object at this ControlDir if one is present.
238
This will not follow the Branch object pointer - it's strictly a direct
239
open facility. Most client code should use open_branch().repository to
242
:param _unsupported: a private parameter, not part of the api.
244
TODO: static convenience version of this?
246
raise NotImplementedError(self.open_repository)
248
def find_repository(self):
249
"""Find the repository that should be used.
251
This does not require a branch as we use it to find the repo for
252
new branches as well as to hook existing branches up to their
255
raise NotImplementedError(self.find_repository)
257
def open_workingtree(self, _unsupported=False,
258
recommend_upgrade=True, from_branch=None):
259
"""Open the workingtree object at this ControlDir if one is present.
261
:param recommend_upgrade: Optional keyword parameter, when True (the
262
default), emit through the ui module a recommendation that the user
263
upgrade the working tree when the workingtree being opened is old
264
(but still fully supported).
265
:param from_branch: override controldir branch (for lightweight
268
raise NotImplementedError(self.open_workingtree)
270
def has_branch(self, name=None):
271
"""Tell if this controldir contains a branch.
273
Note: if you're going to open the branch, you should just go ahead
274
and try, and not ask permission first. (This method just opens the
275
branch and discards it, and that's somewhat expensive.)
278
self.open_branch(name)
280
except errors.NotBranchError:
283
def _get_selected_branch(self):
284
"""Return the name of the branch selected by the user.
286
:return: Name of the branch selected by the user, or None.
288
branch = self.root_transport.get_segment_parameters().get("branch")
289
if branch is not None:
290
branch = urlutils.unescape(branch)
293
def has_workingtree(self):
294
"""Tell if this controldir contains a working tree.
296
This will still raise an exception if the controldir has a workingtree
297
that is remote & inaccessible.
299
Note: if you're going to open the working tree, you should just go ahead
300
and try, and not ask permission first. (This method just opens the
301
workingtree and discards it, and that's somewhat expensive.)
304
self.open_workingtree(recommend_upgrade=False)
306
except errors.NoWorkingTree:
309
def cloning_metadir(self, require_stacking=False):
310
"""Produce a metadir suitable for cloning or sprouting with.
312
These operations may produce workingtrees (yes, even though they're
313
"cloning" something that doesn't have a tree), so a viable workingtree
314
format must be selected.
316
:require_stacking: If True, non-stackable formats will be upgraded
317
to similar stackable formats.
318
:returns: a ControlDirFormat with all component formats either set
319
appropriately or set to None if that component should not be
322
raise NotImplementedError(self.cloning_metadir)
324
def checkout_metadir(self):
325
"""Produce a metadir suitable for checkouts of this controldir."""
326
return self.cloning_metadir()
328
def sprout(self, url, revision_id=None, force_new_repo=False,
329
recurse='down', possible_transports=None,
330
accelerator_tree=None, hardlink=False, stacked=False,
331
source_branch=None, create_tree_if_local=True):
332
"""Create a copy of this controldir prepared for use as a new line of
335
If url's last component does not exist, it will be created.
337
Attributes related to the identity of the source branch like
338
branch nickname will be cleaned, a working tree is created
339
whether one existed before or not; and a local branch is always
342
:param revision_id: if revision_id is not None, then the clone
343
operation may tune itself to download less data.
344
:param accelerator_tree: A tree which can be used for retrieving file
345
contents more quickly than the revision tree, i.e. a workingtree.
346
The revision tree will be used for cases where accelerator_tree's
347
content is different.
348
:param hardlink: If true, hard-link files from accelerator_tree,
350
:param stacked: If true, create a stacked branch referring to the
351
location of this control directory.
352
:param create_tree_if_local: If true, a working-tree will be created
353
when working locally.
355
raise NotImplementedError(self.sprout)
357
def push_branch(self, source, revision_id=None, overwrite=False,
358
remember=False, create_prefix=False):
359
"""Push the source branch into this ControlDir."""
361
# If we can open a branch, use its direct repository, otherwise see
362
# if there is a repository without a branch.
364
br_to = self.open_branch()
365
except errors.NotBranchError:
366
# Didn't find a branch, can we find a repository?
367
repository_to = self.find_repository()
369
# Found a branch, so we must have found a repository
370
repository_to = br_to.repository
372
push_result = PushResult()
373
push_result.source_branch = source
375
# We have a repository but no branch, copy the revisions, and then
377
if revision_id is None:
378
# No revision supplied by the user, default to the branch
380
revision_id = source.last_revision()
381
repository_to.fetch(source.repository, revision_id=revision_id)
382
br_to = source.clone(self, revision_id=revision_id)
383
if source.get_push_location() is None or remember:
384
source.set_push_location(br_to.base)
385
push_result.stacked_on = None
386
push_result.branch_push_result = None
387
push_result.old_revno = None
388
push_result.old_revid = _mod_revision.NULL_REVISION
389
push_result.target_branch = br_to
390
push_result.master_branch = None
391
push_result.workingtree_updated = False
393
# We have successfully opened the branch, remember if necessary:
394
if source.get_push_location() is None or remember:
395
source.set_push_location(br_to.base)
397
tree_to = self.open_workingtree()
398
except errors.NotLocalUrl:
399
push_result.branch_push_result = source.push(br_to,
400
overwrite, stop_revision=revision_id)
401
push_result.workingtree_updated = False
402
except errors.NoWorkingTree:
403
push_result.branch_push_result = source.push(br_to,
404
overwrite, stop_revision=revision_id)
405
push_result.workingtree_updated = None # Not applicable
409
push_result.branch_push_result = source.push(
410
tree_to.branch, overwrite, stop_revision=revision_id)
414
push_result.workingtree_updated = True
415
push_result.old_revno = push_result.branch_push_result.old_revno
416
push_result.old_revid = push_result.branch_push_result.old_revid
417
push_result.target_branch = \
418
push_result.branch_push_result.target_branch
421
def _get_tree_branch(self, name=None):
422
"""Return the branch and tree, if any, for this controldir.
424
:param name: Name of colocated branch to open.
426
Return None for tree if not present or inaccessible.
427
Raise NotBranchError if no branch is present.
428
:return: (tree, branch)
431
tree = self.open_workingtree()
432
except (errors.NoWorkingTree, errors.NotLocalUrl):
434
branch = self.open_branch(name=name)
437
branch = self.open_branch(name=name)
442
def get_config(self):
443
"""Get configuration for this ControlDir."""
444
raise NotImplementedError(self.get_config)
446
def check_conversion_target(self, target_format):
447
"""Check that a controldir as a whole can be converted to a new format."""
448
raise NotImplementedError(self.check_conversion_target)
450
def clone(self, url, revision_id=None, force_new_repo=False,
451
preserve_stacking=False):
452
"""Clone this controldir and its contents to url verbatim.
454
:param url: The url create the clone at. If url's last component does
455
not exist, it will be created.
456
:param revision_id: The tip revision-id to use for any branch or
457
working tree. If not None, then the clone operation may tune
458
itself to download less data.
459
:param force_new_repo: Do not use a shared repository for the target
460
even if one is available.
461
:param preserve_stacking: When cloning a stacked branch, stack the
462
new branch on top of the other branch's stacked-on branch.
464
return self.clone_on_transport(_mod_transport.get_transport(url),
465
revision_id=revision_id,
466
force_new_repo=force_new_repo,
467
preserve_stacking=preserve_stacking)
469
def clone_on_transport(self, transport, revision_id=None,
470
force_new_repo=False, preserve_stacking=False, stacked_on=None,
471
create_prefix=False, use_existing_dir=True, no_tree=False):
472
"""Clone this controldir and its contents to transport verbatim.
474
:param transport: The transport for the location to produce the clone
475
at. If the target directory does not exist, it will be created.
476
:param revision_id: The tip revision-id to use for any branch or
477
working tree. If not None, then the clone operation may tune
478
itself to download less data.
479
:param force_new_repo: Do not use a shared repository for the target,
480
even if one is available.
481
:param preserve_stacking: When cloning a stacked branch, stack the
482
new branch on top of the other branch's stacked-on branch.
483
:param create_prefix: Create any missing directories leading up to
485
:param use_existing_dir: Use an existing directory if one exists.
486
:param no_tree: If set to true prevents creation of a working tree.
488
raise NotImplementedError(self.clone_on_transport)
491
def find_bzrdirs(klass, transport, evaluate=None, list_current=None):
492
"""Find control dirs recursively from current location.
494
This is intended primarily as a building block for more sophisticated
495
functionality, like finding trees under a directory, or finding
496
branches that use a given repository.
498
:param evaluate: An optional callable that yields recurse, value,
499
where recurse controls whether this controldir is recursed into
500
and value is the value to yield. By default, all bzrdirs
501
are recursed into, and the return value is the controldir.
502
:param list_current: if supplied, use this function to list the current
503
directory, instead of Transport.list_dir
504
:return: a generator of found bzrdirs, or whatever evaluate returns.
506
if list_current is None:
507
def list_current(transport):
508
return transport.list_dir('')
510
def evaluate(controldir):
511
return True, controldir
513
pending = [transport]
514
while len(pending) > 0:
515
current_transport = pending.pop()
518
controldir = klass.open_from_transport(current_transport)
519
except (errors.NotBranchError, errors.PermissionDenied):
522
recurse, value = evaluate(controldir)
525
subdirs = list_current(current_transport)
526
except (errors.NoSuchFile, errors.PermissionDenied):
529
for subdir in sorted(subdirs, reverse=True):
530
pending.append(current_transport.clone(subdir))
533
def find_branches(klass, transport):
534
"""Find all branches under a transport.
536
This will find all branches below the transport, including branches
537
inside other branches. Where possible, it will use
538
Repository.find_branches.
540
To list all the branches that use a particular Repository, see
541
Repository.find_branches
543
def evaluate(controldir):
545
repository = controldir.open_repository()
546
except errors.NoRepositoryPresent:
549
return False, ([], repository)
550
return True, (controldir.list_branches(), None)
552
for branches, repo in klass.find_bzrdirs(
553
transport, evaluate=evaluate):
555
ret.extend(repo.find_branches())
556
if branches is not None:
561
def create_branch_and_repo(klass, base, force_new_repo=False, format=None):
562
"""Create a new ControlDir, Branch and Repository at the url 'base'.
564
This will use the current default ControlDirFormat unless one is
565
specified, and use whatever
566
repository format that that uses via controldir.create_branch and
567
create_repository. If a shared repository is available that is used
570
The created Branch object is returned.
572
:param base: The URL to create the branch at.
573
:param force_new_repo: If True a new repository is always created.
574
:param format: If supplied, the format of branch to create. If not
575
supplied, the default is used.
577
controldir = klass.create(base, format)
578
controldir._find_or_create_repository(force_new_repo)
579
return controldir.create_branch()
582
def create_branch_convenience(klass, base, force_new_repo=False,
583
force_new_tree=None, format=None,
584
possible_transports=None):
585
"""Create a new ControlDir, Branch and Repository at the url 'base'.
587
This is a convenience function - it will use an existing repository
588
if possible, can be told explicitly whether to create a working tree or
591
This will use the current default ControlDirFormat unless one is
592
specified, and use whatever
593
repository format that that uses via ControlDir.create_branch and
594
create_repository. If a shared repository is available that is used
595
preferentially. Whatever repository is used, its tree creation policy
598
The created Branch object is returned.
599
If a working tree cannot be made due to base not being a file:// url,
600
no error is raised unless force_new_tree is True, in which case no
601
data is created on disk and NotLocalUrl is raised.
603
:param base: The URL to create the branch at.
604
:param force_new_repo: If True a new repository is always created.
605
:param force_new_tree: If True or False force creation of a tree or
606
prevent such creation respectively.
607
:param format: Override for the controldir format to create.
608
:param possible_transports: An optional reusable transports list.
611
# check for non local urls
612
t = _mod_transport.get_transport(base, possible_transports)
613
if not isinstance(t, local.LocalTransport):
614
raise errors.NotLocalUrl(base)
615
controldir = klass.create(base, format, possible_transports)
616
repo = controldir._find_or_create_repository(force_new_repo)
617
result = controldir.create_branch()
618
if force_new_tree or (repo.make_working_trees() and
619
force_new_tree is None):
621
controldir.create_workingtree()
622
except errors.NotLocalUrl:
627
def create_standalone_workingtree(klass, base, format=None):
628
"""Create a new ControlDir, WorkingTree, Branch and Repository at 'base'.
630
'base' must be a local path or a file:// url.
632
This will use the current default ControlDirFormat unless one is
633
specified, and use whatever
634
repository format that that uses for bzrdirformat.create_workingtree,
635
create_branch and create_repository.
637
:param format: Override for the controldir format to create.
638
:return: The WorkingTree object.
640
t = _mod_transport.get_transport(base)
641
if not isinstance(t, local.LocalTransport):
642
raise errors.NotLocalUrl(base)
643
controldir = klass.create_branch_and_repo(base,
645
format=format).bzrdir
646
return controldir.create_workingtree()
649
def open_unsupported(klass, base):
650
"""Open a branch which is not supported."""
651
return klass.open(base, _unsupported=True)
654
def open(klass, base, _unsupported=False, possible_transports=None):
655
"""Open an existing controldir, rooted at 'base' (url).
657
:param _unsupported: a private parameter to the ControlDir class.
659
t = _mod_transport.get_transport(base, possible_transports)
660
return klass.open_from_transport(t, _unsupported=_unsupported)
663
def open_from_transport(klass, transport, _unsupported=False,
664
_server_formats=True):
665
"""Open a controldir within a particular directory.
667
:param transport: Transport containing the controldir.
668
:param _unsupported: private.
670
for hook in klass.hooks['pre_open']:
672
# Keep initial base since 'transport' may be modified while following
674
base = transport.base
675
def find_format(transport):
676
return transport, ControlDirFormat.find_format(
677
transport, _server_formats=_server_formats)
679
def redirected(transport, e, redirection_notice):
680
redirected_transport = transport._redirected_to(e.source, e.target)
681
if redirected_transport is None:
682
raise errors.NotBranchError(base)
683
trace.note(gettext('{0} is{1} redirected to {2}').format(
684
transport.base, e.permanently, redirected_transport.base))
685
return redirected_transport
688
transport, format = _mod_transport.do_catching_redirections(
689
find_format, transport, redirected)
690
except errors.TooManyRedirections:
691
raise errors.NotBranchError(base)
693
format.check_support_status(_unsupported)
694
return format.open(transport, _found=True)
697
def open_containing(klass, url, possible_transports=None):
698
"""Open an existing branch which contains url.
700
:param url: url to search from.
702
See open_containing_from_transport for more detail.
704
transport = _mod_transport.get_transport(url, possible_transports)
705
return klass.open_containing_from_transport(transport)
708
def open_containing_from_transport(klass, a_transport):
709
"""Open an existing branch which contains a_transport.base.
711
This probes for a branch at a_transport, and searches upwards from there.
713
Basically we keep looking up until we find the control directory or
714
run into the root. If there isn't one, raises NotBranchError.
715
If there is one and it is either an unrecognised format or an unsupported
716
format, UnknownFormatError or UnsupportedFormatError are raised.
717
If there is one, it is returned, along with the unused portion of url.
719
:return: The ControlDir that contains the path, and a Unicode path
720
for the rest of the URL.
722
# this gets the normalised url back. I.e. '.' -> the full path.
723
url = a_transport.base
726
result = klass.open_from_transport(a_transport)
727
return result, urlutils.unescape(a_transport.relpath(url))
728
except errors.NotBranchError, e:
731
new_t = a_transport.clone('..')
732
except errors.InvalidURLJoin:
733
# reached the root, whatever that may be
734
raise errors.NotBranchError(path=url)
735
if new_t.base == a_transport.base:
736
# reached the root, whatever that may be
737
raise errors.NotBranchError(path=url)
741
def open_tree_or_branch(klass, location):
742
"""Return the branch and working tree at a location.
744
If there is no tree at the location, tree will be None.
745
If there is no branch at the location, an exception will be
747
:return: (tree, branch)
749
controldir = klass.open(location)
750
return controldir._get_tree_branch()
753
def open_containing_tree_or_branch(klass, location):
754
"""Return the branch and working tree contained by a location.
756
Returns (tree, branch, relpath).
757
If there is no tree at containing the location, tree will be None.
758
If there is no branch containing the location, an exception will be
760
relpath is the portion of the path that is contained by the branch.
762
controldir, relpath = klass.open_containing(location)
763
tree, branch = controldir._get_tree_branch()
764
return tree, branch, relpath
767
def open_containing_tree_branch_or_repository(klass, location):
768
"""Return the working tree, branch and repo contained by a location.
770
Returns (tree, branch, repository, relpath).
771
If there is no tree containing the location, tree will be None.
772
If there is no branch containing the location, branch will be None.
773
If there is no repository containing the location, repository will be
775
relpath is the portion of the path that is contained by the innermost
778
If no tree, branch or repository is found, a NotBranchError is raised.
780
controldir, relpath = klass.open_containing(location)
782
tree, branch = controldir._get_tree_branch()
783
except errors.NotBranchError:
785
repo = controldir.find_repository()
786
return None, None, repo, relpath
787
except (errors.NoRepositoryPresent):
788
raise errors.NotBranchError(location)
789
return tree, branch, branch.repository, relpath
792
def create(klass, base, format=None, possible_transports=None):
793
"""Create a new ControlDir at the url 'base'.
795
:param format: If supplied, the format of branch to create. If not
796
supplied, the default is used.
797
:param possible_transports: If supplied, a list of transports that
798
can be reused to share a remote connection.
800
if klass is not ControlDir:
801
raise AssertionError("ControlDir.create always creates the"
802
"default format, not one of %r" % klass)
803
t = _mod_transport.get_transport(base, possible_transports)
806
format = ControlDirFormat.get_default_format()
807
return format.initialize_on_transport(t)
810
class ControlDirHooks(hooks.Hooks):
811
"""Hooks for ControlDir operations."""
814
"""Create the default hooks."""
815
hooks.Hooks.__init__(self, "bzrlib.controldir", "ControlDir.hooks")
816
self.add_hook('pre_open',
817
"Invoked before attempting to open a ControlDir with the transport "
818
"that the open will use.", (1, 14))
819
self.add_hook('post_repo_init',
820
"Invoked after a repository has been initialized. "
821
"post_repo_init is called with a "
822
"bzrlib.controldir.RepoInitHookParams.",
825
# install the default hooks
826
ControlDir.hooks = ControlDirHooks()
829
class ControlComponentFormat(object):
830
"""A component that can live inside of a .bzr meta directory."""
832
upgrade_recommended = False
834
def get_format_string(self):
835
"""Return the format of this format, if usable in meta directories."""
836
raise NotImplementedError(self.get_format_string)
838
def get_format_description(self):
839
"""Return the short description for this format."""
840
raise NotImplementedError(self.get_format_description)
842
def is_supported(self):
843
"""Is this format supported?
845
Supported formats must be initializable and openable.
846
Unsupported formats may not support initialization or committing or
847
some other features depending on the reason for not being supported.
851
def check_support_status(self, allow_unsupported, recommend_upgrade=True,
853
"""Give an error or warning on old formats.
855
:param allow_unsupported: If true, allow opening
856
formats that are strongly deprecated, and which may
857
have limited functionality.
859
:param recommend_upgrade: If true (default), warn
860
the user through the ui object that they may wish
861
to upgrade the object.
863
if not allow_unsupported and not self.is_supported():
864
# see open_downlevel to open legacy branches.
865
raise errors.UnsupportedFormatError(format=self)
866
if recommend_upgrade and self.upgrade_recommended:
867
ui.ui_factory.recommend_upgrade(
868
self.get_format_description(), basedir)
871
class ControlComponentFormatRegistry(registry.FormatRegistry):
872
"""A registry for control components (branch, workingtree, repository)."""
874
def __init__(self, other_registry=None):
875
super(ControlComponentFormatRegistry, self).__init__(other_registry)
876
self._extra_formats = []
878
def register(self, format):
879
"""Register a new format."""
880
super(ControlComponentFormatRegistry, self).register(
881
format.get_format_string(), format)
883
def remove(self, format):
884
"""Remove a registered format."""
885
super(ControlComponentFormatRegistry, self).remove(
886
format.get_format_string())
888
def register_extra(self, format):
889
"""Register a format that can not be used in a metadir.
891
This is mainly useful to allow custom repository formats, such as older
892
Bazaar formats and foreign formats, to be tested.
894
self._extra_formats.append(registry._ObjectGetter(format))
896
def remove_extra(self, format):
897
"""Remove an extra format.
899
self._extra_formats.remove(registry._ObjectGetter(format))
901
def register_extra_lazy(self, module_name, member_name):
902
"""Register a format lazily.
904
self._extra_formats.append(
905
registry._LazyObjectGetter(module_name, member_name))
907
def _get_extra(self):
908
"""Return all "extra" formats, not usable in meta directories."""
910
for getter in self._extra_formats:
918
"""Return all formats, even those not usable in metadirs.
921
for name in self.keys():
926
return result + self._get_extra()
928
def _get_all_modules(self):
929
"""Return a set of the modules providing objects."""
931
for name in self.keys():
932
modules.add(self._get_module(name))
933
for getter in self._extra_formats:
934
modules.add(getter.get_module())
938
class Converter(object):
939
"""Converts a disk format object from one format to another."""
941
def convert(self, to_convert, pb):
942
"""Perform the conversion of to_convert, giving feedback via pb.
944
:param to_convert: The disk object to convert.
945
:param pb: a progress bar to use for progress information.
948
def step(self, message):
949
"""Update the pb by a step."""
951
self.pb.update(message, self.count, self.total)
954
class ControlDirFormat(object):
955
"""An encapsulation of the initialization and open routines for a format.
957
Formats provide three things:
958
* An initialization routine,
962
Formats are placed in a dict by their format string for reference
963
during controldir opening. These should be subclasses of ControlDirFormat
966
Once a format is deprecated, just deprecate the initialize and open
967
methods on the format class. Do not deprecate the object, as the
968
object will be created every system load.
970
:cvar colocated_branches: Whether this formats supports colocated branches.
971
:cvar supports_workingtrees: This control directory can co-exist with a
975
_default_format = None
976
"""The default format used for new control directories."""
979
"""The registered server format probers, e.g. RemoteBzrProber.
981
This is a list of Prober-derived classes.
985
"""The registered format probers, e.g. BzrProber.
987
This is a list of Prober-derived classes.
990
colocated_branches = False
991
"""Whether co-located branches are supported for this control dir format.
994
supports_workingtrees = True
995
"""Whether working trees can exist in control directories of this format.
998
fixed_components = False
999
"""Whether components can not change format independent of the control dir.
1002
upgrade_recommended = False
1003
"""Whether an upgrade from this format is recommended."""
1005
def get_format_description(self):
1006
"""Return the short description for this format."""
1007
raise NotImplementedError(self.get_format_description)
1009
def get_converter(self, format=None):
1010
"""Return the converter to use to convert controldirs needing converts.
1012
This returns a bzrlib.controldir.Converter object.
1014
This should return the best upgrader to step this format towards the
1015
current default format. In the case of plugins we can/should provide
1016
some means for them to extend the range of returnable converters.
1018
:param format: Optional format to override the default format of the
1021
raise NotImplementedError(self.get_converter)
1023
def is_supported(self):
1024
"""Is this format supported?
1026
Supported formats must be openable.
1027
Unsupported formats may not support initialization or committing or
1028
some other features depending on the reason for not being supported.
1032
def is_initializable(self):
1033
"""Whether new control directories of this format can be initialized.
1035
return self.is_supported()
1037
def check_support_status(self, allow_unsupported, recommend_upgrade=True,
1039
"""Give an error or warning on old formats.
1041
:param allow_unsupported: If true, allow opening
1042
formats that are strongly deprecated, and which may
1043
have limited functionality.
1045
:param recommend_upgrade: If true (default), warn
1046
the user through the ui object that they may wish
1047
to upgrade the object.
1049
if not allow_unsupported and not self.is_supported():
1050
# see open_downlevel to open legacy branches.
1051
raise errors.UnsupportedFormatError(format=self)
1052
if recommend_upgrade and self.upgrade_recommended:
1053
ui.ui_factory.recommend_upgrade(
1054
self.get_format_description(), basedir)
1056
def same_model(self, target_format):
1057
return (self.repository_format.rich_root_data ==
1058
target_format.rich_root_data)
1061
def register_format(klass, format):
1062
"""Register a format that does not use '.bzr' for its control dir.
1065
raise errors.BzrError("ControlDirFormat.register_format() has been "
1066
"removed in Bazaar 2.4. Please upgrade your plugins.")
1069
def register_prober(klass, prober):
1070
"""Register a prober that can look for a control dir.
1073
klass._probers.append(prober)
1076
def unregister_prober(klass, prober):
1077
"""Unregister a prober.
1080
klass._probers.remove(prober)
1083
def register_server_prober(klass, prober):
1084
"""Register a control format prober for client-server environments.
1086
These probers will be used before ones registered with
1087
register_prober. This gives implementations that decide to the
1088
chance to grab it before anything looks at the contents of the format
1091
klass._server_probers.append(prober)
1095
return self.get_format_description().rstrip()
1098
def known_formats(klass):
1099
"""Return all the known formats.
1102
for prober_kls in klass._probers + klass._server_probers:
1103
result.update(prober_kls.known_formats())
1107
def find_format(klass, transport, _server_formats=True):
1108
"""Return the format present at transport."""
1110
_probers = klass._server_probers + klass._probers
1112
_probers = klass._probers
1113
for prober_kls in _probers:
1114
prober = prober_kls()
1116
return prober.probe_transport(transport)
1117
except errors.NotBranchError:
1118
# this format does not find a control dir here.
1120
raise errors.NotBranchError(path=transport.base)
1122
def initialize(self, url, possible_transports=None):
1123
"""Create a control dir at this url and return an opened copy.
1125
While not deprecated, this method is very specific and its use will
1126
lead to many round trips to setup a working environment. See
1127
initialize_on_transport_ex for a [nearly] all-in-one method.
1129
Subclasses should typically override initialize_on_transport
1130
instead of this method.
1132
return self.initialize_on_transport(
1133
_mod_transport.get_transport(url, possible_transports))
1135
def initialize_on_transport(self, transport):
1136
"""Initialize a new controldir in the base directory of a Transport."""
1137
raise NotImplementedError(self.initialize_on_transport)
1139
def initialize_on_transport_ex(self, transport, use_existing_dir=False,
1140
create_prefix=False, force_new_repo=False, stacked_on=None,
1141
stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
1142
shared_repo=False, vfs_only=False):
1143
"""Create this format on transport.
1145
The directory to initialize will be created.
1147
:param force_new_repo: Do not use a shared repository for the target,
1148
even if one is available.
1149
:param create_prefix: Create any missing directories leading up to
1151
:param use_existing_dir: Use an existing directory if one exists.
1152
:param stacked_on: A url to stack any created branch on, None to follow
1153
any target stacking policy.
1154
:param stack_on_pwd: If stack_on is relative, the location it is
1156
:param repo_format_name: If non-None, a repository will be
1157
made-or-found. Should none be found, or if force_new_repo is True
1158
the repo_format_name is used to select the format of repository to
1160
:param make_working_trees: Control the setting of make_working_trees
1161
for a new shared repository when one is made. None to use whatever
1162
default the format has.
1163
:param shared_repo: Control whether made repositories are shared or
1165
:param vfs_only: If True do not attempt to use a smart server
1166
:return: repo, controldir, require_stacking, repository_policy. repo is
1167
None if none was created or found, controldir is always valid.
1168
require_stacking is the result of examining the stacked_on
1169
parameter and any stacking policy found for the target.
1171
raise NotImplementedError(self.initialize_on_transport_ex)
1173
def network_name(self):
1174
"""A simple byte string uniquely identifying this format for RPC calls.
1176
Bzr control formats use this disk format string to identify the format
1177
over the wire. Its possible that other control formats have more
1178
complex detection requirements, so we permit them to use any unique and
1179
immutable string they desire.
1181
raise NotImplementedError(self.network_name)
1183
def open(self, transport, _found=False):
1184
"""Return an instance of this format for the dir transport points at.
1186
raise NotImplementedError(self.open)
1189
def _set_default_format(klass, format):
1190
"""Set default format (for testing behavior of defaults only)"""
1191
klass._default_format = format
1194
def get_default_format(klass):
1195
"""Return the current default format."""
1196
return klass._default_format
1198
def supports_transport(self, transport):
1199
"""Check if this format can be opened over a particular transport.
1201
raise NotImplementedError(self.supports_transport)
1204
class Prober(object):
1205
"""Abstract class that can be used to detect a particular kind of
1208
At the moment this just contains a single method to probe a particular
1209
transport, but it may be extended in the future to e.g. avoid
1210
multiple levels of probing for Subversion repositories.
1212
See BzrProber and RemoteBzrProber in bzrlib.bzrdir for the
1213
probers that detect .bzr/ directories and Bazaar smart servers,
1216
Probers should be registered using the register_server_prober or
1217
register_prober methods on ControlDirFormat.
1220
def probe_transport(self, transport):
1221
"""Return the controldir style format present in a directory.
1223
:raise UnknownFormatError: If a control dir was found but is
1224
in an unknown format.
1225
:raise NotBranchError: If no control directory was found.
1226
:return: A ControlDirFormat instance.
1228
raise NotImplementedError(self.probe_transport)
1231
def known_formats(klass):
1232
"""Return the control dir formats known by this prober.
1234
Multiple probers can return the same formats, so this should
1237
:return: A set of known formats.
1239
raise NotImplementedError(klass.known_formats)
1242
class ControlDirFormatInfo(object):
1244
def __init__(self, native, deprecated, hidden, experimental):
1245
self.deprecated = deprecated
1246
self.native = native
1247
self.hidden = hidden
1248
self.experimental = experimental
1251
class ControlDirFormatRegistry(registry.Registry):
1252
"""Registry of user-selectable ControlDir subformats.
1254
Differs from ControlDirFormat._formats in that it provides sub-formats,
1255
e.g. BzrDirMeta1 with weave repository. Also, it's more user-oriented.
1259
"""Create a ControlDirFormatRegistry."""
1260
self._aliases = set()
1261
self._registration_order = list()
1262
super(ControlDirFormatRegistry, self).__init__()
1265
"""Return a set of the format names which are aliases."""
1266
return frozenset(self._aliases)
1268
def register(self, key, factory, help, native=True, deprecated=False,
1269
hidden=False, experimental=False, alias=False):
1270
"""Register a ControlDirFormat factory.
1272
The factory must be a callable that takes one parameter: the key.
1273
It must produce an instance of the ControlDirFormat when called.
1275
This function mainly exists to prevent the info object from being
1278
registry.Registry.register(self, key, factory, help,
1279
ControlDirFormatInfo(native, deprecated, hidden, experimental))
1281
self._aliases.add(key)
1282
self._registration_order.append(key)
1284
def register_lazy(self, key, module_name, member_name, help, native=True,
1285
deprecated=False, hidden=False, experimental=False, alias=False):
1286
registry.Registry.register_lazy(self, key, module_name, member_name,
1287
help, ControlDirFormatInfo(native, deprecated, hidden, experimental))
1289
self._aliases.add(key)
1290
self._registration_order.append(key)
1292
def set_default(self, key):
1293
"""Set the 'default' key to be a clone of the supplied key.
1295
This method must be called once and only once.
1297
registry.Registry.register(self, 'default', self.get(key),
1298
self.get_help(key), info=self.get_info(key))
1299
self._aliases.add('default')
1301
def set_default_repository(self, key):
1302
"""Set the FormatRegistry default and Repository default.
1304
This is a transitional method while Repository.set_default_format
1307
if 'default' in self:
1308
self.remove('default')
1309
self.set_default(key)
1310
format = self.get('default')()
1312
def make_bzrdir(self, key):
1313
return self.get(key)()
1315
def help_topic(self, topic):
1317
default_realkey = None
1318
default_help = self.get_help('default')
1320
for key in self._registration_order:
1321
if key == 'default':
1323
help = self.get_help(key)
1324
if help == default_help:
1325
default_realkey = key
1327
help_pairs.append((key, help))
1329
def wrapped(key, help, info):
1331
help = '(native) ' + help
1332
return ':%s:\n%s\n\n' % (key,
1333
textwrap.fill(help, initial_indent=' ',
1334
subsequent_indent=' ',
1335
break_long_words=False))
1336
if default_realkey is not None:
1337
output += wrapped(default_realkey, '(default) %s' % default_help,
1338
self.get_info('default'))
1339
deprecated_pairs = []
1340
experimental_pairs = []
1341
for key, help in help_pairs:
1342
info = self.get_info(key)
1345
elif info.deprecated:
1346
deprecated_pairs.append((key, help))
1347
elif info.experimental:
1348
experimental_pairs.append((key, help))
1350
output += wrapped(key, help, info)
1351
output += "\nSee :doc:`formats-help` for more about storage formats."
1353
if len(experimental_pairs) > 0:
1354
other_output += "Experimental formats are shown below.\n\n"
1355
for key, help in experimental_pairs:
1356
info = self.get_info(key)
1357
other_output += wrapped(key, help, info)
1360
"No experimental formats are available.\n\n"
1361
if len(deprecated_pairs) > 0:
1362
other_output += "\nDeprecated formats are shown below.\n\n"
1363
for key, help in deprecated_pairs:
1364
info = self.get_info(key)
1365
other_output += wrapped(key, help, info)
1368
"\nNo deprecated formats are available.\n\n"
1370
"\nSee :doc:`formats-help` for more about storage formats."
1372
if topic == 'other-formats':
1378
class RepoInitHookParams(object):
1379
"""Object holding parameters passed to `*_repo_init` hooks.
1381
There are 4 fields that hooks may wish to access:
1383
:ivar repository: Repository created
1384
:ivar format: Repository format
1385
:ivar bzrdir: The controldir for the repository
1386
:ivar shared: The repository is shared
1389
def __init__(self, repository, format, controldir, shared):
1390
"""Create a group of RepoInitHook parameters.
1392
:param repository: Repository created
1393
:param format: Repository format
1394
:param controldir: The controldir for the repository
1395
:param shared: The repository is shared
1397
self.repository = repository
1398
self.format = format
1399
self.bzrdir = controldir
1400
self.shared = shared
1402
def __eq__(self, other):
1403
return self.__dict__ == other.__dict__
1407
return "<%s for %s>" % (self.__class__.__name__,
1410
return "<%s for %s>" % (self.__class__.__name__,
1414
# Please register new formats after old formats so that formats
1415
# appear in chronological order and format descriptions can build
1417
format_registry = ControlDirFormatRegistry()
1419
network_format_registry = registry.FormatRegistry()
1420
"""Registry of formats indexed by their network name.
1422
The network name for a ControlDirFormat is an identifier that can be used when
1423
referring to formats with smart server operations. See
1424
ControlDirFormat.network_name() for more detail.