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 { "": 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 set_branch_reference(self, target_branch, name=None):
234
"""Set the referenced URL for the branch in this controldir.
236
:param name: Optional colocated branch name
237
:param target_branch: Branch to reference
238
:raises NoColocatedBranchSupport: If a branch name was specified
239
but colocated branches are not supported.
240
:return: The referencing branch
242
raise NotImplementedError(self.set_branch_reference)
244
def open_branch(self, name=None, unsupported=False,
245
ignore_fallbacks=False, possible_transports=None):
246
"""Open the branch object at this ControlDir if one is present.
248
:param unsupported: if True, then no longer supported branch formats can
250
:param ignore_fallbacks: Whether to open fallback repositories
251
:param possible_transports: Transports to use for opening e.g.
252
fallback repositories.
254
raise NotImplementedError(self.open_branch)
256
def open_repository(self, _unsupported=False):
257
"""Open the repository object at this ControlDir if one is present.
259
This will not follow the Branch object pointer - it's strictly a direct
260
open facility. Most client code should use open_branch().repository to
263
:param _unsupported: a private parameter, not part of the api.
265
raise NotImplementedError(self.open_repository)
267
def find_repository(self):
268
"""Find the repository that should be used.
270
This does not require a branch as we use it to find the repo for
271
new branches as well as to hook existing branches up to their
274
raise NotImplementedError(self.find_repository)
276
def open_workingtree(self, unsupported=False,
277
recommend_upgrade=True, from_branch=None):
278
"""Open the workingtree object at this ControlDir if one is present.
280
:param recommend_upgrade: Optional keyword parameter, when True (the
281
default), emit through the ui module a recommendation that the user
282
upgrade the working tree when the workingtree being opened is old
283
(but still fully supported).
284
:param from_branch: override controldir branch (for lightweight
287
raise NotImplementedError(self.open_workingtree)
289
def has_branch(self, name=None):
290
"""Tell if this controldir contains a branch.
292
Note: if you're going to open the branch, you should just go ahead
293
and try, and not ask permission first. (This method just opens the
294
branch and discards it, and that's somewhat expensive.)
297
self.open_branch(name, ignore_fallbacks=True)
299
except errors.NotBranchError:
302
def _get_selected_branch(self):
303
"""Return the name of the branch selected by the user.
305
:return: Name of the branch selected by the user, or None.
307
branch = self.root_transport.get_segment_parameters().get("branch")
310
return urlutils.unescape(branch)
312
def has_workingtree(self):
313
"""Tell if this controldir contains a working tree.
315
This will still raise an exception if the controldir has a workingtree
316
that is remote & inaccessible.
318
Note: if you're going to open the working tree, you should just go ahead
319
and try, and not ask permission first. (This method just opens the
320
workingtree and discards it, and that's somewhat expensive.)
323
self.open_workingtree(recommend_upgrade=False)
325
except errors.NoWorkingTree:
328
def cloning_metadir(self, require_stacking=False):
329
"""Produce a metadir suitable for cloning or sprouting with.
331
These operations may produce workingtrees (yes, even though they're
332
"cloning" something that doesn't have a tree), so a viable workingtree
333
format must be selected.
335
:require_stacking: If True, non-stackable formats will be upgraded
336
to similar stackable formats.
337
:returns: a ControlDirFormat with all component formats either set
338
appropriately or set to None if that component should not be
341
raise NotImplementedError(self.cloning_metadir)
343
def checkout_metadir(self):
344
"""Produce a metadir suitable for checkouts of this controldir.
346
:returns: A ControlDirFormat with all component formats
347
either set appropriately or set to None if that component
348
should not be created.
350
return self.cloning_metadir()
352
def sprout(self, url, revision_id=None, force_new_repo=False,
353
recurse='down', possible_transports=None,
354
accelerator_tree=None, hardlink=False, stacked=False,
355
source_branch=None, create_tree_if_local=True):
356
"""Create a copy of this controldir prepared for use as a new line of
359
If url's last component does not exist, it will be created.
361
Attributes related to the identity of the source branch like
362
branch nickname will be cleaned, a working tree is created
363
whether one existed before or not; and a local branch is always
366
:param revision_id: if revision_id is not None, then the clone
367
operation may tune itself to download less data.
368
:param accelerator_tree: A tree which can be used for retrieving file
369
contents more quickly than the revision tree, i.e. a workingtree.
370
The revision tree will be used for cases where accelerator_tree's
371
content is different.
372
:param hardlink: If true, hard-link files from accelerator_tree,
374
:param stacked: If true, create a stacked branch referring to the
375
location of this control directory.
376
:param create_tree_if_local: If true, a working-tree will be created
377
when working locally.
379
raise NotImplementedError(self.sprout)
381
def push_branch(self, source, revision_id=None, overwrite=False,
382
remember=False, create_prefix=False):
383
"""Push the source branch into this ControlDir."""
385
# If we can open a branch, use its direct repository, otherwise see
386
# if there is a repository without a branch.
388
br_to = self.open_branch()
389
except errors.NotBranchError:
390
# Didn't find a branch, can we find a repository?
391
repository_to = self.find_repository()
393
# Found a branch, so we must have found a repository
394
repository_to = br_to.repository
396
push_result = PushResult()
397
push_result.source_branch = source
399
# We have a repository but no branch, copy the revisions, and then
401
if revision_id is None:
402
# No revision supplied by the user, default to the branch
404
revision_id = source.last_revision()
405
repository_to.fetch(source.repository, revision_id=revision_id)
406
br_to = source.clone(self, revision_id=revision_id)
407
if source.get_push_location() is None or remember:
408
source.set_push_location(br_to.base)
409
push_result.stacked_on = None
410
push_result.branch_push_result = None
411
push_result.old_revno = None
412
push_result.old_revid = _mod_revision.NULL_REVISION
413
push_result.target_branch = br_to
414
push_result.master_branch = None
415
push_result.workingtree_updated = False
417
# We have successfully opened the branch, remember if necessary:
418
if source.get_push_location() is None or remember:
419
source.set_push_location(br_to.base)
421
tree_to = self.open_workingtree()
422
except errors.NotLocalUrl:
423
push_result.branch_push_result = source.push(br_to,
424
overwrite, stop_revision=revision_id)
425
push_result.workingtree_updated = False
426
except errors.NoWorkingTree:
427
push_result.branch_push_result = source.push(br_to,
428
overwrite, stop_revision=revision_id)
429
push_result.workingtree_updated = None # Not applicable
433
push_result.branch_push_result = source.push(
434
tree_to.branch, overwrite, stop_revision=revision_id)
438
push_result.workingtree_updated = True
439
push_result.old_revno = push_result.branch_push_result.old_revno
440
push_result.old_revid = push_result.branch_push_result.old_revid
441
push_result.target_branch = \
442
push_result.branch_push_result.target_branch
445
def _get_tree_branch(self, name=None):
446
"""Return the branch and tree, if any, for this controldir.
448
:param name: Name of colocated branch to open.
450
Return None for tree if not present or inaccessible.
451
Raise NotBranchError if no branch is present.
452
:return: (tree, branch)
455
tree = self.open_workingtree()
456
except (errors.NoWorkingTree, errors.NotLocalUrl):
458
branch = self.open_branch(name=name)
461
branch = self.open_branch(name=name)
466
def get_config(self):
467
"""Get configuration for this ControlDir."""
468
raise NotImplementedError(self.get_config)
470
def check_conversion_target(self, target_format):
471
"""Check that a controldir as a whole can be converted to a new format."""
472
raise NotImplementedError(self.check_conversion_target)
474
def clone(self, url, revision_id=None, force_new_repo=False,
475
preserve_stacking=False):
476
"""Clone this controldir and its contents to url verbatim.
478
:param url: The url create the clone at. If url's last component does
479
not exist, it will be created.
480
:param revision_id: The tip revision-id to use for any branch or
481
working tree. If not None, then the clone operation may tune
482
itself to download less data.
483
:param force_new_repo: Do not use a shared repository for the target
484
even if one is available.
485
:param preserve_stacking: When cloning a stacked branch, stack the
486
new branch on top of the other branch's stacked-on branch.
488
return self.clone_on_transport(_mod_transport.get_transport(url),
489
revision_id=revision_id,
490
force_new_repo=force_new_repo,
491
preserve_stacking=preserve_stacking)
493
def clone_on_transport(self, transport, revision_id=None,
494
force_new_repo=False, preserve_stacking=False, stacked_on=None,
495
create_prefix=False, use_existing_dir=True, no_tree=False):
496
"""Clone this controldir and its contents to transport verbatim.
498
:param transport: The transport for the location to produce the clone
499
at. If the target directory does not exist, it will be created.
500
:param revision_id: The tip revision-id to use for any branch or
501
working tree. If not None, then the clone operation may tune
502
itself to download less data.
503
:param force_new_repo: Do not use a shared repository for the target,
504
even if one is available.
505
:param preserve_stacking: When cloning a stacked branch, stack the
506
new branch on top of the other branch's stacked-on branch.
507
:param create_prefix: Create any missing directories leading up to
509
:param use_existing_dir: Use an existing directory if one exists.
510
:param no_tree: If set to true prevents creation of a working tree.
512
raise NotImplementedError(self.clone_on_transport)
515
def find_bzrdirs(klass, transport, evaluate=None, list_current=None):
516
"""Find control dirs recursively from current location.
518
This is intended primarily as a building block for more sophisticated
519
functionality, like finding trees under a directory, or finding
520
branches that use a given repository.
522
:param evaluate: An optional callable that yields recurse, value,
523
where recurse controls whether this controldir is recursed into
524
and value is the value to yield. By default, all bzrdirs
525
are recursed into, and the return value is the controldir.
526
:param list_current: if supplied, use this function to list the current
527
directory, instead of Transport.list_dir
528
:return: a generator of found bzrdirs, or whatever evaluate returns.
530
if list_current is None:
531
def list_current(transport):
532
return transport.list_dir('')
534
def evaluate(controldir):
535
return True, controldir
537
pending = [transport]
538
while len(pending) > 0:
539
current_transport = pending.pop()
542
controldir = klass.open_from_transport(current_transport)
543
except (errors.NotBranchError, errors.PermissionDenied):
546
recurse, value = evaluate(controldir)
549
subdirs = list_current(current_transport)
550
except (errors.NoSuchFile, errors.PermissionDenied):
553
for subdir in sorted(subdirs, reverse=True):
554
pending.append(current_transport.clone(subdir))
557
def find_branches(klass, transport):
558
"""Find all branches under a transport.
560
This will find all branches below the transport, including branches
561
inside other branches. Where possible, it will use
562
Repository.find_branches.
564
To list all the branches that use a particular Repository, see
565
Repository.find_branches
567
def evaluate(controldir):
569
repository = controldir.open_repository()
570
except errors.NoRepositoryPresent:
573
return False, ([], repository)
574
return True, (controldir.list_branches(), None)
576
for branches, repo in klass.find_bzrdirs(
577
transport, evaluate=evaluate):
579
ret.extend(repo.find_branches())
580
if branches is not None:
585
def create_branch_and_repo(klass, base, force_new_repo=False, format=None):
586
"""Create a new ControlDir, Branch and Repository at the url 'base'.
588
This will use the current default ControlDirFormat unless one is
589
specified, and use whatever
590
repository format that that uses via controldir.create_branch and
591
create_repository. If a shared repository is available that is used
594
The created Branch object is returned.
596
:param base: The URL to create the branch at.
597
:param force_new_repo: If True a new repository is always created.
598
:param format: If supplied, the format of branch to create. If not
599
supplied, the default is used.
601
controldir = klass.create(base, format)
602
controldir._find_or_create_repository(force_new_repo)
603
return controldir.create_branch()
606
def create_branch_convenience(klass, base, force_new_repo=False,
607
force_new_tree=None, format=None,
608
possible_transports=None):
609
"""Create a new ControlDir, Branch and Repository at the url 'base'.
611
This is a convenience function - it will use an existing repository
612
if possible, can be told explicitly whether to create a working tree or
615
This will use the current default ControlDirFormat unless one is
616
specified, and use whatever
617
repository format that that uses via ControlDir.create_branch and
618
create_repository. If a shared repository is available that is used
619
preferentially. Whatever repository is used, its tree creation policy
622
The created Branch object is returned.
623
If a working tree cannot be made due to base not being a file:// url,
624
no error is raised unless force_new_tree is True, in which case no
625
data is created on disk and NotLocalUrl is raised.
627
:param base: The URL to create the branch at.
628
:param force_new_repo: If True a new repository is always created.
629
:param force_new_tree: If True or False force creation of a tree or
630
prevent such creation respectively.
631
:param format: Override for the controldir format to create.
632
:param possible_transports: An optional reusable transports list.
635
# check for non local urls
636
t = _mod_transport.get_transport(base, possible_transports)
637
if not isinstance(t, local.LocalTransport):
638
raise errors.NotLocalUrl(base)
639
controldir = klass.create(base, format, possible_transports)
640
repo = controldir._find_or_create_repository(force_new_repo)
641
result = controldir.create_branch()
642
if force_new_tree or (repo.make_working_trees() and
643
force_new_tree is None):
645
controldir.create_workingtree()
646
except errors.NotLocalUrl:
651
def create_standalone_workingtree(klass, base, format=None):
652
"""Create a new ControlDir, WorkingTree, Branch and Repository at 'base'.
654
'base' must be a local path or a file:// url.
656
This will use the current default ControlDirFormat unless one is
657
specified, and use whatever
658
repository format that that uses for bzrdirformat.create_workingtree,
659
create_branch and create_repository.
661
:param format: Override for the controldir format to create.
662
:return: The WorkingTree object.
664
t = _mod_transport.get_transport(base)
665
if not isinstance(t, local.LocalTransport):
666
raise errors.NotLocalUrl(base)
667
controldir = klass.create_branch_and_repo(base,
669
format=format).bzrdir
670
return controldir.create_workingtree()
673
def open_unsupported(klass, base):
674
"""Open a branch which is not supported."""
675
return klass.open(base, _unsupported=True)
678
def open(klass, base, possible_transports=None, probers=None,
680
"""Open an existing controldir, rooted at 'base' (url).
682
:param _unsupported: a private parameter to the ControlDir class.
684
t = _mod_transport.get_transport(base, possible_transports)
685
return klass.open_from_transport(t, probers=probers,
686
_unsupported=_unsupported)
689
def open_from_transport(klass, transport, _unsupported=False,
691
"""Open a controldir within a particular directory.
693
:param transport: Transport containing the controldir.
694
:param _unsupported: private.
696
for hook in klass.hooks['pre_open']:
698
# Keep initial base since 'transport' may be modified while following
700
base = transport.base
701
def find_format(transport):
702
return transport, ControlDirFormat.find_format(transport,
705
def redirected(transport, e, redirection_notice):
706
redirected_transport = transport._redirected_to(e.source, e.target)
707
if redirected_transport is None:
708
raise errors.NotBranchError(base)
709
trace.note(gettext('{0} is{1} redirected to {2}').format(
710
transport.base, e.permanently, redirected_transport.base))
711
return redirected_transport
714
transport, format = _mod_transport.do_catching_redirections(
715
find_format, transport, redirected)
716
except errors.TooManyRedirections:
717
raise errors.NotBranchError(base)
719
format.check_support_status(_unsupported)
720
return format.open(transport, _found=True)
723
def open_containing(klass, url, possible_transports=None):
724
"""Open an existing branch which contains url.
726
:param url: url to search from.
728
See open_containing_from_transport for more detail.
730
transport = _mod_transport.get_transport(url, possible_transports)
731
return klass.open_containing_from_transport(transport)
734
def open_containing_from_transport(klass, a_transport):
735
"""Open an existing branch which contains a_transport.base.
737
This probes for a branch at a_transport, and searches upwards from there.
739
Basically we keep looking up until we find the control directory or
740
run into the root. If there isn't one, raises NotBranchError.
741
If there is one and it is either an unrecognised format or an unsupported
742
format, UnknownFormatError or UnsupportedFormatError are raised.
743
If there is one, it is returned, along with the unused portion of url.
745
:return: The ControlDir that contains the path, and a Unicode path
746
for the rest of the URL.
748
# this gets the normalised url back. I.e. '.' -> the full path.
749
url = a_transport.base
752
result = klass.open_from_transport(a_transport)
753
return result, urlutils.unescape(a_transport.relpath(url))
754
except errors.NotBranchError, e:
756
except errors.PermissionDenied:
759
new_t = a_transport.clone('..')
760
except errors.InvalidURLJoin:
761
# reached the root, whatever that may be
762
raise errors.NotBranchError(path=url)
763
if new_t.base == a_transport.base:
764
# reached the root, whatever that may be
765
raise errors.NotBranchError(path=url)
769
def open_tree_or_branch(klass, location):
770
"""Return the branch and working tree at a location.
772
If there is no tree at the location, tree will be None.
773
If there is no branch at the location, an exception will be
775
:return: (tree, branch)
777
controldir = klass.open(location)
778
return controldir._get_tree_branch()
781
def open_containing_tree_or_branch(klass, location,
782
possible_transports=None):
783
"""Return the branch and working tree contained by a location.
785
Returns (tree, branch, relpath).
786
If there is no tree at containing the location, tree will be None.
787
If there is no branch containing the location, an exception will be
789
relpath is the portion of the path that is contained by the branch.
791
controldir, relpath = klass.open_containing(location,
792
possible_transports=possible_transports)
793
tree, branch = controldir._get_tree_branch()
794
return tree, branch, relpath
797
def open_containing_tree_branch_or_repository(klass, location):
798
"""Return the working tree, branch and repo contained by a location.
800
Returns (tree, branch, repository, relpath).
801
If there is no tree containing the location, tree will be None.
802
If there is no branch containing the location, branch will be None.
803
If there is no repository containing the location, repository will be
805
relpath is the portion of the path that is contained by the innermost
808
If no tree, branch or repository is found, a NotBranchError is raised.
810
controldir, relpath = klass.open_containing(location)
812
tree, branch = controldir._get_tree_branch()
813
except errors.NotBranchError:
815
repo = controldir.find_repository()
816
return None, None, repo, relpath
817
except (errors.NoRepositoryPresent):
818
raise errors.NotBranchError(location)
819
return tree, branch, branch.repository, relpath
822
def create(klass, base, format=None, possible_transports=None):
823
"""Create a new ControlDir at the url 'base'.
825
:param format: If supplied, the format of branch to create. If not
826
supplied, the default is used.
827
:param possible_transports: If supplied, a list of transports that
828
can be reused to share a remote connection.
830
if klass is not ControlDir:
831
raise AssertionError("ControlDir.create always creates the"
832
"default format, not one of %r" % klass)
833
t = _mod_transport.get_transport(base, possible_transports)
836
format = ControlDirFormat.get_default_format()
837
return format.initialize_on_transport(t)
840
class ControlDirHooks(hooks.Hooks):
841
"""Hooks for ControlDir operations."""
844
"""Create the default hooks."""
845
hooks.Hooks.__init__(self, "bzrlib.controldir", "ControlDir.hooks")
846
self.add_hook('pre_open',
847
"Invoked before attempting to open a ControlDir with the transport "
848
"that the open will use.", (1, 14))
849
self.add_hook('post_repo_init',
850
"Invoked after a repository has been initialized. "
851
"post_repo_init is called with a "
852
"bzrlib.controldir.RepoInitHookParams.",
855
# install the default hooks
856
ControlDir.hooks = ControlDirHooks()
859
class ControlComponentFormat(object):
860
"""A component that can live inside of a control directory."""
862
upgrade_recommended = False
864
def get_format_description(self):
865
"""Return the short description for this format."""
866
raise NotImplementedError(self.get_format_description)
868
def is_supported(self):
869
"""Is this format supported?
871
Supported formats must be initializable and openable.
872
Unsupported formats may not support initialization or committing or
873
some other features depending on the reason for not being supported.
877
def check_support_status(self, allow_unsupported, recommend_upgrade=True,
879
"""Give an error or warning on old formats.
881
:param allow_unsupported: If true, allow opening
882
formats that are strongly deprecated, and which may
883
have limited functionality.
885
:param recommend_upgrade: If true (default), warn
886
the user through the ui object that they may wish
887
to upgrade the object.
889
if not allow_unsupported and not self.is_supported():
890
# see open_downlevel to open legacy branches.
891
raise errors.UnsupportedFormatError(format=self)
892
if recommend_upgrade and self.upgrade_recommended:
893
ui.ui_factory.recommend_upgrade(
894
self.get_format_description(), basedir)
897
def get_format_string(cls):
898
raise NotImplementedError(cls.get_format_string)
901
class ControlComponentFormatRegistry(registry.FormatRegistry):
902
"""A registry for control components (branch, workingtree, repository)."""
904
def __init__(self, other_registry=None):
905
super(ControlComponentFormatRegistry, self).__init__(other_registry)
906
self._extra_formats = []
908
def register(self, format):
909
"""Register a new format."""
910
super(ControlComponentFormatRegistry, self).register(
911
format.get_format_string(), format)
913
def remove(self, format):
914
"""Remove a registered format."""
915
super(ControlComponentFormatRegistry, self).remove(
916
format.get_format_string())
918
def register_extra(self, format):
919
"""Register a format that can not be used in a metadir.
921
This is mainly useful to allow custom repository formats, such as older
922
Bazaar formats and foreign formats, to be tested.
924
self._extra_formats.append(registry._ObjectGetter(format))
926
def remove_extra(self, format):
927
"""Remove an extra format.
929
self._extra_formats.remove(registry._ObjectGetter(format))
931
def register_extra_lazy(self, module_name, member_name):
932
"""Register a format lazily.
934
self._extra_formats.append(
935
registry._LazyObjectGetter(module_name, member_name))
937
def _get_extra(self):
938
"""Return all "extra" formats, not usable in meta directories."""
940
for getter in self._extra_formats:
948
"""Return all formats, even those not usable in metadirs.
951
for name in self.keys():
956
return result + self._get_extra()
958
def _get_all_modules(self):
959
"""Return a set of the modules providing objects."""
961
for name in self.keys():
962
modules.add(self._get_module(name))
963
for getter in self._extra_formats:
964
modules.add(getter.get_module())
968
class Converter(object):
969
"""Converts a disk format object from one format to another."""
971
def convert(self, to_convert, pb):
972
"""Perform the conversion of to_convert, giving feedback via pb.
974
:param to_convert: The disk object to convert.
975
:param pb: a progress bar to use for progress information.
978
def step(self, message):
979
"""Update the pb by a step."""
981
self.pb.update(message, self.count, self.total)
984
class ControlDirFormat(object):
985
"""An encapsulation of the initialization and open routines for a format.
987
Formats provide three things:
988
* An initialization routine,
992
Formats are placed in a dict by their format string for reference
993
during controldir opening. These should be subclasses of ControlDirFormat
996
Once a format is deprecated, just deprecate the initialize and open
997
methods on the format class. Do not deprecate the object, as the
998
object will be created every system load.
1000
:cvar colocated_branches: Whether this formats supports colocated branches.
1001
:cvar supports_workingtrees: This control directory can co-exist with a
1005
_default_format = None
1006
"""The default format used for new control directories."""
1008
_server_probers = []
1009
"""The registered server format probers, e.g. RemoteBzrProber.
1011
This is a list of Prober-derived classes.
1015
"""The registered format probers, e.g. BzrProber.
1017
This is a list of Prober-derived classes.
1020
colocated_branches = False
1021
"""Whether co-located branches are supported for this control dir format.
1024
supports_workingtrees = True
1025
"""Whether working trees can exist in control directories of this format.
1028
fixed_components = False
1029
"""Whether components can not change format independent of the control dir.
1032
upgrade_recommended = False
1033
"""Whether an upgrade from this format is recommended."""
1035
def get_format_description(self):
1036
"""Return the short description for this format."""
1037
raise NotImplementedError(self.get_format_description)
1039
def get_converter(self, format=None):
1040
"""Return the converter to use to convert controldirs needing converts.
1042
This returns a bzrlib.controldir.Converter object.
1044
This should return the best upgrader to step this format towards the
1045
current default format. In the case of plugins we can/should provide
1046
some means for them to extend the range of returnable converters.
1048
:param format: Optional format to override the default format of the
1051
raise NotImplementedError(self.get_converter)
1053
def is_supported(self):
1054
"""Is this format supported?
1056
Supported formats must be openable.
1057
Unsupported formats may not support initialization or committing or
1058
some other features depending on the reason for not being supported.
1062
def is_initializable(self):
1063
"""Whether new control directories of this format can be initialized.
1065
return self.is_supported()
1067
def check_support_status(self, allow_unsupported, recommend_upgrade=True,
1069
"""Give an error or warning on old formats.
1071
:param allow_unsupported: If true, allow opening
1072
formats that are strongly deprecated, and which may
1073
have limited functionality.
1075
:param recommend_upgrade: If true (default), warn
1076
the user through the ui object that they may wish
1077
to upgrade the object.
1079
if not allow_unsupported and not self.is_supported():
1080
# see open_downlevel to open legacy branches.
1081
raise errors.UnsupportedFormatError(format=self)
1082
if recommend_upgrade and self.upgrade_recommended:
1083
ui.ui_factory.recommend_upgrade(
1084
self.get_format_description(), basedir)
1086
def same_model(self, target_format):
1087
return (self.repository_format.rich_root_data ==
1088
target_format.rich_root_data)
1091
def register_format(klass, format):
1092
"""Register a format that does not use '.bzr' for its control dir.
1095
raise errors.BzrError("ControlDirFormat.register_format() has been "
1096
"removed in Bazaar 2.4. Please upgrade your plugins.")
1099
def register_prober(klass, prober):
1100
"""Register a prober that can look for a control dir.
1103
klass._probers.append(prober)
1106
def unregister_prober(klass, prober):
1107
"""Unregister a prober.
1110
klass._probers.remove(prober)
1113
def register_server_prober(klass, prober):
1114
"""Register a control format prober for client-server environments.
1116
These probers will be used before ones registered with
1117
register_prober. This gives implementations that decide to the
1118
chance to grab it before anything looks at the contents of the format
1121
klass._server_probers.append(prober)
1125
return self.get_format_description().rstrip()
1128
def all_probers(klass):
1129
return klass._server_probers + klass._probers
1132
def known_formats(klass):
1133
"""Return all the known formats.
1136
for prober_kls in klass.all_probers():
1137
result.update(prober_kls.known_formats())
1141
def find_format(klass, transport, probers=None):
1142
"""Return the format present at transport."""
1144
probers = klass.all_probers()
1145
for prober_kls in probers:
1146
prober = prober_kls()
1148
return prober.probe_transport(transport)
1149
except errors.NotBranchError:
1150
# this format does not find a control dir here.
1152
raise errors.NotBranchError(path=transport.base)
1154
def initialize(self, url, possible_transports=None):
1155
"""Create a control dir at this url and return an opened copy.
1157
While not deprecated, this method is very specific and its use will
1158
lead to many round trips to setup a working environment. See
1159
initialize_on_transport_ex for a [nearly] all-in-one method.
1161
Subclasses should typically override initialize_on_transport
1162
instead of this method.
1164
return self.initialize_on_transport(
1165
_mod_transport.get_transport(url, possible_transports))
1167
def initialize_on_transport(self, transport):
1168
"""Initialize a new controldir in the base directory of a Transport."""
1169
raise NotImplementedError(self.initialize_on_transport)
1171
def initialize_on_transport_ex(self, transport, use_existing_dir=False,
1172
create_prefix=False, force_new_repo=False, stacked_on=None,
1173
stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
1174
shared_repo=False, vfs_only=False):
1175
"""Create this format on transport.
1177
The directory to initialize will be created.
1179
:param force_new_repo: Do not use a shared repository for the target,
1180
even if one is available.
1181
:param create_prefix: Create any missing directories leading up to
1183
:param use_existing_dir: Use an existing directory if one exists.
1184
:param stacked_on: A url to stack any created branch on, None to follow
1185
any target stacking policy.
1186
:param stack_on_pwd: If stack_on is relative, the location it is
1188
:param repo_format_name: If non-None, a repository will be
1189
made-or-found. Should none be found, or if force_new_repo is True
1190
the repo_format_name is used to select the format of repository to
1192
:param make_working_trees: Control the setting of make_working_trees
1193
for a new shared repository when one is made. None to use whatever
1194
default the format has.
1195
:param shared_repo: Control whether made repositories are shared or
1197
:param vfs_only: If True do not attempt to use a smart server
1198
:return: repo, controldir, require_stacking, repository_policy. repo is
1199
None if none was created or found, controldir is always valid.
1200
require_stacking is the result of examining the stacked_on
1201
parameter and any stacking policy found for the target.
1203
raise NotImplementedError(self.initialize_on_transport_ex)
1205
def network_name(self):
1206
"""A simple byte string uniquely identifying this format for RPC calls.
1208
Bzr control formats use this disk format string to identify the format
1209
over the wire. Its possible that other control formats have more
1210
complex detection requirements, so we permit them to use any unique and
1211
immutable string they desire.
1213
raise NotImplementedError(self.network_name)
1215
def open(self, transport, _found=False):
1216
"""Return an instance of this format for the dir transport points at.
1218
raise NotImplementedError(self.open)
1221
def _set_default_format(klass, format):
1222
"""Set default format (for testing behavior of defaults only)"""
1223
klass._default_format = format
1226
def get_default_format(klass):
1227
"""Return the current default format."""
1228
return klass._default_format
1230
def supports_transport(self, transport):
1231
"""Check if this format can be opened over a particular transport.
1233
raise NotImplementedError(self.supports_transport)
1236
class Prober(object):
1237
"""Abstract class that can be used to detect a particular kind of
1240
At the moment this just contains a single method to probe a particular
1241
transport, but it may be extended in the future to e.g. avoid
1242
multiple levels of probing for Subversion repositories.
1244
See BzrProber and RemoteBzrProber in bzrlib.bzrdir for the
1245
probers that detect .bzr/ directories and Bazaar smart servers,
1248
Probers should be registered using the register_server_prober or
1249
register_prober methods on ControlDirFormat.
1252
def probe_transport(self, transport):
1253
"""Return the controldir style format present in a directory.
1255
:raise UnknownFormatError: If a control dir was found but is
1256
in an unknown format.
1257
:raise NotBranchError: If no control directory was found.
1258
:return: A ControlDirFormat instance.
1260
raise NotImplementedError(self.probe_transport)
1263
def known_formats(klass):
1264
"""Return the control dir formats known by this prober.
1266
Multiple probers can return the same formats, so this should
1269
:return: A set of known formats.
1271
raise NotImplementedError(klass.known_formats)
1274
class ControlDirFormatInfo(object):
1276
def __init__(self, native, deprecated, hidden, experimental):
1277
self.deprecated = deprecated
1278
self.native = native
1279
self.hidden = hidden
1280
self.experimental = experimental
1283
class ControlDirFormatRegistry(registry.Registry):
1284
"""Registry of user-selectable ControlDir subformats.
1286
Differs from ControlDirFormat._formats in that it provides sub-formats,
1287
e.g. BzrDirMeta1 with weave repository. Also, it's more user-oriented.
1291
"""Create a ControlDirFormatRegistry."""
1292
self._aliases = set()
1293
self._registration_order = list()
1294
super(ControlDirFormatRegistry, self).__init__()
1297
"""Return a set of the format names which are aliases."""
1298
return frozenset(self._aliases)
1300
def register(self, key, factory, help, native=True, deprecated=False,
1301
hidden=False, experimental=False, alias=False):
1302
"""Register a ControlDirFormat factory.
1304
The factory must be a callable that takes one parameter: the key.
1305
It must produce an instance of the ControlDirFormat when called.
1307
This function mainly exists to prevent the info object from being
1310
registry.Registry.register(self, key, factory, help,
1311
ControlDirFormatInfo(native, deprecated, hidden, experimental))
1313
self._aliases.add(key)
1314
self._registration_order.append(key)
1316
def register_lazy(self, key, module_name, member_name, help, native=True,
1317
deprecated=False, hidden=False, experimental=False, alias=False):
1318
registry.Registry.register_lazy(self, key, module_name, member_name,
1319
help, ControlDirFormatInfo(native, deprecated, hidden, experimental))
1321
self._aliases.add(key)
1322
self._registration_order.append(key)
1324
def set_default(self, key):
1325
"""Set the 'default' key to be a clone of the supplied key.
1327
This method must be called once and only once.
1329
registry.Registry.register(self, 'default', self.get(key),
1330
self.get_help(key), info=self.get_info(key))
1331
self._aliases.add('default')
1333
def set_default_repository(self, key):
1334
"""Set the FormatRegistry default and Repository default.
1336
This is a transitional method while Repository.set_default_format
1339
if 'default' in self:
1340
self.remove('default')
1341
self.set_default(key)
1342
format = self.get('default')()
1344
def make_bzrdir(self, key):
1345
return self.get(key)()
1347
def help_topic(self, topic):
1349
default_realkey = None
1350
default_help = self.get_help('default')
1352
for key in self._registration_order:
1353
if key == 'default':
1355
help = self.get_help(key)
1356
if help == default_help:
1357
default_realkey = key
1359
help_pairs.append((key, help))
1361
def wrapped(key, help, info):
1363
help = '(native) ' + help
1364
return ':%s:\n%s\n\n' % (key,
1365
textwrap.fill(help, initial_indent=' ',
1366
subsequent_indent=' ',
1367
break_long_words=False))
1368
if default_realkey is not None:
1369
output += wrapped(default_realkey, '(default) %s' % default_help,
1370
self.get_info('default'))
1371
deprecated_pairs = []
1372
experimental_pairs = []
1373
for key, help in help_pairs:
1374
info = self.get_info(key)
1377
elif info.deprecated:
1378
deprecated_pairs.append((key, help))
1379
elif info.experimental:
1380
experimental_pairs.append((key, help))
1382
output += wrapped(key, help, info)
1383
output += "\nSee :doc:`formats-help` for more about storage formats."
1385
if len(experimental_pairs) > 0:
1386
other_output += "Experimental formats are shown below.\n\n"
1387
for key, help in experimental_pairs:
1388
info = self.get_info(key)
1389
other_output += wrapped(key, help, info)
1392
"No experimental formats are available.\n\n"
1393
if len(deprecated_pairs) > 0:
1394
other_output += "\nDeprecated formats are shown below.\n\n"
1395
for key, help in deprecated_pairs:
1396
info = self.get_info(key)
1397
other_output += wrapped(key, help, info)
1400
"\nNo deprecated formats are available.\n\n"
1402
"\nSee :doc:`formats-help` for more about storage formats."
1404
if topic == 'other-formats':
1410
class RepoInitHookParams(object):
1411
"""Object holding parameters passed to `*_repo_init` hooks.
1413
There are 4 fields that hooks may wish to access:
1415
:ivar repository: Repository created
1416
:ivar format: Repository format
1417
:ivar bzrdir: The controldir for the repository
1418
:ivar shared: The repository is shared
1421
def __init__(self, repository, format, controldir, shared):
1422
"""Create a group of RepoInitHook parameters.
1424
:param repository: Repository created
1425
:param format: Repository format
1426
:param controldir: The controldir for the repository
1427
:param shared: The repository is shared
1429
self.repository = repository
1430
self.format = format
1431
self.bzrdir = controldir
1432
self.shared = shared
1434
def __eq__(self, other):
1435
return self.__dict__ == other.__dict__
1439
return "<%s for %s>" % (self.__class__.__name__,
1442
return "<%s for %s>" % (self.__class__.__name__,
1446
# Please register new formats after old formats so that formats
1447
# appear in chronological order and format descriptions can build
1449
format_registry = ControlDirFormatRegistry()
1451
network_format_registry = registry.FormatRegistry()
1452
"""Registry of formats indexed by their network name.
1454
The network name for a ControlDirFormat is an identifier that can be used when
1455
referring to formats with smart server operations. See
1456
ControlDirFormat.network_name() for more detail.