1
# Copyright (C) 2010, 2011 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""ControlDir is the basic control directory class.
19
The ControlDir class is the base for the control directory used
20
by all bzr and foreign formats. For the ".bzr" implementation,
21
see bzrlib.bzrdir.BzrDir.
25
from bzrlib.lazy_import import lazy_import
26
lazy_import(globals(), """
32
revision as _mod_revision,
33
transport as _mod_transport,
38
from bzrlib.transport import local
39
from bzrlib.push import (
43
from bzrlib.i18n import gettext
46
from bzrlib import registry
49
class ControlComponent(object):
50
"""Abstract base class for control directory components.
52
This provides interfaces that are common across controldirs,
53
repositories, branches, and workingtree control directories.
55
They all expose two urls and transports: the *user* URL is the
56
one that stops above the control directory (eg .bzr) and that
57
should normally be used in messages, and the *control* URL is
58
under that in eg .bzr/checkout and is used to read the control
61
This can be used as a mixin and is intended to fit with
66
def control_transport(self):
67
raise NotImplementedError
70
def control_url(self):
71
return self.control_transport.base
74
def user_transport(self):
75
raise NotImplementedError
79
return self.user_transport.base
82
class ControlDir(ControlComponent):
83
"""A control directory.
85
While this represents a generic control directory, there are a few
86
features that are present in this interface that are currently only
87
supported by one of its implementations, BzrDir.
89
These features (bound branches, stacked branches) are currently only
90
supported by Bazaar, but could be supported by other version control
91
systems as well. Implementations are required to raise the appropriate
92
exceptions when an operation is requested that is not supported.
94
This also makes life easier for API users who can rely on the
95
implementation always allowing a particular feature to be requested but
96
raising an exception when it is not supported, rather than requiring the
97
API users to check for magic attributes to see what features are supported.
100
def can_convert_format(self):
101
"""Return true if this controldir is one whose format we can convert
105
def list_branches(self):
106
"""Return a sequence of all branches local to this control directory.
109
return self.get_branches().values()
111
def get_branches(self):
112
"""Get all branches in this control directory, as a dictionary.
114
:return: Dictionary mapping branch names to instances.
117
return { None: self.open_branch() }
118
except (errors.NotBranchError, errors.NoRepositoryPresent):
121
def is_control_filename(self, filename):
122
"""True if filename is the name of a path which is reserved for
125
:param filename: A filename within the root transport of this
128
This is true IF and ONLY IF the filename is part of the namespace reserved
129
for bzr control dirs. Currently this is the '.bzr' directory in the root
130
of the root_transport. it is expected that plugins will need to extend
131
this in the future - for instance to make bzr talk with svn working
134
raise NotImplementedError(self.is_control_filename)
136
def needs_format_conversion(self, format=None):
137
"""Return true if this controldir needs convert_format run on it.
139
For instance, if the repository format is out of date but the
140
branch and working tree are not, this should return True.
142
:param format: Optional parameter indicating a specific desired
143
format we plan to arrive at.
145
raise NotImplementedError(self.needs_format_conversion)
147
def create_repository(self, shared=False):
148
"""Create a new repository in this control directory.
150
:param shared: If a shared repository should be created
151
:return: The newly created repository
153
raise NotImplementedError(self.create_repository)
155
def destroy_repository(self):
156
"""Destroy the repository in this ControlDir."""
157
raise NotImplementedError(self.destroy_repository)
159
def create_branch(self, name=None, repository=None,
160
append_revisions_only=None):
161
"""Create a branch in this ControlDir.
163
:param name: Name of the colocated branch to create, None for
165
:param append_revisions_only: Whether this branch should only allow
166
appending new revisions to its history.
168
The controldirs format will control what branch format is created.
169
For more control see BranchFormatXX.create(a_controldir).
171
raise NotImplementedError(self.create_branch)
173
def destroy_branch(self, name=None):
174
"""Destroy a branch in this ControlDir.
176
:param name: Name of the branch to destroy, None for the default
179
raise NotImplementedError(self.destroy_branch)
181
def create_workingtree(self, revision_id=None, from_branch=None,
182
accelerator_tree=None, hardlink=False):
183
"""Create a working tree at this ControlDir.
185
:param revision_id: create it as of this revision id.
186
:param from_branch: override controldir branch
187
(for lightweight checkouts)
188
:param accelerator_tree: A tree which can be used for retrieving file
189
contents more quickly than the revision tree, i.e. a workingtree.
190
The revision tree will be used for cases where accelerator_tree's
191
content is different.
193
raise NotImplementedError(self.create_workingtree)
195
def destroy_workingtree(self):
196
"""Destroy the working tree at this ControlDir.
198
Formats that do not support this may raise UnsupportedOperation.
200
raise NotImplementedError(self.destroy_workingtree)
202
def destroy_workingtree_metadata(self):
203
"""Destroy the control files for the working tree at this ControlDir.
205
The contents of working tree files are not affected.
206
Formats that do not support this may raise UnsupportedOperation.
208
raise NotImplementedError(self.destroy_workingtree_metadata)
210
def find_branch_format(self, name=None):
211
"""Find the branch 'format' for this controldir.
213
This might be a synthetic object for e.g. RemoteBranch and SVN.
215
raise NotImplementedError(self.find_branch_format)
217
def get_branch_reference(self, name=None):
218
"""Return the referenced URL for the branch in this controldir.
220
:param name: Optional colocated branch name
221
:raises NotBranchError: If there is no Branch.
222
:raises NoColocatedBranchSupport: If a branch name was specified
223
but colocated branches are not supported.
224
:return: The URL the branch in this controldir references if it is a
225
reference branch, or None for regular branches.
228
raise errors.NoColocatedBranchSupport(self)
231
def open_branch(self, name=None, unsupported=False,
232
ignore_fallbacks=False, possible_transports=None):
233
"""Open the branch object at this ControlDir if one is present.
235
:param unsupported: if True, then no longer supported branch formats can
237
:param ignore_fallbacks: Whether to open fallback repositories
238
:param possible_transports: Transports to use for opening e.g.
239
fallback repositories.
241
raise NotImplementedError(self.open_branch)
243
def open_repository(self, _unsupported=False):
244
"""Open the repository object at this ControlDir if one is present.
246
This will not follow the Branch object pointer - it's strictly a direct
247
open facility. Most client code should use open_branch().repository to
250
:param _unsupported: a private parameter, not part of the api.
252
raise NotImplementedError(self.open_repository)
254
def find_repository(self):
255
"""Find the repository that should be used.
257
This does not require a branch as we use it to find the repo for
258
new branches as well as to hook existing branches up to their
261
raise NotImplementedError(self.find_repository)
263
def open_workingtree(self, _unsupported=False,
264
recommend_upgrade=True, from_branch=None):
265
"""Open the workingtree object at this ControlDir if one is present.
267
:param recommend_upgrade: Optional keyword parameter, when True (the
268
default), emit through the ui module a recommendation that the user
269
upgrade the working tree when the workingtree being opened is old
270
(but still fully supported).
271
:param from_branch: override controldir branch (for lightweight
274
raise NotImplementedError(self.open_workingtree)
276
def has_branch(self, name=None):
277
"""Tell if this controldir contains a branch.
279
Note: if you're going to open the branch, you should just go ahead
280
and try, and not ask permission first. (This method just opens the
281
branch and discards it, and that's somewhat expensive.)
284
self.open_branch(name, ignore_fallbacks=True)
286
except errors.NotBranchError:
289
def _get_selected_branch(self):
290
"""Return the name of the branch selected by the user.
292
:return: Name of the branch selected by the user, or None.
294
branch = self.root_transport.get_segment_parameters().get("branch")
295
if branch is not None:
296
branch = urlutils.unescape(branch)
299
def has_workingtree(self):
300
"""Tell if this controldir contains a working tree.
302
This will still raise an exception if the controldir has a workingtree
303
that is remote & inaccessible.
305
Note: if you're going to open the working tree, you should just go ahead
306
and try, and not ask permission first. (This method just opens the
307
workingtree and discards it, and that's somewhat expensive.)
310
self.open_workingtree(recommend_upgrade=False)
312
except errors.NoWorkingTree:
315
def cloning_metadir(self, require_stacking=False):
316
"""Produce a metadir suitable for cloning or sprouting with.
318
These operations may produce workingtrees (yes, even though they're
319
"cloning" something that doesn't have a tree), so a viable workingtree
320
format must be selected.
322
:require_stacking: If True, non-stackable formats will be upgraded
323
to similar stackable formats.
324
:returns: a ControlDirFormat with all component formats either set
325
appropriately or set to None if that component should not be
328
raise NotImplementedError(self.cloning_metadir)
330
def checkout_metadir(self):
331
"""Produce a metadir suitable for checkouts of this controldir."""
332
return self.cloning_metadir()
334
def sprout(self, url, revision_id=None, force_new_repo=False,
335
recurse='down', possible_transports=None,
336
accelerator_tree=None, hardlink=False, stacked=False,
337
source_branch=None, create_tree_if_local=True):
338
"""Create a copy of this controldir prepared for use as a new line of
341
If url's last component does not exist, it will be created.
343
Attributes related to the identity of the source branch like
344
branch nickname will be cleaned, a working tree is created
345
whether one existed before or not; and a local branch is always
348
:param revision_id: if revision_id is not None, then the clone
349
operation may tune itself to download less data.
350
:param accelerator_tree: A tree which can be used for retrieving file
351
contents more quickly than the revision tree, i.e. a workingtree.
352
The revision tree will be used for cases where accelerator_tree's
353
content is different.
354
:param hardlink: If true, hard-link files from accelerator_tree,
356
:param stacked: If true, create a stacked branch referring to the
357
location of this control directory.
358
:param create_tree_if_local: If true, a working-tree will be created
359
when working locally.
361
raise NotImplementedError(self.sprout)
363
def push_branch(self, source, revision_id=None, overwrite=False,
364
remember=False, create_prefix=False):
365
"""Push the source branch into this ControlDir."""
367
# If we can open a branch, use its direct repository, otherwise see
368
# if there is a repository without a branch.
370
br_to = self.open_branch()
371
except errors.NotBranchError:
372
# Didn't find a branch, can we find a repository?
373
repository_to = self.find_repository()
375
# Found a branch, so we must have found a repository
376
repository_to = br_to.repository
378
push_result = PushResult()
379
push_result.source_branch = source
381
# We have a repository but no branch, copy the revisions, and then
383
if revision_id is None:
384
# No revision supplied by the user, default to the branch
386
revision_id = source.last_revision()
387
repository_to.fetch(source.repository, revision_id=revision_id)
388
br_to = source.clone(self, revision_id=revision_id)
389
if source.get_push_location() is None or remember:
390
source.set_push_location(br_to.base)
391
push_result.stacked_on = None
392
push_result.branch_push_result = None
393
push_result.old_revno = None
394
push_result.old_revid = _mod_revision.NULL_REVISION
395
push_result.target_branch = br_to
396
push_result.master_branch = None
397
push_result.workingtree_updated = False
399
# We have successfully opened the branch, remember if necessary:
400
if source.get_push_location() is None or remember:
401
source.set_push_location(br_to.base)
403
tree_to = self.open_workingtree()
404
except errors.NotLocalUrl:
405
push_result.branch_push_result = source.push(br_to,
406
overwrite, stop_revision=revision_id)
407
push_result.workingtree_updated = False
408
except errors.NoWorkingTree:
409
push_result.branch_push_result = source.push(br_to,
410
overwrite, stop_revision=revision_id)
411
push_result.workingtree_updated = None # Not applicable
415
push_result.branch_push_result = source.push(
416
tree_to.branch, overwrite, stop_revision=revision_id)
420
push_result.workingtree_updated = True
421
push_result.old_revno = push_result.branch_push_result.old_revno
422
push_result.old_revid = push_result.branch_push_result.old_revid
423
push_result.target_branch = \
424
push_result.branch_push_result.target_branch
427
def _get_tree_branch(self, name=None):
428
"""Return the branch and tree, if any, for this controldir.
430
:param name: Name of colocated branch to open.
432
Return None for tree if not present or inaccessible.
433
Raise NotBranchError if no branch is present.
434
:return: (tree, branch)
437
tree = self.open_workingtree()
438
except (errors.NoWorkingTree, errors.NotLocalUrl):
440
branch = self.open_branch(name=name)
443
branch = self.open_branch(name=name)
448
def get_config(self):
449
"""Get configuration for this ControlDir."""
450
raise NotImplementedError(self.get_config)
452
def check_conversion_target(self, target_format):
453
"""Check that a controldir as a whole can be converted to a new format."""
454
raise NotImplementedError(self.check_conversion_target)
456
def clone(self, url, revision_id=None, force_new_repo=False,
457
preserve_stacking=False):
458
"""Clone this controldir and its contents to url verbatim.
460
:param url: The url create the clone at. If url's last component does
461
not exist, it will be created.
462
:param revision_id: The tip revision-id to use for any branch or
463
working tree. If not None, then the clone operation may tune
464
itself to download less data.
465
:param force_new_repo: Do not use a shared repository for the target
466
even if one is available.
467
:param preserve_stacking: When cloning a stacked branch, stack the
468
new branch on top of the other branch's stacked-on branch.
470
return self.clone_on_transport(_mod_transport.get_transport(url),
471
revision_id=revision_id,
472
force_new_repo=force_new_repo,
473
preserve_stacking=preserve_stacking)
475
def clone_on_transport(self, transport, revision_id=None,
476
force_new_repo=False, preserve_stacking=False, stacked_on=None,
477
create_prefix=False, use_existing_dir=True, no_tree=False):
478
"""Clone this controldir and its contents to transport verbatim.
480
:param transport: The transport for the location to produce the clone
481
at. If the target directory does not exist, it will be created.
482
:param revision_id: The tip revision-id to use for any branch or
483
working tree. If not None, then the clone operation may tune
484
itself to download less data.
485
:param force_new_repo: Do not use a shared repository for the target,
486
even if one is available.
487
:param preserve_stacking: When cloning a stacked branch, stack the
488
new branch on top of the other branch's stacked-on branch.
489
:param create_prefix: Create any missing directories leading up to
491
:param use_existing_dir: Use an existing directory if one exists.
492
:param no_tree: If set to true prevents creation of a working tree.
494
raise NotImplementedError(self.clone_on_transport)
497
def find_bzrdirs(klass, transport, evaluate=None, list_current=None):
498
"""Find control dirs recursively from current location.
500
This is intended primarily as a building block for more sophisticated
501
functionality, like finding trees under a directory, or finding
502
branches that use a given repository.
504
:param evaluate: An optional callable that yields recurse, value,
505
where recurse controls whether this controldir is recursed into
506
and value is the value to yield. By default, all bzrdirs
507
are recursed into, and the return value is the controldir.
508
:param list_current: if supplied, use this function to list the current
509
directory, instead of Transport.list_dir
510
:return: a generator of found bzrdirs, or whatever evaluate returns.
512
if list_current is None:
513
def list_current(transport):
514
return transport.list_dir('')
516
def evaluate(controldir):
517
return True, controldir
519
pending = [transport]
520
while len(pending) > 0:
521
current_transport = pending.pop()
524
controldir = klass.open_from_transport(current_transport)
525
except (errors.NotBranchError, errors.PermissionDenied):
528
recurse, value = evaluate(controldir)
531
subdirs = list_current(current_transport)
532
except (errors.NoSuchFile, errors.PermissionDenied):
535
for subdir in sorted(subdirs, reverse=True):
536
pending.append(current_transport.clone(subdir))
539
def find_branches(klass, transport):
540
"""Find all branches under a transport.
542
This will find all branches below the transport, including branches
543
inside other branches. Where possible, it will use
544
Repository.find_branches.
546
To list all the branches that use a particular Repository, see
547
Repository.find_branches
549
def evaluate(controldir):
551
repository = controldir.open_repository()
552
except errors.NoRepositoryPresent:
555
return False, ([], repository)
556
return True, (controldir.list_branches(), None)
558
for branches, repo in klass.find_bzrdirs(
559
transport, evaluate=evaluate):
561
ret.extend(repo.find_branches())
562
if branches is not None:
567
def create_branch_and_repo(klass, base, force_new_repo=False, format=None):
568
"""Create a new ControlDir, Branch and Repository at the url 'base'.
570
This will use the current default ControlDirFormat unless one is
571
specified, and use whatever
572
repository format that that uses via controldir.create_branch and
573
create_repository. If a shared repository is available that is used
576
The created Branch object is returned.
578
:param base: The URL to create the branch at.
579
:param force_new_repo: If True a new repository is always created.
580
:param format: If supplied, the format of branch to create. If not
581
supplied, the default is used.
583
controldir = klass.create(base, format)
584
controldir._find_or_create_repository(force_new_repo)
585
return controldir.create_branch()
588
def create_branch_convenience(klass, base, force_new_repo=False,
589
force_new_tree=None, format=None,
590
possible_transports=None):
591
"""Create a new ControlDir, Branch and Repository at the url 'base'.
593
This is a convenience function - it will use an existing repository
594
if possible, can be told explicitly whether to create a working tree or
597
This will use the current default ControlDirFormat unless one is
598
specified, and use whatever
599
repository format that that uses via ControlDir.create_branch and
600
create_repository. If a shared repository is available that is used
601
preferentially. Whatever repository is used, its tree creation policy
604
The created Branch object is returned.
605
If a working tree cannot be made due to base not being a file:// url,
606
no error is raised unless force_new_tree is True, in which case no
607
data is created on disk and NotLocalUrl is raised.
609
:param base: The URL to create the branch at.
610
:param force_new_repo: If True a new repository is always created.
611
:param force_new_tree: If True or False force creation of a tree or
612
prevent such creation respectively.
613
:param format: Override for the controldir format to create.
614
:param possible_transports: An optional reusable transports list.
617
# check for non local urls
618
t = _mod_transport.get_transport(base, possible_transports)
619
if not isinstance(t, local.LocalTransport):
620
raise errors.NotLocalUrl(base)
621
controldir = klass.create(base, format, possible_transports)
622
repo = controldir._find_or_create_repository(force_new_repo)
623
result = controldir.create_branch()
624
if force_new_tree or (repo.make_working_trees() and
625
force_new_tree is None):
627
controldir.create_workingtree()
628
except errors.NotLocalUrl:
633
def create_standalone_workingtree(klass, base, format=None):
634
"""Create a new ControlDir, WorkingTree, Branch and Repository at 'base'.
636
'base' must be a local path or a file:// url.
638
This will use the current default ControlDirFormat unless one is
639
specified, and use whatever
640
repository format that that uses for bzrdirformat.create_workingtree,
641
create_branch and create_repository.
643
:param format: Override for the controldir format to create.
644
:return: The WorkingTree object.
646
t = _mod_transport.get_transport(base)
647
if not isinstance(t, local.LocalTransport):
648
raise errors.NotLocalUrl(base)
649
controldir = klass.create_branch_and_repo(base,
651
format=format).bzrdir
652
return controldir.create_workingtree()
655
def open_unsupported(klass, base):
656
"""Open a branch which is not supported."""
657
return klass.open(base, _unsupported=True)
660
def open(klass, base, _unsupported=False, possible_transports=None):
661
"""Open an existing controldir, rooted at 'base' (url).
663
:param _unsupported: a private parameter to the ControlDir class.
665
t = _mod_transport.get_transport(base, possible_transports)
666
return klass.open_from_transport(t, _unsupported=_unsupported)
669
def open_from_transport(klass, transport, _unsupported=False,
670
_server_formats=True):
671
"""Open a controldir within a particular directory.
673
:param transport: Transport containing the controldir.
674
:param _unsupported: private.
676
for hook in klass.hooks['pre_open']:
678
# Keep initial base since 'transport' may be modified while following
680
base = transport.base
681
def find_format(transport):
682
return transport, ControlDirFormat.find_format(
683
transport, _server_formats=_server_formats)
685
def redirected(transport, e, redirection_notice):
686
redirected_transport = transport._redirected_to(e.source, e.target)
687
if redirected_transport is None:
688
raise errors.NotBranchError(base)
689
trace.note(gettext('{0} is{1} redirected to {2}').format(
690
transport.base, e.permanently, redirected_transport.base))
691
return redirected_transport
694
transport, format = _mod_transport.do_catching_redirections(
695
find_format, transport, redirected)
696
except errors.TooManyRedirections:
697
raise errors.NotBranchError(base)
699
format.check_support_status(_unsupported)
700
return format.open(transport, _found=True)
703
def open_containing(klass, url, possible_transports=None):
704
"""Open an existing branch which contains url.
706
:param url: url to search from.
708
See open_containing_from_transport for more detail.
710
transport = _mod_transport.get_transport(url, possible_transports)
711
return klass.open_containing_from_transport(transport)
714
def open_containing_from_transport(klass, a_transport):
715
"""Open an existing branch which contains a_transport.base.
717
This probes for a branch at a_transport, and searches upwards from there.
719
Basically we keep looking up until we find the control directory or
720
run into the root. If there isn't one, raises NotBranchError.
721
If there is one and it is either an unrecognised format or an unsupported
722
format, UnknownFormatError or UnsupportedFormatError are raised.
723
If there is one, it is returned, along with the unused portion of url.
725
:return: The ControlDir that contains the path, and a Unicode path
726
for the rest of the URL.
728
# this gets the normalised url back. I.e. '.' -> the full path.
729
url = a_transport.base
732
result = klass.open_from_transport(a_transport)
733
return result, urlutils.unescape(a_transport.relpath(url))
734
except errors.NotBranchError, e:
737
new_t = a_transport.clone('..')
738
except errors.InvalidURLJoin:
739
# reached the root, whatever that may be
740
raise errors.NotBranchError(path=url)
741
if new_t.base == a_transport.base:
742
# reached the root, whatever that may be
743
raise errors.NotBranchError(path=url)
747
def open_tree_or_branch(klass, location):
748
"""Return the branch and working tree at a location.
750
If there is no tree at the location, tree will be None.
751
If there is no branch at the location, an exception will be
753
:return: (tree, branch)
755
controldir = klass.open(location)
756
return controldir._get_tree_branch()
759
def open_containing_tree_or_branch(klass, location):
760
"""Return the branch and working tree contained by a location.
762
Returns (tree, branch, relpath).
763
If there is no tree at containing the location, tree will be None.
764
If there is no branch containing the location, an exception will be
766
relpath is the portion of the path that is contained by the branch.
768
controldir, relpath = klass.open_containing(location)
769
tree, branch = controldir._get_tree_branch()
770
return tree, branch, relpath
773
def open_containing_tree_branch_or_repository(klass, location):
774
"""Return the working tree, branch and repo contained by a location.
776
Returns (tree, branch, repository, relpath).
777
If there is no tree containing the location, tree will be None.
778
If there is no branch containing the location, branch will be None.
779
If there is no repository containing the location, repository will be
781
relpath is the portion of the path that is contained by the innermost
784
If no tree, branch or repository is found, a NotBranchError is raised.
786
controldir, relpath = klass.open_containing(location)
788
tree, branch = controldir._get_tree_branch()
789
except errors.NotBranchError:
791
repo = controldir.find_repository()
792
return None, None, repo, relpath
793
except (errors.NoRepositoryPresent):
794
raise errors.NotBranchError(location)
795
return tree, branch, branch.repository, relpath
798
def create(klass, base, format=None, possible_transports=None):
799
"""Create a new ControlDir at the url 'base'.
801
:param format: If supplied, the format of branch to create. If not
802
supplied, the default is used.
803
:param possible_transports: If supplied, a list of transports that
804
can be reused to share a remote connection.
806
if klass is not ControlDir:
807
raise AssertionError("ControlDir.create always creates the"
808
"default format, not one of %r" % klass)
809
t = _mod_transport.get_transport(base, possible_transports)
812
format = ControlDirFormat.get_default_format()
813
return format.initialize_on_transport(t)
816
class ControlDirHooks(hooks.Hooks):
817
"""Hooks for ControlDir operations."""
820
"""Create the default hooks."""
821
hooks.Hooks.__init__(self, "bzrlib.controldir", "ControlDir.hooks")
822
self.add_hook('pre_open',
823
"Invoked before attempting to open a ControlDir with the transport "
824
"that the open will use.", (1, 14))
825
self.add_hook('post_repo_init',
826
"Invoked after a repository has been initialized. "
827
"post_repo_init is called with a "
828
"bzrlib.controldir.RepoInitHookParams.",
831
# install the default hooks
832
ControlDir.hooks = ControlDirHooks()
835
class ControlComponentFormat(object):
836
"""A component that can live inside of a .bzr meta directory."""
838
upgrade_recommended = False
840
def get_format_description(self):
841
"""Return the short description for this format."""
842
raise NotImplementedError(self.get_format_description)
844
def is_supported(self):
845
"""Is this format supported?
847
Supported formats must be initializable and openable.
848
Unsupported formats may not support initialization or committing or
849
some other features depending on the reason for not being supported.
853
def check_support_status(self, allow_unsupported, recommend_upgrade=True,
855
"""Give an error or warning on old formats.
857
:param allow_unsupported: If true, allow opening
858
formats that are strongly deprecated, and which may
859
have limited functionality.
861
:param recommend_upgrade: If true (default), warn
862
the user through the ui object that they may wish
863
to upgrade the object.
865
if not allow_unsupported and not self.is_supported():
866
# see open_downlevel to open legacy branches.
867
raise errors.UnsupportedFormatError(format=self)
868
if recommend_upgrade and self.upgrade_recommended:
869
ui.ui_factory.recommend_upgrade(
870
self.get_format_description(), basedir)
873
def get_format_string(cls):
874
raise NotImplementedError(cls.get_format_string)
877
class ControlComponentFormatRegistry(registry.FormatRegistry):
878
"""A registry for control components (branch, workingtree, repository)."""
880
def __init__(self, other_registry=None):
881
super(ControlComponentFormatRegistry, self).__init__(other_registry)
882
self._extra_formats = []
884
def register(self, format):
885
"""Register a new format."""
886
super(ControlComponentFormatRegistry, self).register(
887
format.get_format_string(), format)
889
def remove(self, format):
890
"""Remove a registered format."""
891
super(ControlComponentFormatRegistry, self).remove(
892
format.get_format_string())
894
def register_extra(self, format):
895
"""Register a format that can not be used in a metadir.
897
This is mainly useful to allow custom repository formats, such as older
898
Bazaar formats and foreign formats, to be tested.
900
self._extra_formats.append(registry._ObjectGetter(format))
902
def remove_extra(self, format):
903
"""Remove an extra format.
905
self._extra_formats.remove(registry._ObjectGetter(format))
907
def register_extra_lazy(self, module_name, member_name):
908
"""Register a format lazily.
910
self._extra_formats.append(
911
registry._LazyObjectGetter(module_name, member_name))
913
def _get_extra(self):
914
"""Return all "extra" formats, not usable in meta directories."""
916
for getter in self._extra_formats:
924
"""Return all formats, even those not usable in metadirs.
927
for name in self.keys():
932
return result + self._get_extra()
934
def _get_all_modules(self):
935
"""Return a set of the modules providing objects."""
937
for name in self.keys():
938
modules.add(self._get_module(name))
939
for getter in self._extra_formats:
940
modules.add(getter.get_module())
944
class Converter(object):
945
"""Converts a disk format object from one format to another."""
947
def convert(self, to_convert, pb):
948
"""Perform the conversion of to_convert, giving feedback via pb.
950
:param to_convert: The disk object to convert.
951
:param pb: a progress bar to use for progress information.
954
def step(self, message):
955
"""Update the pb by a step."""
957
self.pb.update(message, self.count, self.total)
960
class ControlDirFormat(object):
961
"""An encapsulation of the initialization and open routines for a format.
963
Formats provide three things:
964
* An initialization routine,
968
Formats are placed in a dict by their format string for reference
969
during controldir opening. These should be subclasses of ControlDirFormat
972
Once a format is deprecated, just deprecate the initialize and open
973
methods on the format class. Do not deprecate the object, as the
974
object will be created every system load.
976
:cvar colocated_branches: Whether this formats supports colocated branches.
977
:cvar supports_workingtrees: This control directory can co-exist with a
981
_default_format = None
982
"""The default format used for new control directories."""
985
"""The registered server format probers, e.g. RemoteBzrProber.
987
This is a list of Prober-derived classes.
991
"""The registered format probers, e.g. BzrProber.
993
This is a list of Prober-derived classes.
996
colocated_branches = False
997
"""Whether co-located branches are supported for this control dir format.
1000
supports_workingtrees = True
1001
"""Whether working trees can exist in control directories of this format.
1004
fixed_components = False
1005
"""Whether components can not change format independent of the control dir.
1008
upgrade_recommended = False
1009
"""Whether an upgrade from this format is recommended."""
1011
def get_format_description(self):
1012
"""Return the short description for this format."""
1013
raise NotImplementedError(self.get_format_description)
1015
def get_converter(self, format=None):
1016
"""Return the converter to use to convert controldirs needing converts.
1018
This returns a bzrlib.controldir.Converter object.
1020
This should return the best upgrader to step this format towards the
1021
current default format. In the case of plugins we can/should provide
1022
some means for them to extend the range of returnable converters.
1024
:param format: Optional format to override the default format of the
1027
raise NotImplementedError(self.get_converter)
1029
def is_supported(self):
1030
"""Is this format supported?
1032
Supported formats must be openable.
1033
Unsupported formats may not support initialization or committing or
1034
some other features depending on the reason for not being supported.
1038
def is_initializable(self):
1039
"""Whether new control directories of this format can be initialized.
1041
return self.is_supported()
1043
def check_support_status(self, allow_unsupported, recommend_upgrade=True,
1045
"""Give an error or warning on old formats.
1047
:param allow_unsupported: If true, allow opening
1048
formats that are strongly deprecated, and which may
1049
have limited functionality.
1051
:param recommend_upgrade: If true (default), warn
1052
the user through the ui object that they may wish
1053
to upgrade the object.
1055
if not allow_unsupported and not self.is_supported():
1056
# see open_downlevel to open legacy branches.
1057
raise errors.UnsupportedFormatError(format=self)
1058
if recommend_upgrade and self.upgrade_recommended:
1059
ui.ui_factory.recommend_upgrade(
1060
self.get_format_description(), basedir)
1062
def same_model(self, target_format):
1063
return (self.repository_format.rich_root_data ==
1064
target_format.rich_root_data)
1067
def register_format(klass, format):
1068
"""Register a format that does not use '.bzr' for its control dir.
1071
raise errors.BzrError("ControlDirFormat.register_format() has been "
1072
"removed in Bazaar 2.4. Please upgrade your plugins.")
1075
def register_prober(klass, prober):
1076
"""Register a prober that can look for a control dir.
1079
klass._probers.append(prober)
1082
def unregister_prober(klass, prober):
1083
"""Unregister a prober.
1086
klass._probers.remove(prober)
1089
def register_server_prober(klass, prober):
1090
"""Register a control format prober for client-server environments.
1092
These probers will be used before ones registered with
1093
register_prober. This gives implementations that decide to the
1094
chance to grab it before anything looks at the contents of the format
1097
klass._server_probers.append(prober)
1101
return self.get_format_description().rstrip()
1104
def known_formats(klass):
1105
"""Return all the known formats.
1108
for prober_kls in klass._probers + klass._server_probers:
1109
result.update(prober_kls.known_formats())
1113
def find_format(klass, transport, _server_formats=True):
1114
"""Return the format present at transport."""
1116
_probers = klass._server_probers + klass._probers
1118
_probers = klass._probers
1119
for prober_kls in _probers:
1120
prober = prober_kls()
1122
return prober.probe_transport(transport)
1123
except errors.NotBranchError:
1124
# this format does not find a control dir here.
1126
raise errors.NotBranchError(path=transport.base)
1128
def initialize(self, url, possible_transports=None):
1129
"""Create a control dir at this url and return an opened copy.
1131
While not deprecated, this method is very specific and its use will
1132
lead to many round trips to setup a working environment. See
1133
initialize_on_transport_ex for a [nearly] all-in-one method.
1135
Subclasses should typically override initialize_on_transport
1136
instead of this method.
1138
return self.initialize_on_transport(
1139
_mod_transport.get_transport(url, possible_transports))
1141
def initialize_on_transport(self, transport):
1142
"""Initialize a new controldir in the base directory of a Transport."""
1143
raise NotImplementedError(self.initialize_on_transport)
1145
def initialize_on_transport_ex(self, transport, use_existing_dir=False,
1146
create_prefix=False, force_new_repo=False, stacked_on=None,
1147
stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
1148
shared_repo=False, vfs_only=False):
1149
"""Create this format on transport.
1151
The directory to initialize will be created.
1153
:param force_new_repo: Do not use a shared repository for the target,
1154
even if one is available.
1155
:param create_prefix: Create any missing directories leading up to
1157
:param use_existing_dir: Use an existing directory if one exists.
1158
:param stacked_on: A url to stack any created branch on, None to follow
1159
any target stacking policy.
1160
:param stack_on_pwd: If stack_on is relative, the location it is
1162
:param repo_format_name: If non-None, a repository will be
1163
made-or-found. Should none be found, or if force_new_repo is True
1164
the repo_format_name is used to select the format of repository to
1166
:param make_working_trees: Control the setting of make_working_trees
1167
for a new shared repository when one is made. None to use whatever
1168
default the format has.
1169
:param shared_repo: Control whether made repositories are shared or
1171
:param vfs_only: If True do not attempt to use a smart server
1172
:return: repo, controldir, require_stacking, repository_policy. repo is
1173
None if none was created or found, controldir is always valid.
1174
require_stacking is the result of examining the stacked_on
1175
parameter and any stacking policy found for the target.
1177
raise NotImplementedError(self.initialize_on_transport_ex)
1179
def network_name(self):
1180
"""A simple byte string uniquely identifying this format for RPC calls.
1182
Bzr control formats use this disk format string to identify the format
1183
over the wire. Its possible that other control formats have more
1184
complex detection requirements, so we permit them to use any unique and
1185
immutable string they desire.
1187
raise NotImplementedError(self.network_name)
1189
def open(self, transport, _found=False):
1190
"""Return an instance of this format for the dir transport points at.
1192
raise NotImplementedError(self.open)
1195
def _set_default_format(klass, format):
1196
"""Set default format (for testing behavior of defaults only)"""
1197
klass._default_format = format
1200
def get_default_format(klass):
1201
"""Return the current default format."""
1202
return klass._default_format
1204
def supports_transport(self, transport):
1205
"""Check if this format can be opened over a particular transport.
1207
raise NotImplementedError(self.supports_transport)
1210
class Prober(object):
1211
"""Abstract class that can be used to detect a particular kind of
1214
At the moment this just contains a single method to probe a particular
1215
transport, but it may be extended in the future to e.g. avoid
1216
multiple levels of probing for Subversion repositories.
1218
See BzrProber and RemoteBzrProber in bzrlib.bzrdir for the
1219
probers that detect .bzr/ directories and Bazaar smart servers,
1222
Probers should be registered using the register_server_prober or
1223
register_prober methods on ControlDirFormat.
1226
def probe_transport(self, transport):
1227
"""Return the controldir style format present in a directory.
1229
:raise UnknownFormatError: If a control dir was found but is
1230
in an unknown format.
1231
:raise NotBranchError: If no control directory was found.
1232
:return: A ControlDirFormat instance.
1234
raise NotImplementedError(self.probe_transport)
1237
def known_formats(klass):
1238
"""Return the control dir formats known by this prober.
1240
Multiple probers can return the same formats, so this should
1243
:return: A set of known formats.
1245
raise NotImplementedError(klass.known_formats)
1248
class ControlDirFormatInfo(object):
1250
def __init__(self, native, deprecated, hidden, experimental):
1251
self.deprecated = deprecated
1252
self.native = native
1253
self.hidden = hidden
1254
self.experimental = experimental
1257
class ControlDirFormatRegistry(registry.Registry):
1258
"""Registry of user-selectable ControlDir subformats.
1260
Differs from ControlDirFormat._formats in that it provides sub-formats,
1261
e.g. BzrDirMeta1 with weave repository. Also, it's more user-oriented.
1265
"""Create a ControlDirFormatRegistry."""
1266
self._aliases = set()
1267
self._registration_order = list()
1268
super(ControlDirFormatRegistry, self).__init__()
1271
"""Return a set of the format names which are aliases."""
1272
return frozenset(self._aliases)
1274
def register(self, key, factory, help, native=True, deprecated=False,
1275
hidden=False, experimental=False, alias=False):
1276
"""Register a ControlDirFormat factory.
1278
The factory must be a callable that takes one parameter: the key.
1279
It must produce an instance of the ControlDirFormat when called.
1281
This function mainly exists to prevent the info object from being
1284
registry.Registry.register(self, key, factory, help,
1285
ControlDirFormatInfo(native, deprecated, hidden, experimental))
1287
self._aliases.add(key)
1288
self._registration_order.append(key)
1290
def register_lazy(self, key, module_name, member_name, help, native=True,
1291
deprecated=False, hidden=False, experimental=False, alias=False):
1292
registry.Registry.register_lazy(self, key, module_name, member_name,
1293
help, ControlDirFormatInfo(native, deprecated, hidden, experimental))
1295
self._aliases.add(key)
1296
self._registration_order.append(key)
1298
def set_default(self, key):
1299
"""Set the 'default' key to be a clone of the supplied key.
1301
This method must be called once and only once.
1303
registry.Registry.register(self, 'default', self.get(key),
1304
self.get_help(key), info=self.get_info(key))
1305
self._aliases.add('default')
1307
def set_default_repository(self, key):
1308
"""Set the FormatRegistry default and Repository default.
1310
This is a transitional method while Repository.set_default_format
1313
if 'default' in self:
1314
self.remove('default')
1315
self.set_default(key)
1316
format = self.get('default')()
1318
def make_bzrdir(self, key):
1319
return self.get(key)()
1321
def help_topic(self, topic):
1323
default_realkey = None
1324
default_help = self.get_help('default')
1326
for key in self._registration_order:
1327
if key == 'default':
1329
help = self.get_help(key)
1330
if help == default_help:
1331
default_realkey = key
1333
help_pairs.append((key, help))
1335
def wrapped(key, help, info):
1337
help = '(native) ' + help
1338
return ':%s:\n%s\n\n' % (key,
1339
textwrap.fill(help, initial_indent=' ',
1340
subsequent_indent=' ',
1341
break_long_words=False))
1342
if default_realkey is not None:
1343
output += wrapped(default_realkey, '(default) %s' % default_help,
1344
self.get_info('default'))
1345
deprecated_pairs = []
1346
experimental_pairs = []
1347
for key, help in help_pairs:
1348
info = self.get_info(key)
1351
elif info.deprecated:
1352
deprecated_pairs.append((key, help))
1353
elif info.experimental:
1354
experimental_pairs.append((key, help))
1356
output += wrapped(key, help, info)
1357
output += "\nSee :doc:`formats-help` for more about storage formats."
1359
if len(experimental_pairs) > 0:
1360
other_output += "Experimental formats are shown below.\n\n"
1361
for key, help in experimental_pairs:
1362
info = self.get_info(key)
1363
other_output += wrapped(key, help, info)
1366
"No experimental formats are available.\n\n"
1367
if len(deprecated_pairs) > 0:
1368
other_output += "\nDeprecated formats are shown below.\n\n"
1369
for key, help in deprecated_pairs:
1370
info = self.get_info(key)
1371
other_output += wrapped(key, help, info)
1374
"\nNo deprecated formats are available.\n\n"
1376
"\nSee :doc:`formats-help` for more about storage formats."
1378
if topic == 'other-formats':
1384
class RepoInitHookParams(object):
1385
"""Object holding parameters passed to `*_repo_init` hooks.
1387
There are 4 fields that hooks may wish to access:
1389
:ivar repository: Repository created
1390
:ivar format: Repository format
1391
:ivar bzrdir: The controldir for the repository
1392
:ivar shared: The repository is shared
1395
def __init__(self, repository, format, controldir, shared):
1396
"""Create a group of RepoInitHook parameters.
1398
:param repository: Repository created
1399
:param format: Repository format
1400
:param controldir: The controldir for the repository
1401
:param shared: The repository is shared
1403
self.repository = repository
1404
self.format = format
1405
self.bzrdir = controldir
1406
self.shared = shared
1408
def __eq__(self, other):
1409
return self.__dict__ == other.__dict__
1413
return "<%s for %s>" % (self.__class__.__name__,
1416
return "<%s for %s>" % (self.__class__.__name__,
1420
# Please register new formats after old formats so that formats
1421
# appear in chronological order and format descriptions can build
1423
format_registry = ControlDirFormatRegistry()
1425
network_format_registry = registry.FormatRegistry()
1426
"""Registry of formats indexed by their network name.
1428
The network name for a ControlDirFormat is an identifier that can be used when
1429
referring to formats with smart server operations. See
1430
ControlDirFormat.network_name() for more detail.