1
# Copyright (C) 2010, 2011, 2012 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 breezy.bzrdir.BzrDir.
25
from __future__ import absolute_import
27
from .lazy_import import lazy_import
28
lazy_import(globals(), """
32
branch as _mod_branch,
34
revision as _mod_revision,
35
transport as _mod_transport,
40
from breezy.transport import local
41
from breezy.push import (
45
from breezy.i18n import gettext
54
class MustHaveWorkingTree(errors.BzrError):
56
_fmt = "Branching '%(url)s'(%(format)s) must create a working tree."
58
def __init__(self, format, url):
59
errors.BzrError.__init__(self, format=format, url=url)
62
class BranchReferenceLoop(errors.BzrError):
64
_fmt = "Can not create branch reference that points at branch itself."
66
def __init__(self, branch):
67
errors.BzrError.__init__(self, branch=branch)
70
class ControlComponent(object):
71
"""Abstract base class for control directory components.
73
This provides interfaces that are common across controldirs,
74
repositories, branches, and workingtree control directories.
76
They all expose two urls and transports: the *user* URL is the
77
one that stops above the control directory (eg .bzr) and that
78
should normally be used in messages, and the *control* URL is
79
under that in eg .bzr/checkout and is used to read the control
82
This can be used as a mixin and is intended to fit with
87
def control_transport(self):
88
raise NotImplementedError
91
def control_url(self):
92
return self.control_transport.base
95
def user_transport(self):
96
raise NotImplementedError
100
return self.user_transport.base
103
class ControlDir(ControlComponent):
104
"""A control directory.
106
While this represents a generic control directory, there are a few
107
features that are present in this interface that are currently only
108
supported by one of its implementations, BzrDir.
110
These features (bound branches, stacked branches) are currently only
111
supported by Bazaar, but could be supported by other version control
112
systems as well. Implementations are required to raise the appropriate
113
exceptions when an operation is requested that is not supported.
115
This also makes life easier for API users who can rely on the
116
implementation always allowing a particular feature to be requested but
117
raising an exception when it is not supported, rather than requiring the
118
API users to check for magic attributes to see what features are supported.
121
def can_convert_format(self):
122
"""Return true if this controldir is one whose format we can convert
126
def list_branches(self):
127
"""Return a sequence of all branches local to this control directory.
130
return list(self.get_branches().values())
132
def get_branches(self):
133
"""Get all branches in this control directory, as a dictionary.
135
:return: Dictionary mapping branch names to instances.
138
return {"": self.open_branch()}
139
except (errors.NotBranchError, errors.NoRepositoryPresent):
142
def is_control_filename(self, filename):
143
"""True if filename is the name of a path which is reserved for
146
:param filename: A filename within the root transport of this
149
This is true IF and ONLY IF the filename is part of the namespace reserved
150
for bzr control dirs. Currently this is the '.bzr' directory in the root
151
of the root_transport. it is expected that plugins will need to extend
152
this in the future - for instance to make bzr talk with svn working
155
return self._format.is_control_filename(filename)
157
def needs_format_conversion(self, format=None):
158
"""Return true if this controldir needs convert_format run on it.
160
For instance, if the repository format is out of date but the
161
branch and working tree are not, this should return True.
163
:param format: Optional parameter indicating a specific desired
164
format we plan to arrive at.
166
raise NotImplementedError(self.needs_format_conversion)
168
def create_repository(self, shared=False):
169
"""Create a new repository in this control directory.
171
:param shared: If a shared repository should be created
172
:return: The newly created repository
174
raise NotImplementedError(self.create_repository)
176
def destroy_repository(self):
177
"""Destroy the repository in this ControlDir."""
178
raise NotImplementedError(self.destroy_repository)
180
def create_branch(self, name=None, repository=None,
181
append_revisions_only=None):
182
"""Create a branch in this ControlDir.
184
:param name: Name of the colocated branch to create, None for
185
the user selected branch or "" for the active branch.
186
:param append_revisions_only: Whether this branch should only allow
187
appending new revisions to its history.
189
The controldirs format will control what branch format is created.
190
For more control see BranchFormatXX.create(a_controldir).
192
raise NotImplementedError(self.create_branch)
194
def destroy_branch(self, name=None):
195
"""Destroy a branch in this ControlDir.
197
:param name: Name of the branch to destroy, None for the
198
user selected branch or "" for the active branch.
199
:raise NotBranchError: When the branch does not exist
201
raise NotImplementedError(self.destroy_branch)
203
def create_workingtree(self, revision_id=None, from_branch=None,
204
accelerator_tree=None, hardlink=False):
205
"""Create a working tree at this ControlDir.
207
:param revision_id: create it as of this revision id.
208
:param from_branch: override controldir branch
209
(for lightweight checkouts)
210
:param accelerator_tree: A tree which can be used for retrieving file
211
contents more quickly than the revision tree, i.e. a workingtree.
212
The revision tree will be used for cases where accelerator_tree's
213
content is different.
215
raise NotImplementedError(self.create_workingtree)
217
def destroy_workingtree(self):
218
"""Destroy the working tree at this ControlDir.
220
Formats that do not support this may raise UnsupportedOperation.
222
raise NotImplementedError(self.destroy_workingtree)
224
def destroy_workingtree_metadata(self):
225
"""Destroy the control files for the working tree at this ControlDir.
227
The contents of working tree files are not affected.
228
Formats that do not support this may raise UnsupportedOperation.
230
raise NotImplementedError(self.destroy_workingtree_metadata)
232
def find_branch_format(self, name=None):
233
"""Find the branch 'format' for this controldir.
235
This might be a synthetic object for e.g. RemoteBranch and SVN.
237
raise NotImplementedError(self.find_branch_format)
239
def get_branch_reference(self, name=None):
240
"""Return the referenced URL for the branch in this controldir.
242
:param name: Optional colocated branch name
243
:raises NotBranchError: If there is no Branch.
244
:raises NoColocatedBranchSupport: If a branch name was specified
245
but colocated branches are not supported.
246
:return: The URL the branch in this controldir references if it is a
247
reference branch, or None for regular branches.
250
raise errors.NoColocatedBranchSupport(self)
253
def set_branch_reference(self, target_branch, name=None):
254
"""Set the referenced URL for the branch in this controldir.
256
:param name: Optional colocated branch name
257
:param target_branch: Branch to reference
258
:raises NoColocatedBranchSupport: If a branch name was specified
259
but colocated branches are not supported.
260
:return: The referencing branch
262
raise NotImplementedError(self.set_branch_reference)
264
def open_branch(self, name=None, unsupported=False,
265
ignore_fallbacks=False, possible_transports=None):
266
"""Open the branch object at this ControlDir if one is present.
268
:param unsupported: if True, then no longer supported branch formats can
270
:param ignore_fallbacks: Whether to open fallback repositories
271
:param possible_transports: Transports to use for opening e.g.
272
fallback repositories.
274
raise NotImplementedError(self.open_branch)
276
def open_repository(self, _unsupported=False):
277
"""Open the repository object at this ControlDir if one is present.
279
This will not follow the Branch object pointer - it's strictly a direct
280
open facility. Most client code should use open_branch().repository to
283
:param _unsupported: a private parameter, not part of the api.
285
raise NotImplementedError(self.open_repository)
287
def find_repository(self):
288
"""Find the repository that should be used.
290
This does not require a branch as we use it to find the repo for
291
new branches as well as to hook existing branches up to their
294
raise NotImplementedError(self.find_repository)
296
def open_workingtree(self, unsupported=False,
297
recommend_upgrade=True, from_branch=None):
298
"""Open the workingtree object at this ControlDir if one is present.
300
:param recommend_upgrade: Optional keyword parameter, when True (the
301
default), emit through the ui module a recommendation that the user
302
upgrade the working tree when the workingtree being opened is old
303
(but still fully supported).
304
:param from_branch: override controldir branch (for lightweight
307
raise NotImplementedError(self.open_workingtree)
309
def has_branch(self, name=None):
310
"""Tell if this controldir contains a branch.
312
Note: if you're going to open the branch, you should just go ahead
313
and try, and not ask permission first. (This method just opens the
314
branch and discards it, and that's somewhat expensive.)
317
self.open_branch(name, ignore_fallbacks=True)
319
except errors.NotBranchError:
322
def _get_selected_branch(self):
323
"""Return the name of the branch selected by the user.
325
:return: Name of the branch selected by the user, or "".
327
branch = self.root_transport.get_segment_parameters().get("branch")
330
return urlutils.unescape(branch)
332
def has_workingtree(self):
333
"""Tell if this controldir contains a working tree.
335
This will still raise an exception if the controldir has a workingtree
336
that is remote & inaccessible.
338
Note: if you're going to open the working tree, you should just go ahead
339
and try, and not ask permission first. (This method just opens the
340
workingtree and discards it, and that's somewhat expensive.)
343
self.open_workingtree(recommend_upgrade=False)
345
except errors.NoWorkingTree:
348
def cloning_metadir(self, require_stacking=False):
349
"""Produce a metadir suitable for cloning or sprouting with.
351
These operations may produce workingtrees (yes, even though they're
352
"cloning" something that doesn't have a tree), so a viable workingtree
353
format must be selected.
355
:require_stacking: If True, non-stackable formats will be upgraded
356
to similar stackable formats.
357
:returns: a ControlDirFormat with all component formats either set
358
appropriately or set to None if that component should not be
361
raise NotImplementedError(self.cloning_metadir)
363
def checkout_metadir(self):
364
"""Produce a metadir suitable for checkouts of this controldir.
366
:returns: A ControlDirFormat with all component formats
367
either set appropriately or set to None if that component
368
should not be created.
370
return self.cloning_metadir()
372
def sprout(self, url, revision_id=None, force_new_repo=False,
373
recurse='down', possible_transports=None,
374
accelerator_tree=None, hardlink=False, stacked=False,
375
source_branch=None, create_tree_if_local=True,
377
"""Create a copy of this controldir prepared for use as a new line of
380
If url's last component does not exist, it will be created.
382
Attributes related to the identity of the source branch like
383
branch nickname will be cleaned, a working tree is created
384
whether one existed before or not; and a local branch is always
387
:param revision_id: if revision_id is not None, then the clone
388
operation may tune itself to download less data.
389
:param accelerator_tree: A tree which can be used for retrieving file
390
contents more quickly than the revision tree, i.e. a workingtree.
391
The revision tree will be used for cases where accelerator_tree's
392
content is different.
393
:param hardlink: If true, hard-link files from accelerator_tree,
395
:param stacked: If true, create a stacked branch referring to the
396
location of this control directory.
397
:param create_tree_if_local: If true, a working-tree will be created
398
when working locally.
400
raise NotImplementedError(self.sprout)
402
def push_branch(self, source, revision_id=None, overwrite=False,
403
remember=False, create_prefix=False, lossy=False):
404
"""Push the source branch into this ControlDir."""
406
# If we can open a branch, use its direct repository, otherwise see
407
# if there is a repository without a branch.
409
br_to = self.open_branch()
410
except errors.NotBranchError:
411
# Didn't find a branch, can we find a repository?
412
repository_to = self.find_repository()
414
# Found a branch, so we must have found a repository
415
repository_to = br_to.repository
417
push_result = PushResult()
418
push_result.source_branch = source
420
# We have a repository but no branch, copy the revisions, and then
422
if revision_id is None:
423
# No revision supplied by the user, default to the branch
425
revision_id = source.last_revision()
426
repository_to.fetch(source.repository, revision_id=revision_id)
427
br_to = source.sprout(self, revision_id=revision_id, lossy=lossy)
428
if source.get_push_location() is None or remember:
429
# FIXME: Should be done only if we succeed ? -- vila 2012-01-18
430
source.set_push_location(br_to.base)
431
push_result.stacked_on = None
432
push_result.branch_push_result = None
433
push_result.old_revno = None
434
push_result.old_revid = _mod_revision.NULL_REVISION
435
push_result.target_branch = br_to
436
push_result.master_branch = None
437
push_result.workingtree_updated = False
439
# We have successfully opened the branch, remember if necessary:
440
if source.get_push_location() is None or remember:
441
# FIXME: Should be done only if we succeed ? -- vila 2012-01-18
442
source.set_push_location(br_to.base)
444
tree_to = self.open_workingtree()
445
except errors.NotLocalUrl:
446
push_result.branch_push_result = source.push(
447
br_to, overwrite, stop_revision=revision_id, lossy=lossy)
448
push_result.workingtree_updated = False
449
except errors.NoWorkingTree:
450
push_result.branch_push_result = source.push(
451
br_to, overwrite, stop_revision=revision_id, lossy=lossy)
452
push_result.workingtree_updated = None # Not applicable
454
with tree_to.lock_write():
455
push_result.branch_push_result = source.push(
456
tree_to.branch, overwrite, stop_revision=revision_id,
459
push_result.workingtree_updated = True
460
push_result.old_revno = push_result.branch_push_result.old_revno
461
push_result.old_revid = push_result.branch_push_result.old_revid
462
push_result.target_branch = \
463
push_result.branch_push_result.target_branch
466
def _get_tree_branch(self, name=None):
467
"""Return the branch and tree, if any, for this controldir.
469
:param name: Name of colocated branch to open.
471
Return None for tree if not present or inaccessible.
472
Raise NotBranchError if no branch is present.
473
:return: (tree, branch)
476
tree = self.open_workingtree()
477
except (errors.NoWorkingTree, errors.NotLocalUrl):
479
branch = self.open_branch(name=name)
482
branch = self.open_branch(name=name)
487
def get_config(self):
488
"""Get configuration for this ControlDir."""
489
raise NotImplementedError(self.get_config)
491
def check_conversion_target(self, target_format):
492
"""Check that a controldir as a whole can be converted to a new format."""
493
raise NotImplementedError(self.check_conversion_target)
495
def clone(self, url, revision_id=None, force_new_repo=False,
496
preserve_stacking=False):
497
"""Clone this controldir and its contents to url verbatim.
499
:param url: The url create the clone at. If url's last component does
500
not exist, it will be created.
501
:param revision_id: The tip revision-id to use for any branch or
502
working tree. If not None, then the clone operation may tune
503
itself to download less data.
504
:param force_new_repo: Do not use a shared repository for the target
505
even if one is available.
506
:param preserve_stacking: When cloning a stacked branch, stack the
507
new branch on top of the other branch's stacked-on branch.
509
return self.clone_on_transport(_mod_transport.get_transport(url),
510
revision_id=revision_id,
511
force_new_repo=force_new_repo,
512
preserve_stacking=preserve_stacking)
514
def clone_on_transport(self, transport, revision_id=None,
515
force_new_repo=False, preserve_stacking=False, stacked_on=None,
516
create_prefix=False, use_existing_dir=True, no_tree=False):
517
"""Clone this controldir and its contents to transport verbatim.
519
:param transport: The transport for the location to produce the clone
520
at. If the target directory does not exist, it will be created.
521
:param revision_id: The tip revision-id to use for any branch or
522
working tree. If not None, then the clone operation may tune
523
itself to download less data.
524
:param force_new_repo: Do not use a shared repository for the target,
525
even if one is available.
526
:param preserve_stacking: When cloning a stacked branch, stack the
527
new branch on top of the other branch's stacked-on branch.
528
:param create_prefix: Create any missing directories leading up to
530
:param use_existing_dir: Use an existing directory if one exists.
531
:param no_tree: If set to true prevents creation of a working tree.
533
raise NotImplementedError(self.clone_on_transport)
536
def find_controldirs(klass, transport, evaluate=None, list_current=None):
537
"""Find control dirs recursively from current location.
539
This is intended primarily as a building block for more sophisticated
540
functionality, like finding trees under a directory, or finding
541
branches that use a given repository.
543
:param evaluate: An optional callable that yields recurse, value,
544
where recurse controls whether this controldir is recursed into
545
and value is the value to yield. By default, all bzrdirs
546
are recursed into, and the return value is the controldir.
547
:param list_current: if supplied, use this function to list the current
548
directory, instead of Transport.list_dir
549
:return: a generator of found bzrdirs, or whatever evaluate returns.
551
if list_current is None:
552
def list_current(transport):
553
return transport.list_dir('')
555
def evaluate(controldir):
556
return True, controldir
558
pending = [transport]
559
while len(pending) > 0:
560
current_transport = pending.pop()
563
controldir = klass.open_from_transport(current_transport)
564
except (errors.NotBranchError, errors.PermissionDenied,
565
errors.UnknownFormatError):
568
recurse, value = evaluate(controldir)
571
subdirs = list_current(current_transport)
572
except (errors.NoSuchFile, errors.PermissionDenied):
575
for subdir in sorted(subdirs, reverse=True):
576
pending.append(current_transport.clone(subdir))
579
def find_branches(klass, transport):
580
"""Find all branches under a transport.
582
This will find all branches below the transport, including branches
583
inside other branches. Where possible, it will use
584
Repository.find_branches.
586
To list all the branches that use a particular Repository, see
587
Repository.find_branches
589
def evaluate(controldir):
591
repository = controldir.open_repository()
592
except errors.NoRepositoryPresent:
595
return False, ([], repository)
596
return True, (controldir.list_branches(), None)
598
for branches, repo in klass.find_controldirs(
599
transport, evaluate=evaluate):
601
ret.extend(repo.find_branches())
602
if branches is not None:
607
def create_branch_and_repo(klass, base, force_new_repo=False, format=None):
608
"""Create a new ControlDir, Branch and Repository at the url 'base'.
610
This will use the current default ControlDirFormat unless one is
611
specified, and use whatever
612
repository format that that uses via controldir.create_branch and
613
create_repository. If a shared repository is available that is used
616
The created Branch object is returned.
618
:param base: The URL to create the branch at.
619
:param force_new_repo: If True a new repository is always created.
620
:param format: If supplied, the format of branch to create. If not
621
supplied, the default is used.
623
controldir = klass.create(base, format)
624
controldir._find_or_create_repository(force_new_repo)
625
return controldir.create_branch()
628
def create_branch_convenience(klass, base, force_new_repo=False,
629
force_new_tree=None, format=None,
630
possible_transports=None):
631
"""Create a new ControlDir, Branch and Repository at the url 'base'.
633
This is a convenience function - it will use an existing repository
634
if possible, can be told explicitly whether to create a working tree or
637
This will use the current default ControlDirFormat unless one is
638
specified, and use whatever
639
repository format that that uses via ControlDir.create_branch and
640
create_repository. If a shared repository is available that is used
641
preferentially. Whatever repository is used, its tree creation policy
644
The created Branch object is returned.
645
If a working tree cannot be made due to base not being a file:// url,
646
no error is raised unless force_new_tree is True, in which case no
647
data is created on disk and NotLocalUrl is raised.
649
:param base: The URL to create the branch at.
650
:param force_new_repo: If True a new repository is always created.
651
:param force_new_tree: If True or False force creation of a tree or
652
prevent such creation respectively.
653
:param format: Override for the controldir format to create.
654
:param possible_transports: An optional reusable transports list.
657
# check for non local urls
658
t = _mod_transport.get_transport(base, possible_transports)
659
if not isinstance(t, local.LocalTransport):
660
raise errors.NotLocalUrl(base)
661
controldir = klass.create(base, format, possible_transports)
662
repo = controldir._find_or_create_repository(force_new_repo)
663
result = controldir.create_branch()
664
if force_new_tree or (repo.make_working_trees() and
665
force_new_tree is None):
667
controldir.create_workingtree()
668
except errors.NotLocalUrl:
673
def create_standalone_workingtree(klass, base, format=None):
674
"""Create a new ControlDir, WorkingTree, Branch and Repository at 'base'.
676
'base' must be a local path or a file:// url.
678
This will use the current default ControlDirFormat unless one is
679
specified, and use whatever
680
repository format that that uses for bzrdirformat.create_workingtree,
681
create_branch and create_repository.
683
:param format: Override for the controldir format to create.
684
:return: The WorkingTree object.
686
t = _mod_transport.get_transport(base)
687
if not isinstance(t, local.LocalTransport):
688
raise errors.NotLocalUrl(base)
689
controldir = klass.create_branch_and_repo(base,
691
format=format).controldir
692
return controldir.create_workingtree()
695
def open_unsupported(klass, base):
696
"""Open a branch which is not supported."""
697
return klass.open(base, _unsupported=True)
700
def open(klass, base, possible_transports=None, probers=None,
702
"""Open an existing controldir, rooted at 'base' (url).
704
:param _unsupported: a private parameter to the ControlDir class.
706
t = _mod_transport.get_transport(base, possible_transports)
707
return klass.open_from_transport(t, probers=probers,
708
_unsupported=_unsupported)
711
def open_from_transport(klass, transport, _unsupported=False,
713
"""Open a controldir within a particular directory.
715
:param transport: Transport containing the controldir.
716
:param _unsupported: private.
718
for hook in klass.hooks['pre_open']:
720
# Keep initial base since 'transport' may be modified while following
722
base = transport.base
724
def find_format(transport):
725
return transport, ControlDirFormat.find_format(transport,
728
def redirected(transport, e, redirection_notice):
729
redirected_transport = transport._redirected_to(e.source, e.target)
730
if redirected_transport is None:
731
raise errors.NotBranchError(base)
732
trace.note(gettext('{0} is{1} redirected to {2}').format(
733
transport.base, e.permanently, redirected_transport.base))
734
return redirected_transport
737
transport, format = _mod_transport.do_catching_redirections(
738
find_format, transport, redirected)
739
except errors.TooManyRedirections:
740
raise errors.NotBranchError(base)
742
format.check_support_status(_unsupported)
743
return format.open(transport, _found=True)
746
def open_containing(klass, url, possible_transports=None):
747
"""Open an existing branch which contains url.
749
:param url: url to search from.
751
See open_containing_from_transport for more detail.
753
transport = _mod_transport.get_transport(url, possible_transports)
754
return klass.open_containing_from_transport(transport)
757
def open_containing_from_transport(klass, a_transport):
758
"""Open an existing branch which contains a_transport.base.
760
This probes for a branch at a_transport, and searches upwards from there.
762
Basically we keep looking up until we find the control directory or
763
run into the root. If there isn't one, raises NotBranchError.
764
If there is one and it is either an unrecognised format or an unsupported
765
format, UnknownFormatError or UnsupportedFormatError are raised.
766
If there is one, it is returned, along with the unused portion of url.
768
:return: The ControlDir that contains the path, and a Unicode path
769
for the rest of the URL.
771
# this gets the normalised url back. I.e. '.' -> the full path.
772
url = a_transport.base
775
result = klass.open_from_transport(a_transport)
776
return result, urlutils.unescape(a_transport.relpath(url))
777
except errors.NotBranchError:
779
except errors.PermissionDenied:
782
new_t = a_transport.clone('..')
783
except urlutils.InvalidURLJoin:
784
# reached the root, whatever that may be
785
raise errors.NotBranchError(path=url)
786
if new_t.base == a_transport.base:
787
# reached the root, whatever that may be
788
raise errors.NotBranchError(path=url)
792
def open_tree_or_branch(klass, location):
793
"""Return the branch and working tree at a location.
795
If there is no tree at the location, tree will be None.
796
If there is no branch at the location, an exception will be
798
:return: (tree, branch)
800
controldir = klass.open(location)
801
return controldir._get_tree_branch()
804
def open_containing_tree_or_branch(klass, location,
805
possible_transports=None):
806
"""Return the branch and working tree contained by a location.
808
Returns (tree, branch, relpath).
809
If there is no tree at containing the location, tree will be None.
810
If there is no branch containing the location, an exception will be
812
relpath is the portion of the path that is contained by the branch.
814
controldir, relpath = klass.open_containing(location,
815
possible_transports=possible_transports)
816
tree, branch = controldir._get_tree_branch()
817
return tree, branch, relpath
820
def open_containing_tree_branch_or_repository(klass, location):
821
"""Return the working tree, branch and repo contained by a location.
823
Returns (tree, branch, repository, relpath).
824
If there is no tree containing the location, tree will be None.
825
If there is no branch containing the location, branch will be None.
826
If there is no repository containing the location, repository will be
828
relpath is the portion of the path that is contained by the innermost
831
If no tree, branch or repository is found, a NotBranchError is raised.
833
controldir, relpath = klass.open_containing(location)
835
tree, branch = controldir._get_tree_branch()
836
except errors.NotBranchError:
838
repo = controldir.find_repository()
839
return None, None, repo, relpath
840
except (errors.NoRepositoryPresent):
841
raise errors.NotBranchError(location)
842
return tree, branch, branch.repository, relpath
845
def create(klass, base, format=None, possible_transports=None):
846
"""Create a new ControlDir at the url 'base'.
848
:param format: If supplied, the format of branch to create. If not
849
supplied, the default is used.
850
:param possible_transports: If supplied, a list of transports that
851
can be reused to share a remote connection.
853
if klass is not ControlDir:
854
raise AssertionError("ControlDir.create always creates the"
855
"default format, not one of %r" % klass)
856
t = _mod_transport.get_transport(base, possible_transports)
859
format = ControlDirFormat.get_default_format()
860
return format.initialize_on_transport(t)
863
class ControlDirHooks(hooks.Hooks):
864
"""Hooks for ControlDir operations."""
867
"""Create the default hooks."""
868
hooks.Hooks.__init__(self, "breezy.controldir", "ControlDir.hooks")
869
self.add_hook('pre_open',
870
"Invoked before attempting to open a ControlDir with the transport "
871
"that the open will use.", (1, 14))
872
self.add_hook('post_repo_init',
873
"Invoked after a repository has been initialized. "
874
"post_repo_init is called with a "
875
"breezy.controldir.RepoInitHookParams.",
879
# install the default hooks
880
ControlDir.hooks = ControlDirHooks()
883
class ControlComponentFormat(object):
884
"""A component that can live inside of a control directory."""
886
upgrade_recommended = False
888
def get_format_description(self):
889
"""Return the short description for this format."""
890
raise NotImplementedError(self.get_format_description)
892
def is_supported(self):
893
"""Is this format supported?
895
Supported formats must be initializable and openable.
896
Unsupported formats may not support initialization or committing or
897
some other features depending on the reason for not being supported.
901
def check_support_status(self, allow_unsupported, recommend_upgrade=True,
903
"""Give an error or warning on old formats.
905
:param allow_unsupported: If true, allow opening
906
formats that are strongly deprecated, and which may
907
have limited functionality.
909
:param recommend_upgrade: If true (default), warn
910
the user through the ui object that they may wish
911
to upgrade the object.
913
if not allow_unsupported and not self.is_supported():
914
# see open_downlevel to open legacy branches.
915
raise errors.UnsupportedFormatError(format=self)
916
if recommend_upgrade and self.upgrade_recommended:
917
ui.ui_factory.recommend_upgrade(
918
self.get_format_description(), basedir)
921
def get_format_string(cls):
922
raise NotImplementedError(cls.get_format_string)
925
class ControlComponentFormatRegistry(registry.FormatRegistry):
926
"""A registry for control components (branch, workingtree, repository)."""
928
def __init__(self, other_registry=None):
929
super(ControlComponentFormatRegistry, self).__init__(other_registry)
930
self._extra_formats = []
932
def register(self, format):
933
"""Register a new format."""
934
super(ControlComponentFormatRegistry, self).register(
935
format.get_format_string(), format)
937
def remove(self, format):
938
"""Remove a registered format."""
939
super(ControlComponentFormatRegistry, self).remove(
940
format.get_format_string())
942
def register_extra(self, format):
943
"""Register a format that can not be used in a metadir.
945
This is mainly useful to allow custom repository formats, such as older
946
Bazaar formats and foreign formats, to be tested.
948
self._extra_formats.append(registry._ObjectGetter(format))
950
def remove_extra(self, format):
951
"""Remove an extra format.
953
self._extra_formats.remove(registry._ObjectGetter(format))
955
def register_extra_lazy(self, module_name, member_name):
956
"""Register a format lazily.
958
self._extra_formats.append(
959
registry._LazyObjectGetter(module_name, member_name))
961
def _get_extra(self):
962
"""Return getters for extra formats, not usable in meta directories."""
963
return [getter.get_obj for getter in self._extra_formats]
965
def _get_all_lazy(self):
966
"""Return getters for all formats, even those not usable in metadirs."""
967
result = [self._dict[name].get_obj for name in self.keys()]
968
result.extend(self._get_extra())
972
"""Return all formats, even those not usable in metadirs."""
974
for getter in self._get_all_lazy():
981
def _get_all_modules(self):
982
"""Return a set of the modules providing objects."""
984
for name in self.keys():
985
modules.add(self._get_module(name))
986
for getter in self._extra_formats:
987
modules.add(getter.get_module())
991
class Converter(object):
992
"""Converts a disk format object from one format to another."""
994
def convert(self, to_convert, pb):
995
"""Perform the conversion of to_convert, giving feedback via pb.
997
:param to_convert: The disk object to convert.
998
:param pb: a progress bar to use for progress information.
1001
def step(self, message):
1002
"""Update the pb by a step."""
1004
self.pb.update(message, self.count, self.total)
1007
class ControlDirFormat(object):
1008
"""An encapsulation of the initialization and open routines for a format.
1010
Formats provide three things:
1011
* An initialization routine,
1015
Formats are placed in a dict by their format string for reference
1016
during controldir opening. These should be subclasses of ControlDirFormat
1019
Once a format is deprecated, just deprecate the initialize and open
1020
methods on the format class. Do not deprecate the object, as the
1021
object will be created every system load.
1023
:cvar colocated_branches: Whether this formats supports colocated branches.
1024
:cvar supports_workingtrees: This control directory can co-exist with a
1028
_default_format = None
1029
"""The default format used for new control directories."""
1031
_server_probers = []
1032
"""The registered server format probers, e.g. RemoteBzrProber.
1034
This is a list of Prober-derived classes.
1038
"""The registered format probers, e.g. BzrProber.
1040
This is a list of Prober-derived classes.
1043
colocated_branches = False
1044
"""Whether co-located branches are supported for this control dir format.
1047
supports_workingtrees = True
1048
"""Whether working trees can exist in control directories of this format.
1051
fixed_components = False
1052
"""Whether components can not change format independent of the control dir.
1055
upgrade_recommended = False
1056
"""Whether an upgrade from this format is recommended."""
1058
def get_format_description(self):
1059
"""Return the short description for this format."""
1060
raise NotImplementedError(self.get_format_description)
1062
def get_converter(self, format=None):
1063
"""Return the converter to use to convert controldirs needing converts.
1065
This returns a breezy.controldir.Converter object.
1067
This should return the best upgrader to step this format towards the
1068
current default format. In the case of plugins we can/should provide
1069
some means for them to extend the range of returnable converters.
1071
:param format: Optional format to override the default format of the
1074
raise NotImplementedError(self.get_converter)
1076
def is_supported(self):
1077
"""Is this format supported?
1079
Supported formats must be openable.
1080
Unsupported formats may not support initialization or committing or
1081
some other features depending on the reason for not being supported.
1085
def is_initializable(self):
1086
"""Whether new control directories of this format can be initialized.
1088
return self.is_supported()
1090
def check_support_status(self, allow_unsupported, recommend_upgrade=True,
1092
"""Give an error or warning on old formats.
1094
:param allow_unsupported: If true, allow opening
1095
formats that are strongly deprecated, and which may
1096
have limited functionality.
1098
:param recommend_upgrade: If true (default), warn
1099
the user through the ui object that they may wish
1100
to upgrade the object.
1102
if not allow_unsupported and not self.is_supported():
1103
# see open_downlevel to open legacy branches.
1104
raise errors.UnsupportedFormatError(format=self)
1105
if recommend_upgrade and self.upgrade_recommended:
1106
ui.ui_factory.recommend_upgrade(
1107
self.get_format_description(), basedir)
1109
def same_model(self, target_format):
1110
return (self.repository_format.rich_root_data ==
1111
target_format.rich_root_data)
1114
def register_prober(klass, prober):
1115
"""Register a prober that can look for a control dir.
1118
klass._probers.append(prober)
1121
def unregister_prober(klass, prober):
1122
"""Unregister a prober.
1125
klass._probers.remove(prober)
1128
def register_server_prober(klass, prober):
1129
"""Register a control format prober for client-server environments.
1131
These probers will be used before ones registered with
1132
register_prober. This gives implementations that decide to the
1133
chance to grab it before anything looks at the contents of the format
1136
klass._server_probers.append(prober)
1140
return self.get_format_description().rstrip()
1143
def all_probers(klass):
1144
return klass._server_probers + klass._probers
1147
def known_formats(klass):
1148
"""Return all the known formats.
1151
for prober_kls in klass.all_probers():
1152
result.extend(prober_kls.known_formats())
1156
def find_format(klass, transport, probers=None):
1157
"""Return the format present at transport."""
1159
probers = klass.all_probers()
1160
for prober_kls in probers:
1161
prober = prober_kls()
1163
return prober.probe_transport(transport)
1164
except errors.NotBranchError:
1165
# this format does not find a control dir here.
1167
raise errors.NotBranchError(path=transport.base)
1169
def initialize(self, url, possible_transports=None):
1170
"""Create a control dir at this url and return an opened copy.
1172
While not deprecated, this method is very specific and its use will
1173
lead to many round trips to setup a working environment. See
1174
initialize_on_transport_ex for a [nearly] all-in-one method.
1176
Subclasses should typically override initialize_on_transport
1177
instead of this method.
1179
return self.initialize_on_transport(
1180
_mod_transport.get_transport(url, possible_transports))
1182
def initialize_on_transport(self, transport):
1183
"""Initialize a new controldir in the base directory of a Transport."""
1184
raise NotImplementedError(self.initialize_on_transport)
1186
def initialize_on_transport_ex(self, transport, use_existing_dir=False,
1187
create_prefix=False, force_new_repo=False, stacked_on=None,
1188
stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
1189
shared_repo=False, vfs_only=False):
1190
"""Create this format on transport.
1192
The directory to initialize will be created.
1194
:param force_new_repo: Do not use a shared repository for the target,
1195
even if one is available.
1196
:param create_prefix: Create any missing directories leading up to
1198
:param use_existing_dir: Use an existing directory if one exists.
1199
:param stacked_on: A url to stack any created branch on, None to follow
1200
any target stacking policy.
1201
:param stack_on_pwd: If stack_on is relative, the location it is
1203
:param repo_format_name: If non-None, a repository will be
1204
made-or-found. Should none be found, or if force_new_repo is True
1205
the repo_format_name is used to select the format of repository to
1207
:param make_working_trees: Control the setting of make_working_trees
1208
for a new shared repository when one is made. None to use whatever
1209
default the format has.
1210
:param shared_repo: Control whether made repositories are shared or
1212
:param vfs_only: If True do not attempt to use a smart server
1213
:return: repo, controldir, require_stacking, repository_policy. repo is
1214
None if none was created or found, controldir is always valid.
1215
require_stacking is the result of examining the stacked_on
1216
parameter and any stacking policy found for the target.
1218
raise NotImplementedError(self.initialize_on_transport_ex)
1220
def network_name(self):
1221
"""A simple byte string uniquely identifying this format for RPC calls.
1223
Bzr control formats use this disk format string to identify the format
1224
over the wire. Its possible that other control formats have more
1225
complex detection requirements, so we permit them to use any unique and
1226
immutable string they desire.
1228
raise NotImplementedError(self.network_name)
1230
def open(self, transport, _found=False):
1231
"""Return an instance of this format for the dir transport points at.
1233
raise NotImplementedError(self.open)
1236
def _set_default_format(klass, format):
1237
"""Set default format (for testing behavior of defaults only)"""
1238
klass._default_format = format
1241
def get_default_format(klass):
1242
"""Return the current default format."""
1243
return klass._default_format
1245
def supports_transport(self, transport):
1246
"""Check if this format can be opened over a particular transport.
1248
raise NotImplementedError(self.supports_transport)
1251
def is_control_filename(klass, filename):
1252
"""True if filename is the name of a path which is reserved for
1255
:param filename: A filename within the root transport of this
1258
This is true IF and ONLY IF the filename is part of the namespace reserved
1259
for bzr control dirs. Currently this is the '.bzr' directory in the root
1260
of the root_transport. it is expected that plugins will need to extend
1261
this in the future - for instance to make bzr talk with svn working
1264
raise NotImplementedError(self.is_control_filename)
1267
class Prober(object):
1268
"""Abstract class that can be used to detect a particular kind of
1271
At the moment this just contains a single method to probe a particular
1272
transport, but it may be extended in the future to e.g. avoid
1273
multiple levels of probing for Subversion repositories.
1275
See BzrProber and RemoteBzrProber in breezy.bzrdir for the
1276
probers that detect .bzr/ directories and Bazaar smart servers,
1279
Probers should be registered using the register_server_prober or
1280
register_prober methods on ControlDirFormat.
1283
def probe_transport(self, transport):
1284
"""Return the controldir style format present in a directory.
1286
:raise UnknownFormatError: If a control dir was found but is
1287
in an unknown format.
1288
:raise NotBranchError: If no control directory was found.
1289
:return: A ControlDirFormat instance.
1291
raise NotImplementedError(self.probe_transport)
1294
def known_formats(klass):
1295
"""Return the control dir formats known by this prober.
1297
Multiple probers can return the same formats, so this should
1300
:return: A set of known formats.
1302
raise NotImplementedError(klass.known_formats)
1305
class ControlDirFormatInfo(object):
1307
def __init__(self, native, deprecated, hidden, experimental):
1308
self.deprecated = deprecated
1309
self.native = native
1310
self.hidden = hidden
1311
self.experimental = experimental
1314
class ControlDirFormatRegistry(registry.Registry):
1315
"""Registry of user-selectable ControlDir subformats.
1317
Differs from ControlDirFormat._formats in that it provides sub-formats,
1318
e.g. BzrDirMeta1 with weave repository. Also, it's more user-oriented.
1322
"""Create a ControlDirFormatRegistry."""
1323
self._registration_order = list()
1324
super(ControlDirFormatRegistry, self).__init__()
1326
def register(self, key, factory, help, native=True, deprecated=False,
1327
hidden=False, experimental=False):
1328
"""Register a ControlDirFormat factory.
1330
The factory must be a callable that takes one parameter: the key.
1331
It must produce an instance of the ControlDirFormat when called.
1333
This function mainly exists to prevent the info object from being
1336
registry.Registry.register(self, key, factory, help,
1337
ControlDirFormatInfo(native, deprecated, hidden, experimental))
1338
self._registration_order.append(key)
1340
def register_alias(self, key, target, hidden=False):
1341
"""Register a format alias.
1343
:param key: Alias name
1344
:param target: Target format
1345
:param hidden: Whether the alias is hidden
1347
info = self.get_info(target)
1348
registry.Registry.register_alias(self, key, target,
1349
ControlDirFormatInfo(
1350
native=info.native, deprecated=info.deprecated,
1351
hidden=hidden, experimental=info.experimental))
1353
def register_lazy(self, key, module_name, member_name, help, native=True,
1354
deprecated=False, hidden=False, experimental=False):
1355
registry.Registry.register_lazy(self, key, module_name, member_name,
1356
help, ControlDirFormatInfo(native, deprecated, hidden, experimental))
1357
self._registration_order.append(key)
1359
def set_default(self, key):
1360
"""Set the 'default' key to be a clone of the supplied key.
1362
This method must be called once and only once.
1364
self.register_alias('default', key)
1366
def set_default_repository(self, key):
1367
"""Set the FormatRegistry default and Repository default.
1369
This is a transitional method while Repository.set_default_format
1372
if 'default' in self:
1373
self.remove('default')
1374
self.set_default(key)
1375
format = self.get('default')()
1377
def make_controldir(self, key):
1378
return self.get(key)()
1380
def help_topic(self, topic):
1382
default_realkey = None
1383
default_help = self.get_help('default')
1385
for key in self._registration_order:
1386
if key == 'default':
1388
help = self.get_help(key)
1389
if help == default_help:
1390
default_realkey = key
1392
help_pairs.append((key, help))
1394
def wrapped(key, help, info):
1396
help = '(native) ' + help
1397
return ':%s:\n%s\n\n' % (key,
1398
textwrap.fill(help, initial_indent=' ',
1399
subsequent_indent=' ',
1400
break_long_words=False))
1401
if default_realkey is not None:
1402
output += wrapped(default_realkey, '(default) %s' % default_help,
1403
self.get_info('default'))
1404
deprecated_pairs = []
1405
experimental_pairs = []
1406
for key, help in help_pairs:
1407
info = self.get_info(key)
1410
elif info.deprecated:
1411
deprecated_pairs.append((key, help))
1412
elif info.experimental:
1413
experimental_pairs.append((key, help))
1415
output += wrapped(key, help, info)
1416
output += "\nSee :doc:`formats-help` for more about storage formats."
1418
if len(experimental_pairs) > 0:
1419
other_output += "Experimental formats are shown below.\n\n"
1420
for key, help in experimental_pairs:
1421
info = self.get_info(key)
1422
other_output += wrapped(key, help, info)
1425
"No experimental formats are available.\n\n"
1426
if len(deprecated_pairs) > 0:
1427
other_output += "\nDeprecated formats are shown below.\n\n"
1428
for key, help in deprecated_pairs:
1429
info = self.get_info(key)
1430
other_output += wrapped(key, help, info)
1433
"\nNo deprecated formats are available.\n\n"
1435
"\nSee :doc:`formats-help` for more about storage formats."
1437
if topic == 'other-formats':
1443
class RepoInitHookParams(object):
1444
"""Object holding parameters passed to `*_repo_init` hooks.
1446
There are 4 fields that hooks may wish to access:
1448
:ivar repository: Repository created
1449
:ivar format: Repository format
1450
:ivar bzrdir: The controldir for the repository
1451
:ivar shared: The repository is shared
1454
def __init__(self, repository, format, controldir, shared):
1455
"""Create a group of RepoInitHook parameters.
1457
:param repository: Repository created
1458
:param format: Repository format
1459
:param controldir: The controldir for the repository
1460
:param shared: The repository is shared
1462
self.repository = repository
1463
self.format = format
1464
self.controldir = controldir
1465
self.shared = shared
1467
def __eq__(self, other):
1468
return self.__dict__ == other.__dict__
1472
return "<%s for %s>" % (self.__class__.__name__,
1475
return "<%s for %s>" % (self.__class__.__name__,
1479
def is_control_filename(filename):
1480
"""Check if filename is used for control directories."""
1481
# TODO(jelmer): Instead, have a function that returns all control
1483
for key, format in format_registry.items():
1484
if format().is_control_filename(filename):
1490
class RepositoryAcquisitionPolicy(object):
1491
"""Abstract base class for repository acquisition policies.
1493
A repository acquisition policy decides how a ControlDir acquires a repository
1494
for a branch that is being created. The most basic policy decision is
1495
whether to create a new repository or use an existing one.
1498
def __init__(self, stack_on, stack_on_pwd, require_stacking):
1501
:param stack_on: A location to stack on
1502
:param stack_on_pwd: If stack_on is relative, the location it is
1504
:param require_stacking: If True, it is a failure to not stack.
1506
self._stack_on = stack_on
1507
self._stack_on_pwd = stack_on_pwd
1508
self._require_stacking = require_stacking
1510
def configure_branch(self, branch):
1511
"""Apply any configuration data from this policy to the branch.
1513
Default implementation sets repository stacking.
1515
if self._stack_on is None:
1517
if self._stack_on_pwd is None:
1518
stack_on = self._stack_on
1521
stack_on = urlutils.rebase_url(self._stack_on,
1524
except urlutils.InvalidRebaseURLs:
1525
stack_on = self._get_full_stack_on()
1527
branch.set_stacked_on_url(stack_on)
1528
except (_mod_branch.UnstackableBranchFormat,
1529
errors.UnstackableRepositoryFormat):
1530
if self._require_stacking:
1533
def requires_stacking(self):
1534
"""Return True if this policy requires stacking."""
1535
return self._stack_on is not None and self._require_stacking
1537
def _get_full_stack_on(self):
1538
"""Get a fully-qualified URL for the stack_on location."""
1539
if self._stack_on is None:
1541
if self._stack_on_pwd is None:
1542
return self._stack_on
1544
return urlutils.join(self._stack_on_pwd, self._stack_on)
1546
def _add_fallback(self, repository, possible_transports=None):
1547
"""Add a fallback to the supplied repository, if stacking is set."""
1548
stack_on = self._get_full_stack_on()
1549
if stack_on is None:
1552
stacked_dir = ControlDir.open(
1553
stack_on, possible_transports=possible_transports)
1554
except errors.JailBreak:
1555
# We keep the stacking details, but we are in the server code so
1556
# actually stacking is not needed.
1559
stacked_repo = stacked_dir.open_branch().repository
1560
except errors.NotBranchError:
1561
stacked_repo = stacked_dir.open_repository()
1563
repository.add_fallback_repository(stacked_repo)
1564
except errors.UnstackableRepositoryFormat:
1565
if self._require_stacking:
1568
self._require_stacking = True
1570
def acquire_repository(self, make_working_trees=None, shared=False,
1571
possible_transports=None):
1572
"""Acquire a repository for this controlrdir.
1574
Implementations may create a new repository or use a pre-exising
1577
:param make_working_trees: If creating a repository, set
1578
make_working_trees to this value (if non-None)
1579
:param shared: If creating a repository, make it shared if True
1580
:return: A repository, is_new_flag (True if the repository was
1583
raise NotImplementedError(
1584
RepositoryAcquisitionPolicy.acquire_repository)
1587
# Please register new formats after old formats so that formats
1588
# appear in chronological order and format descriptions can build
1590
format_registry = ControlDirFormatRegistry()
1592
network_format_registry = registry.FormatRegistry()
1593
"""Registry of formats indexed by their network name.
1595
The network name for a ControlDirFormat is an identifier that can be used when
1596
referring to formats with smart server operations. See
1597
ControlDirFormat.network_name() for more detail.