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 __future__ import absolute_import
27
from bzrlib.lazy_import import lazy_import
28
lazy_import(globals(), """
34
revision as _mod_revision,
35
transport as _mod_transport,
40
from bzrlib.transport import local
41
from bzrlib.push import (
45
from bzrlib.i18n import gettext
48
from bzrlib import registry
51
class ControlComponent(object):
52
"""Abstract base class for control directory components.
54
This provides interfaces that are common across controldirs,
55
repositories, branches, and workingtree control directories.
57
They all expose two urls and transports: the *user* URL is the
58
one that stops above the control directory (eg .bzr) and that
59
should normally be used in messages, and the *control* URL is
60
under that in eg .bzr/checkout and is used to read the control
63
This can be used as a mixin and is intended to fit with
68
def control_transport(self):
69
raise NotImplementedError
72
def control_url(self):
73
return self.control_transport.base
76
def user_transport(self):
77
raise NotImplementedError
81
return self.user_transport.base
84
class ControlDir(ControlComponent):
85
"""A control directory.
87
While this represents a generic control directory, there are a few
88
features that are present in this interface that are currently only
89
supported by one of its implementations, BzrDir.
91
These features (bound branches, stacked branches) are currently only
92
supported by Bazaar, but could be supported by other version control
93
systems as well. Implementations are required to raise the appropriate
94
exceptions when an operation is requested that is not supported.
96
This also makes life easier for API users who can rely on the
97
implementation always allowing a particular feature to be requested but
98
raising an exception when it is not supported, rather than requiring the
99
API users to check for magic attributes to see what features are supported.
102
def can_convert_format(self):
103
"""Return true if this controldir is one whose format we can convert
107
def list_branches(self):
108
"""Return a sequence of all branches local to this control directory.
111
return self.get_branches().values()
113
def get_branches(self):
114
"""Get all branches in this control directory, as a dictionary.
116
:return: Dictionary mapping branch names to instances.
119
return { None: self.open_branch() }
120
except (errors.NotBranchError, errors.NoRepositoryPresent):
123
def is_control_filename(self, filename):
124
"""True if filename is the name of a path which is reserved for
127
:param filename: A filename within the root transport of this
130
This is true IF and ONLY IF the filename is part of the namespace reserved
131
for bzr control dirs. Currently this is the '.bzr' directory in the root
132
of the root_transport. it is expected that plugins will need to extend
133
this in the future - for instance to make bzr talk with svn working
136
raise NotImplementedError(self.is_control_filename)
138
def needs_format_conversion(self, format=None):
139
"""Return true if this controldir needs convert_format run on it.
141
For instance, if the repository format is out of date but the
142
branch and working tree are not, this should return True.
144
:param format: Optional parameter indicating a specific desired
145
format we plan to arrive at.
147
raise NotImplementedError(self.needs_format_conversion)
149
def create_repository(self, shared=False):
150
"""Create a new repository in this control directory.
152
:param shared: If a shared repository should be created
153
:return: The newly created repository
155
raise NotImplementedError(self.create_repository)
157
def destroy_repository(self):
158
"""Destroy the repository in this ControlDir."""
159
raise NotImplementedError(self.destroy_repository)
161
def create_branch(self, name=None, repository=None,
162
append_revisions_only=None):
163
"""Create a branch in this ControlDir.
165
:param name: Name of the colocated branch to create, None for
167
:param append_revisions_only: Whether this branch should only allow
168
appending new revisions to its history.
170
The controldirs format will control what branch format is created.
171
For more control see BranchFormatXX.create(a_controldir).
173
raise NotImplementedError(self.create_branch)
175
def destroy_branch(self, name=None):
176
"""Destroy a branch in this ControlDir.
178
:param name: Name of the branch to destroy, None for the default
181
raise NotImplementedError(self.destroy_branch)
183
def create_workingtree(self, revision_id=None, from_branch=None,
184
accelerator_tree=None, hardlink=False):
185
"""Create a working tree at this ControlDir.
187
:param revision_id: create it as of this revision id.
188
:param from_branch: override controldir branch
189
(for lightweight checkouts)
190
:param accelerator_tree: A tree which can be used for retrieving file
191
contents more quickly than the revision tree, i.e. a workingtree.
192
The revision tree will be used for cases where accelerator_tree's
193
content is different.
195
raise NotImplementedError(self.create_workingtree)
197
def destroy_workingtree(self):
198
"""Destroy the working tree at this ControlDir.
200
Formats that do not support this may raise UnsupportedOperation.
202
raise NotImplementedError(self.destroy_workingtree)
204
def destroy_workingtree_metadata(self):
205
"""Destroy the control files for the working tree at this ControlDir.
207
The contents of working tree files are not affected.
208
Formats that do not support this may raise UnsupportedOperation.
210
raise NotImplementedError(self.destroy_workingtree_metadata)
212
def find_branch_format(self, name=None):
213
"""Find the branch 'format' for this controldir.
215
This might be a synthetic object for e.g. RemoteBranch and SVN.
217
raise NotImplementedError(self.find_branch_format)
219
def get_branch_reference(self, name=None):
220
"""Return the referenced URL for the branch in this controldir.
222
:param name: Optional colocated branch name
223
:raises NotBranchError: If there is no Branch.
224
:raises NoColocatedBranchSupport: If a branch name was specified
225
but colocated branches are not supported.
226
:return: The URL the branch in this controldir references if it is a
227
reference branch, or None for regular branches.
230
raise errors.NoColocatedBranchSupport(self)
233
def open_branch(self, name=None, unsupported=False,
234
ignore_fallbacks=False, possible_transports=None):
235
"""Open the branch object at this ControlDir if one is present.
237
:param unsupported: if True, then no longer supported branch formats can
239
:param ignore_fallbacks: Whether to open fallback repositories
240
:param possible_transports: Transports to use for opening e.g.
241
fallback repositories.
243
raise NotImplementedError(self.open_branch)
245
def open_repository(self, _unsupported=False):
246
"""Open the repository object at this ControlDir if one is present.
248
This will not follow the Branch object pointer - it's strictly a direct
249
open facility. Most client code should use open_branch().repository to
252
:param _unsupported: a private parameter, not part of the api.
254
raise NotImplementedError(self.open_repository)
256
def find_repository(self):
257
"""Find the repository that should be used.
259
This does not require a branch as we use it to find the repo for
260
new branches as well as to hook existing branches up to their
263
raise NotImplementedError(self.find_repository)
265
def open_workingtree(self, _unsupported=False,
266
recommend_upgrade=True, from_branch=None):
267
"""Open the workingtree object at this ControlDir if one is present.
269
:param recommend_upgrade: Optional keyword parameter, when True (the
270
default), emit through the ui module a recommendation that the user
271
upgrade the working tree when the workingtree being opened is old
272
(but still fully supported).
273
:param from_branch: override controldir branch (for lightweight
276
raise NotImplementedError(self.open_workingtree)
278
def has_branch(self, name=None):
279
"""Tell if this controldir contains a branch.
281
Note: if you're going to open the branch, you should just go ahead
282
and try, and not ask permission first. (This method just opens the
283
branch and discards it, and that's somewhat expensive.)
286
self.open_branch(name, ignore_fallbacks=True)
288
except errors.NotBranchError:
291
def _get_selected_branch(self):
292
"""Return the name of the branch selected by the user.
294
:return: Name of the branch selected by the user, or None.
296
branch = self.root_transport.get_segment_parameters().get("branch")
297
if branch is not None:
298
branch = urlutils.unescape(branch)
301
def has_workingtree(self):
302
"""Tell if this controldir contains a working tree.
304
This will still raise an exception if the controldir has a workingtree
305
that is remote & inaccessible.
307
Note: if you're going to open the working tree, you should just go ahead
308
and try, and not ask permission first. (This method just opens the
309
workingtree and discards it, and that's somewhat expensive.)
312
self.open_workingtree(recommend_upgrade=False)
314
except errors.NoWorkingTree:
317
def cloning_metadir(self, require_stacking=False):
318
"""Produce a metadir suitable for cloning or sprouting with.
320
These operations may produce workingtrees (yes, even though they're
321
"cloning" something that doesn't have a tree), so a viable workingtree
322
format must be selected.
324
:require_stacking: If True, non-stackable formats will be upgraded
325
to similar stackable formats.
326
:returns: a ControlDirFormat with all component formats either set
327
appropriately or set to None if that component should not be
330
raise NotImplementedError(self.cloning_metadir)
332
def checkout_metadir(self):
333
"""Produce a metadir suitable for checkouts of this controldir.
335
:returns: A ControlDirFormat with all component formats
336
either set appropriately or set to None if that component
337
should not be created.
339
return self.cloning_metadir()
341
def sprout(self, url, revision_id=None, force_new_repo=False,
342
recurse='down', possible_transports=None,
343
accelerator_tree=None, hardlink=False, stacked=False,
344
source_branch=None, create_tree_if_local=True):
345
"""Create a copy of this controldir prepared for use as a new line of
348
If url's last component does not exist, it will be created.
350
Attributes related to the identity of the source branch like
351
branch nickname will be cleaned, a working tree is created
352
whether one existed before or not; and a local branch is always
355
:param revision_id: if revision_id is not None, then the clone
356
operation may tune itself to download less data.
357
:param accelerator_tree: A tree which can be used for retrieving file
358
contents more quickly than the revision tree, i.e. a workingtree.
359
The revision tree will be used for cases where accelerator_tree's
360
content is different.
361
:param hardlink: If true, hard-link files from accelerator_tree,
363
:param stacked: If true, create a stacked branch referring to the
364
location of this control directory.
365
:param create_tree_if_local: If true, a working-tree will be created
366
when working locally.
368
raise NotImplementedError(self.sprout)
370
def push_branch(self, source, revision_id=None, overwrite=False,
371
remember=False, create_prefix=False):
372
"""Push the source branch into this ControlDir."""
374
# If we can open a branch, use its direct repository, otherwise see
375
# if there is a repository without a branch.
377
br_to = self.open_branch()
378
except errors.NotBranchError:
379
# Didn't find a branch, can we find a repository?
380
repository_to = self.find_repository()
382
# Found a branch, so we must have found a repository
383
repository_to = br_to.repository
385
push_result = PushResult()
386
push_result.source_branch = source
388
# We have a repository but no branch, copy the revisions, and then
390
if revision_id is None:
391
# No revision supplied by the user, default to the branch
393
revision_id = source.last_revision()
394
repository_to.fetch(source.repository, revision_id=revision_id)
395
br_to = source.clone(self, revision_id=revision_id)
396
if source.get_push_location() is None or remember:
397
source.set_push_location(br_to.base)
398
push_result.stacked_on = None
399
push_result.branch_push_result = None
400
push_result.old_revno = None
401
push_result.old_revid = _mod_revision.NULL_REVISION
402
push_result.target_branch = br_to
403
push_result.master_branch = None
404
push_result.workingtree_updated = False
406
# We have successfully opened the branch, remember if necessary:
407
if source.get_push_location() is None or remember:
408
source.set_push_location(br_to.base)
410
tree_to = self.open_workingtree()
411
except errors.NotLocalUrl:
412
push_result.branch_push_result = source.push(br_to,
413
overwrite, stop_revision=revision_id)
414
push_result.workingtree_updated = False
415
except errors.NoWorkingTree:
416
push_result.branch_push_result = source.push(br_to,
417
overwrite, stop_revision=revision_id)
418
push_result.workingtree_updated = None # Not applicable
422
push_result.branch_push_result = source.push(
423
tree_to.branch, overwrite, stop_revision=revision_id)
427
push_result.workingtree_updated = True
428
push_result.old_revno = push_result.branch_push_result.old_revno
429
push_result.old_revid = push_result.branch_push_result.old_revid
430
push_result.target_branch = \
431
push_result.branch_push_result.target_branch
434
def _get_tree_branch(self, name=None):
435
"""Return the branch and tree, if any, for this controldir.
437
:param name: Name of colocated branch to open.
439
Return None for tree if not present or inaccessible.
440
Raise NotBranchError if no branch is present.
441
:return: (tree, branch)
444
tree = self.open_workingtree()
445
except (errors.NoWorkingTree, errors.NotLocalUrl):
447
branch = self.open_branch(name=name)
450
branch = self.open_branch(name=name)
455
def get_config(self):
456
"""Get configuration for this ControlDir."""
457
raise NotImplementedError(self.get_config)
459
def check_conversion_target(self, target_format):
460
"""Check that a controldir as a whole can be converted to a new format."""
461
raise NotImplementedError(self.check_conversion_target)
463
def clone(self, url, revision_id=None, force_new_repo=False,
464
preserve_stacking=False):
465
"""Clone this controldir and its contents to url verbatim.
467
:param url: The url create the clone at. If url's last component does
468
not exist, it will be created.
469
:param revision_id: The tip revision-id to use for any branch or
470
working tree. If not None, then the clone operation may tune
471
itself to download less data.
472
:param force_new_repo: Do not use a shared repository for the target
473
even if one is available.
474
:param preserve_stacking: When cloning a stacked branch, stack the
475
new branch on top of the other branch's stacked-on branch.
477
return self.clone_on_transport(_mod_transport.get_transport(url),
478
revision_id=revision_id,
479
force_new_repo=force_new_repo,
480
preserve_stacking=preserve_stacking)
482
def clone_on_transport(self, transport, revision_id=None,
483
force_new_repo=False, preserve_stacking=False, stacked_on=None,
484
create_prefix=False, use_existing_dir=True, no_tree=False):
485
"""Clone this controldir and its contents to transport verbatim.
487
:param transport: The transport for the location to produce the clone
488
at. If the target directory does not exist, it will be created.
489
:param revision_id: The tip revision-id to use for any branch or
490
working tree. If not None, then the clone operation may tune
491
itself to download less data.
492
:param force_new_repo: Do not use a shared repository for the target,
493
even if one is available.
494
:param preserve_stacking: When cloning a stacked branch, stack the
495
new branch on top of the other branch's stacked-on branch.
496
:param create_prefix: Create any missing directories leading up to
498
:param use_existing_dir: Use an existing directory if one exists.
499
:param no_tree: If set to true prevents creation of a working tree.
501
raise NotImplementedError(self.clone_on_transport)
504
def find_bzrdirs(klass, transport, evaluate=None, list_current=None):
505
"""Find control dirs recursively from current location.
507
This is intended primarily as a building block for more sophisticated
508
functionality, like finding trees under a directory, or finding
509
branches that use a given repository.
511
:param evaluate: An optional callable that yields recurse, value,
512
where recurse controls whether this controldir is recursed into
513
and value is the value to yield. By default, all bzrdirs
514
are recursed into, and the return value is the controldir.
515
:param list_current: if supplied, use this function to list the current
516
directory, instead of Transport.list_dir
517
:return: a generator of found bzrdirs, or whatever evaluate returns.
519
if list_current is None:
520
def list_current(transport):
521
return transport.list_dir('')
523
def evaluate(controldir):
524
return True, controldir
526
pending = [transport]
527
while len(pending) > 0:
528
current_transport = pending.pop()
531
controldir = klass.open_from_transport(current_transport)
532
except (errors.NotBranchError, errors.PermissionDenied):
535
recurse, value = evaluate(controldir)
538
subdirs = list_current(current_transport)
539
except (errors.NoSuchFile, errors.PermissionDenied):
542
for subdir in sorted(subdirs, reverse=True):
543
pending.append(current_transport.clone(subdir))
546
def find_branches(klass, transport):
547
"""Find all branches under a transport.
549
This will find all branches below the transport, including branches
550
inside other branches. Where possible, it will use
551
Repository.find_branches.
553
To list all the branches that use a particular Repository, see
554
Repository.find_branches
556
def evaluate(controldir):
558
repository = controldir.open_repository()
559
except errors.NoRepositoryPresent:
562
return False, ([], repository)
563
return True, (controldir.list_branches(), None)
565
for branches, repo in klass.find_bzrdirs(
566
transport, evaluate=evaluate):
568
ret.extend(repo.find_branches())
569
if branches is not None:
574
def create_branch_and_repo(klass, base, force_new_repo=False, format=None):
575
"""Create a new ControlDir, Branch and Repository at the url 'base'.
577
This will use the current default ControlDirFormat unless one is
578
specified, and use whatever
579
repository format that that uses via controldir.create_branch and
580
create_repository. If a shared repository is available that is used
583
The created Branch object is returned.
585
:param base: The URL to create the branch at.
586
:param force_new_repo: If True a new repository is always created.
587
:param format: If supplied, the format of branch to create. If not
588
supplied, the default is used.
590
controldir = klass.create(base, format)
591
controldir._find_or_create_repository(force_new_repo)
592
return controldir.create_branch()
595
def create_branch_convenience(klass, base, force_new_repo=False,
596
force_new_tree=None, format=None,
597
possible_transports=None):
598
"""Create a new ControlDir, Branch and Repository at the url 'base'.
600
This is a convenience function - it will use an existing repository
601
if possible, can be told explicitly whether to create a working tree or
604
This will use the current default ControlDirFormat unless one is
605
specified, and use whatever
606
repository format that that uses via ControlDir.create_branch and
607
create_repository. If a shared repository is available that is used
608
preferentially. Whatever repository is used, its tree creation policy
611
The created Branch object is returned.
612
If a working tree cannot be made due to base not being a file:// url,
613
no error is raised unless force_new_tree is True, in which case no
614
data is created on disk and NotLocalUrl is raised.
616
:param base: The URL to create the branch at.
617
:param force_new_repo: If True a new repository is always created.
618
:param force_new_tree: If True or False force creation of a tree or
619
prevent such creation respectively.
620
:param format: Override for the controldir format to create.
621
:param possible_transports: An optional reusable transports list.
624
# check for non local urls
625
t = _mod_transport.get_transport(base, possible_transports)
626
if not isinstance(t, local.LocalTransport):
627
raise errors.NotLocalUrl(base)
628
controldir = klass.create(base, format, possible_transports)
629
repo = controldir._find_or_create_repository(force_new_repo)
630
result = controldir.create_branch()
631
if force_new_tree or (repo.make_working_trees() and
632
force_new_tree is None):
634
controldir.create_workingtree()
635
except errors.NotLocalUrl:
640
def create_standalone_workingtree(klass, base, format=None):
641
"""Create a new ControlDir, WorkingTree, Branch and Repository at 'base'.
643
'base' must be a local path or a file:// url.
645
This will use the current default ControlDirFormat unless one is
646
specified, and use whatever
647
repository format that that uses for bzrdirformat.create_workingtree,
648
create_branch and create_repository.
650
:param format: Override for the controldir format to create.
651
:return: The WorkingTree object.
653
t = _mod_transport.get_transport(base)
654
if not isinstance(t, local.LocalTransport):
655
raise errors.NotLocalUrl(base)
656
controldir = klass.create_branch_and_repo(base,
658
format=format).bzrdir
659
return controldir.create_workingtree()
662
def open_unsupported(klass, base):
663
"""Open a branch which is not supported."""
664
return klass.open(base, _unsupported=True)
667
def open(klass, base, _unsupported=False, possible_transports=None):
668
"""Open an existing controldir, rooted at 'base' (url).
670
:param _unsupported: a private parameter to the ControlDir class.
672
t = _mod_transport.get_transport(base, possible_transports)
673
return klass.open_from_transport(t, _unsupported=_unsupported)
676
def open_from_transport(klass, transport, _unsupported=False,
677
_server_formats=True):
678
"""Open a controldir within a particular directory.
680
:param transport: Transport containing the controldir.
681
:param _unsupported: private.
683
for hook in klass.hooks['pre_open']:
685
# Keep initial base since 'transport' may be modified while following
687
base = transport.base
688
def find_format(transport):
689
return transport, ControlDirFormat.find_format(
690
transport, _server_formats=_server_formats)
692
def redirected(transport, e, redirection_notice):
693
redirected_transport = transport._redirected_to(e.source, e.target)
694
if redirected_transport is None:
695
raise errors.NotBranchError(base)
696
trace.note(gettext('{0} is{1} redirected to {2}').format(
697
transport.base, e.permanently, redirected_transport.base))
698
return redirected_transport
701
transport, format = _mod_transport.do_catching_redirections(
702
find_format, transport, redirected)
703
except errors.TooManyRedirections:
704
raise errors.NotBranchError(base)
706
format.check_support_status(_unsupported)
707
return format.open(transport, _found=True)
710
def open_containing(klass, url, possible_transports=None):
711
"""Open an existing branch which contains url.
713
:param url: url to search from.
715
See open_containing_from_transport for more detail.
717
transport = _mod_transport.get_transport(url, possible_transports)
718
return klass.open_containing_from_transport(transport)
721
def open_containing_from_transport(klass, a_transport):
722
"""Open an existing branch which contains a_transport.base.
724
This probes for a branch at a_transport, and searches upwards from there.
726
Basically we keep looking up until we find the control directory or
727
run into the root. If there isn't one, raises NotBranchError.
728
If there is one and it is either an unrecognised format or an unsupported
729
format, UnknownFormatError or UnsupportedFormatError are raised.
730
If there is one, it is returned, along with the unused portion of url.
732
:return: The ControlDir that contains the path, and a Unicode path
733
for the rest of the URL.
735
# this gets the normalised url back. I.e. '.' -> the full path.
736
url = a_transport.base
739
result = klass.open_from_transport(a_transport)
740
return result, urlutils.unescape(a_transport.relpath(url))
741
except errors.NotBranchError, e:
743
except errors.PermissionDenied:
746
new_t = a_transport.clone('..')
747
except errors.InvalidURLJoin:
748
# reached the root, whatever that may be
749
raise errors.NotBranchError(path=url)
750
if new_t.base == a_transport.base:
751
# reached the root, whatever that may be
752
raise errors.NotBranchError(path=url)
756
def open_tree_or_branch(klass, location):
757
"""Return the branch and working tree at a location.
759
If there is no tree at the location, tree will be None.
760
If there is no branch at the location, an exception will be
762
:return: (tree, branch)
764
controldir = klass.open(location)
765
return controldir._get_tree_branch()
768
def open_containing_tree_or_branch(klass, location):
769
"""Return the branch and working tree contained by a location.
771
Returns (tree, branch, relpath).
772
If there is no tree at containing the location, tree will be None.
773
If there is no branch containing the location, an exception will be
775
relpath is the portion of the path that is contained by the branch.
777
controldir, relpath = klass.open_containing(location)
778
tree, branch = controldir._get_tree_branch()
779
return tree, branch, relpath
782
def open_containing_tree_branch_or_repository(klass, location):
783
"""Return the working tree, branch and repo contained by a location.
785
Returns (tree, branch, repository, relpath).
786
If there is no tree containing the location, tree will be None.
787
If there is no branch containing the location, branch will be None.
788
If there is no repository containing the location, repository will be
790
relpath is the portion of the path that is contained by the innermost
793
If no tree, branch or repository is found, a NotBranchError is raised.
795
controldir, relpath = klass.open_containing(location)
797
tree, branch = controldir._get_tree_branch()
798
except errors.NotBranchError:
800
repo = controldir.find_repository()
801
return None, None, repo, relpath
802
except (errors.NoRepositoryPresent):
803
raise errors.NotBranchError(location)
804
return tree, branch, branch.repository, relpath
807
def create(klass, base, format=None, possible_transports=None):
808
"""Create a new ControlDir at the url 'base'.
810
:param format: If supplied, the format of branch to create. If not
811
supplied, the default is used.
812
:param possible_transports: If supplied, a list of transports that
813
can be reused to share a remote connection.
815
if klass is not ControlDir:
816
raise AssertionError("ControlDir.create always creates the"
817
"default format, not one of %r" % klass)
818
t = _mod_transport.get_transport(base, possible_transports)
821
format = ControlDirFormat.get_default_format()
822
return format.initialize_on_transport(t)
825
class ControlDirHooks(hooks.Hooks):
826
"""Hooks for ControlDir operations."""
829
"""Create the default hooks."""
830
hooks.Hooks.__init__(self, "bzrlib.controldir", "ControlDir.hooks")
831
self.add_hook('pre_open',
832
"Invoked before attempting to open a ControlDir with the transport "
833
"that the open will use.", (1, 14))
834
self.add_hook('post_repo_init',
835
"Invoked after a repository has been initialized. "
836
"post_repo_init is called with a "
837
"bzrlib.controldir.RepoInitHookParams.",
840
# install the default hooks
841
ControlDir.hooks = ControlDirHooks()
844
class ControlComponentFormat(object):
845
"""A component that can live inside of a .bzr meta directory."""
847
upgrade_recommended = False
849
def get_format_description(self):
850
"""Return the short description for this format."""
851
raise NotImplementedError(self.get_format_description)
853
def is_supported(self):
854
"""Is this format supported?
856
Supported formats must be initializable and openable.
857
Unsupported formats may not support initialization or committing or
858
some other features depending on the reason for not being supported.
862
def check_support_status(self, allow_unsupported, recommend_upgrade=True,
864
"""Give an error or warning on old formats.
866
:param allow_unsupported: If true, allow opening
867
formats that are strongly deprecated, and which may
868
have limited functionality.
870
:param recommend_upgrade: If true (default), warn
871
the user through the ui object that they may wish
872
to upgrade the object.
874
if not allow_unsupported and not self.is_supported():
875
# see open_downlevel to open legacy branches.
876
raise errors.UnsupportedFormatError(format=self)
877
if recommend_upgrade and self.upgrade_recommended:
878
ui.ui_factory.recommend_upgrade(
879
self.get_format_description(), basedir)
882
def get_format_string(cls):
883
raise NotImplementedError(cls.get_format_string)
886
class ControlComponentFormatRegistry(registry.FormatRegistry):
887
"""A registry for control components (branch, workingtree, repository)."""
889
def __init__(self, other_registry=None):
890
super(ControlComponentFormatRegistry, self).__init__(other_registry)
891
self._extra_formats = []
893
def register(self, format):
894
"""Register a new format."""
895
super(ControlComponentFormatRegistry, self).register(
896
format.get_format_string(), format)
898
def remove(self, format):
899
"""Remove a registered format."""
900
super(ControlComponentFormatRegistry, self).remove(
901
format.get_format_string())
903
def register_extra(self, format):
904
"""Register a format that can not be used in a metadir.
906
This is mainly useful to allow custom repository formats, such as older
907
Bazaar formats and foreign formats, to be tested.
909
self._extra_formats.append(registry._ObjectGetter(format))
911
def remove_extra(self, format):
912
"""Remove an extra format.
914
self._extra_formats.remove(registry._ObjectGetter(format))
916
def register_extra_lazy(self, module_name, member_name):
917
"""Register a format lazily.
919
self._extra_formats.append(
920
registry._LazyObjectGetter(module_name, member_name))
922
def _get_extra(self):
923
"""Return all "extra" formats, not usable in meta directories."""
925
for getter in self._extra_formats:
933
"""Return all formats, even those not usable in metadirs.
936
for name in self.keys():
941
return result + self._get_extra()
943
def _get_all_modules(self):
944
"""Return a set of the modules providing objects."""
946
for name in self.keys():
947
modules.add(self._get_module(name))
948
for getter in self._extra_formats:
949
modules.add(getter.get_module())
953
class Converter(object):
954
"""Converts a disk format object from one format to another."""
956
def convert(self, to_convert, pb):
957
"""Perform the conversion of to_convert, giving feedback via pb.
959
:param to_convert: The disk object to convert.
960
:param pb: a progress bar to use for progress information.
963
def step(self, message):
964
"""Update the pb by a step."""
966
self.pb.update(message, self.count, self.total)
969
class ControlDirFormat(object):
970
"""An encapsulation of the initialization and open routines for a format.
972
Formats provide three things:
973
* An initialization routine,
977
Formats are placed in a dict by their format string for reference
978
during controldir opening. These should be subclasses of ControlDirFormat
981
Once a format is deprecated, just deprecate the initialize and open
982
methods on the format class. Do not deprecate the object, as the
983
object will be created every system load.
985
:cvar colocated_branches: Whether this formats supports colocated branches.
986
:cvar supports_workingtrees: This control directory can co-exist with a
990
_default_format = None
991
"""The default format used for new control directories."""
994
"""The registered server format probers, e.g. RemoteBzrProber.
996
This is a list of Prober-derived classes.
1000
"""The registered format probers, e.g. BzrProber.
1002
This is a list of Prober-derived classes.
1005
colocated_branches = False
1006
"""Whether co-located branches are supported for this control dir format.
1009
supports_workingtrees = True
1010
"""Whether working trees can exist in control directories of this format.
1013
fixed_components = False
1014
"""Whether components can not change format independent of the control dir.
1017
upgrade_recommended = False
1018
"""Whether an upgrade from this format is recommended."""
1020
def get_format_description(self):
1021
"""Return the short description for this format."""
1022
raise NotImplementedError(self.get_format_description)
1024
def get_converter(self, format=None):
1025
"""Return the converter to use to convert controldirs needing converts.
1027
This returns a bzrlib.controldir.Converter object.
1029
This should return the best upgrader to step this format towards the
1030
current default format. In the case of plugins we can/should provide
1031
some means for them to extend the range of returnable converters.
1033
:param format: Optional format to override the default format of the
1036
raise NotImplementedError(self.get_converter)
1038
def is_supported(self):
1039
"""Is this format supported?
1041
Supported formats must be openable.
1042
Unsupported formats may not support initialization or committing or
1043
some other features depending on the reason for not being supported.
1047
def is_initializable(self):
1048
"""Whether new control directories of this format can be initialized.
1050
return self.is_supported()
1052
def check_support_status(self, allow_unsupported, recommend_upgrade=True,
1054
"""Give an error or warning on old formats.
1056
:param allow_unsupported: If true, allow opening
1057
formats that are strongly deprecated, and which may
1058
have limited functionality.
1060
:param recommend_upgrade: If true (default), warn
1061
the user through the ui object that they may wish
1062
to upgrade the object.
1064
if not allow_unsupported and not self.is_supported():
1065
# see open_downlevel to open legacy branches.
1066
raise errors.UnsupportedFormatError(format=self)
1067
if recommend_upgrade and self.upgrade_recommended:
1068
ui.ui_factory.recommend_upgrade(
1069
self.get_format_description(), basedir)
1071
def same_model(self, target_format):
1072
return (self.repository_format.rich_root_data ==
1073
target_format.rich_root_data)
1076
def register_format(klass, format):
1077
"""Register a format that does not use '.bzr' for its control dir.
1080
raise errors.BzrError("ControlDirFormat.register_format() has been "
1081
"removed in Bazaar 2.4. Please upgrade your plugins.")
1084
def register_prober(klass, prober):
1085
"""Register a prober that can look for a control dir.
1088
klass._probers.append(prober)
1091
def unregister_prober(klass, prober):
1092
"""Unregister a prober.
1095
klass._probers.remove(prober)
1098
def register_server_prober(klass, prober):
1099
"""Register a control format prober for client-server environments.
1101
These probers will be used before ones registered with
1102
register_prober. This gives implementations that decide to the
1103
chance to grab it before anything looks at the contents of the format
1106
klass._server_probers.append(prober)
1110
return self.get_format_description().rstrip()
1113
def known_formats(klass):
1114
"""Return all the known formats.
1117
for prober_kls in klass._probers + klass._server_probers:
1118
result.update(prober_kls.known_formats())
1122
def find_format(klass, transport, _server_formats=True):
1123
"""Return the format present at transport."""
1125
_probers = klass._server_probers + klass._probers
1127
_probers = klass._probers
1128
for prober_kls in _probers:
1129
prober = prober_kls()
1131
return prober.probe_transport(transport)
1132
except errors.NotBranchError:
1133
# this format does not find a control dir here.
1135
raise errors.NotBranchError(path=transport.base)
1137
def initialize(self, url, possible_transports=None):
1138
"""Create a control dir at this url and return an opened copy.
1140
While not deprecated, this method is very specific and its use will
1141
lead to many round trips to setup a working environment. See
1142
initialize_on_transport_ex for a [nearly] all-in-one method.
1144
Subclasses should typically override initialize_on_transport
1145
instead of this method.
1147
return self.initialize_on_transport(
1148
_mod_transport.get_transport(url, possible_transports))
1150
def initialize_on_transport(self, transport):
1151
"""Initialize a new controldir in the base directory of a Transport."""
1152
raise NotImplementedError(self.initialize_on_transport)
1154
def initialize_on_transport_ex(self, transport, use_existing_dir=False,
1155
create_prefix=False, force_new_repo=False, stacked_on=None,
1156
stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
1157
shared_repo=False, vfs_only=False):
1158
"""Create this format on transport.
1160
The directory to initialize will be created.
1162
:param force_new_repo: Do not use a shared repository for the target,
1163
even if one is available.
1164
:param create_prefix: Create any missing directories leading up to
1166
:param use_existing_dir: Use an existing directory if one exists.
1167
:param stacked_on: A url to stack any created branch on, None to follow
1168
any target stacking policy.
1169
:param stack_on_pwd: If stack_on is relative, the location it is
1171
:param repo_format_name: If non-None, a repository will be
1172
made-or-found. Should none be found, or if force_new_repo is True
1173
the repo_format_name is used to select the format of repository to
1175
:param make_working_trees: Control the setting of make_working_trees
1176
for a new shared repository when one is made. None to use whatever
1177
default the format has.
1178
:param shared_repo: Control whether made repositories are shared or
1180
:param vfs_only: If True do not attempt to use a smart server
1181
:return: repo, controldir, require_stacking, repository_policy. repo is
1182
None if none was created or found, controldir is always valid.
1183
require_stacking is the result of examining the stacked_on
1184
parameter and any stacking policy found for the target.
1186
raise NotImplementedError(self.initialize_on_transport_ex)
1188
def network_name(self):
1189
"""A simple byte string uniquely identifying this format for RPC calls.
1191
Bzr control formats use this disk format string to identify the format
1192
over the wire. Its possible that other control formats have more
1193
complex detection requirements, so we permit them to use any unique and
1194
immutable string they desire.
1196
raise NotImplementedError(self.network_name)
1198
def open(self, transport, _found=False):
1199
"""Return an instance of this format for the dir transport points at.
1201
raise NotImplementedError(self.open)
1204
def _set_default_format(klass, format):
1205
"""Set default format (for testing behavior of defaults only)"""
1206
klass._default_format = format
1209
def get_default_format(klass):
1210
"""Return the current default format."""
1211
return klass._default_format
1213
def supports_transport(self, transport):
1214
"""Check if this format can be opened over a particular transport.
1216
raise NotImplementedError(self.supports_transport)
1219
class Prober(object):
1220
"""Abstract class that can be used to detect a particular kind of
1223
At the moment this just contains a single method to probe a particular
1224
transport, but it may be extended in the future to e.g. avoid
1225
multiple levels of probing for Subversion repositories.
1227
See BzrProber and RemoteBzrProber in bzrlib.bzrdir for the
1228
probers that detect .bzr/ directories and Bazaar smart servers,
1231
Probers should be registered using the register_server_prober or
1232
register_prober methods on ControlDirFormat.
1235
def probe_transport(self, transport):
1236
"""Return the controldir style format present in a directory.
1238
:raise UnknownFormatError: If a control dir was found but is
1239
in an unknown format.
1240
:raise NotBranchError: If no control directory was found.
1241
:return: A ControlDirFormat instance.
1243
raise NotImplementedError(self.probe_transport)
1246
def known_formats(klass):
1247
"""Return the control dir formats known by this prober.
1249
Multiple probers can return the same formats, so this should
1252
:return: A set of known formats.
1254
raise NotImplementedError(klass.known_formats)
1257
class ControlDirFormatInfo(object):
1259
def __init__(self, native, deprecated, hidden, experimental):
1260
self.deprecated = deprecated
1261
self.native = native
1262
self.hidden = hidden
1263
self.experimental = experimental
1266
class ControlDirFormatRegistry(registry.Registry):
1267
"""Registry of user-selectable ControlDir subformats.
1269
Differs from ControlDirFormat._formats in that it provides sub-formats,
1270
e.g. BzrDirMeta1 with weave repository. Also, it's more user-oriented.
1274
"""Create a ControlDirFormatRegistry."""
1275
self._aliases = set()
1276
self._registration_order = list()
1277
super(ControlDirFormatRegistry, self).__init__()
1280
"""Return a set of the format names which are aliases."""
1281
return frozenset(self._aliases)
1283
def register(self, key, factory, help, native=True, deprecated=False,
1284
hidden=False, experimental=False, alias=False):
1285
"""Register a ControlDirFormat factory.
1287
The factory must be a callable that takes one parameter: the key.
1288
It must produce an instance of the ControlDirFormat when called.
1290
This function mainly exists to prevent the info object from being
1293
registry.Registry.register(self, key, factory, help,
1294
ControlDirFormatInfo(native, deprecated, hidden, experimental))
1296
self._aliases.add(key)
1297
self._registration_order.append(key)
1299
def register_lazy(self, key, module_name, member_name, help, native=True,
1300
deprecated=False, hidden=False, experimental=False, alias=False):
1301
registry.Registry.register_lazy(self, key, module_name, member_name,
1302
help, ControlDirFormatInfo(native, deprecated, hidden, experimental))
1304
self._aliases.add(key)
1305
self._registration_order.append(key)
1307
def set_default(self, key):
1308
"""Set the 'default' key to be a clone of the supplied key.
1310
This method must be called once and only once.
1312
registry.Registry.register(self, 'default', self.get(key),
1313
self.get_help(key), info=self.get_info(key))
1314
self._aliases.add('default')
1316
def set_default_repository(self, key):
1317
"""Set the FormatRegistry default and Repository default.
1319
This is a transitional method while Repository.set_default_format
1322
if 'default' in self:
1323
self.remove('default')
1324
self.set_default(key)
1325
format = self.get('default')()
1327
def make_bzrdir(self, key):
1328
return self.get(key)()
1330
def help_topic(self, topic):
1332
default_realkey = None
1333
default_help = self.get_help('default')
1335
for key in self._registration_order:
1336
if key == 'default':
1338
help = self.get_help(key)
1339
if help == default_help:
1340
default_realkey = key
1342
help_pairs.append((key, help))
1344
def wrapped(key, help, info):
1346
help = '(native) ' + help
1347
return ':%s:\n%s\n\n' % (key,
1348
textwrap.fill(help, initial_indent=' ',
1349
subsequent_indent=' ',
1350
break_long_words=False))
1351
if default_realkey is not None:
1352
output += wrapped(default_realkey, '(default) %s' % default_help,
1353
self.get_info('default'))
1354
deprecated_pairs = []
1355
experimental_pairs = []
1356
for key, help in help_pairs:
1357
info = self.get_info(key)
1360
elif info.deprecated:
1361
deprecated_pairs.append((key, help))
1362
elif info.experimental:
1363
experimental_pairs.append((key, help))
1365
output += wrapped(key, help, info)
1366
output += "\nSee :doc:`formats-help` for more about storage formats."
1368
if len(experimental_pairs) > 0:
1369
other_output += "Experimental formats are shown below.\n\n"
1370
for key, help in experimental_pairs:
1371
info = self.get_info(key)
1372
other_output += wrapped(key, help, info)
1375
"No experimental formats are available.\n\n"
1376
if len(deprecated_pairs) > 0:
1377
other_output += "\nDeprecated formats are shown below.\n\n"
1378
for key, help in deprecated_pairs:
1379
info = self.get_info(key)
1380
other_output += wrapped(key, help, info)
1383
"\nNo deprecated formats are available.\n\n"
1385
"\nSee :doc:`formats-help` for more about storage formats."
1387
if topic == 'other-formats':
1393
class RepoInitHookParams(object):
1394
"""Object holding parameters passed to `*_repo_init` hooks.
1396
There are 4 fields that hooks may wish to access:
1398
:ivar repository: Repository created
1399
:ivar format: Repository format
1400
:ivar bzrdir: The controldir for the repository
1401
:ivar shared: The repository is shared
1404
def __init__(self, repository, format, controldir, shared):
1405
"""Create a group of RepoInitHook parameters.
1407
:param repository: Repository created
1408
:param format: Repository format
1409
:param controldir: The controldir for the repository
1410
:param shared: The repository is shared
1412
self.repository = repository
1413
self.format = format
1414
self.bzrdir = controldir
1415
self.shared = shared
1417
def __eq__(self, other):
1418
return self.__dict__ == other.__dict__
1422
return "<%s for %s>" % (self.__class__.__name__,
1425
return "<%s for %s>" % (self.__class__.__name__,
1429
# Please register new formats after old formats so that formats
1430
# appear in chronological order and format descriptions can build
1432
format_registry = ControlDirFormatRegistry()
1434
network_format_registry = registry.FormatRegistry()
1435
"""Registry of formats indexed by their network name.
1437
The network name for a ControlDirFormat is an identifier that can be used when
1438
referring to formats with smart server operations. See
1439
ControlDirFormat.network_name() for more detail.