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 .lazy_import import lazy_import
26
lazy_import(globals(), """
30
branch as _mod_branch,
32
revision as _mod_revision,
33
transport as _mod_transport,
38
from breezy.transport import local
39
from breezy.push import (
43
from breezy.i18n import gettext
52
class MustHaveWorkingTree(errors.BzrError):
54
_fmt = "Branching '%(url)s'(%(format)s) must create a working tree."
56
def __init__(self, format, url):
57
errors.BzrError.__init__(self, format=format, url=url)
60
class BranchReferenceLoop(errors.BzrError):
62
_fmt = "Can not create branch reference that points at branch itself."
64
def __init__(self, branch):
65
errors.BzrError.__init__(self, branch=branch)
68
class ControlComponent(object):
69
"""Abstract base class for control directory components.
71
This provides interfaces that are common across controldirs,
72
repositories, branches, and workingtree control directories.
74
They all expose two urls and transports: the *user* URL is the
75
one that stops above the control directory (eg .bzr) and that
76
should normally be used in messages, and the *control* URL is
77
under that in eg .bzr/checkout and is used to read the control
80
This can be used as a mixin and is intended to fit with
85
def control_transport(self):
86
raise NotImplementedError
89
def control_url(self):
90
return self.control_transport.base
93
def user_transport(self):
94
raise NotImplementedError
98
return self.user_transport.base
101
class ControlDir(ControlComponent):
102
"""A control directory.
104
While this represents a generic control directory, there are a few
105
features that are present in this interface that are currently only
106
supported by one of its implementations, BzrDir.
108
These features (bound branches, stacked branches) are currently only
109
supported by Bazaar, but could be supported by other version control
110
systems as well. Implementations are required to raise the appropriate
111
exceptions when an operation is requested that is not supported.
113
This also makes life easier for API users who can rely on the
114
implementation always allowing a particular feature to be requested but
115
raising an exception when it is not supported, rather than requiring the
116
API users to check for magic attributes to see what features are supported.
119
def can_convert_format(self):
120
"""Return true if this controldir is one whose format we can convert
124
def list_branches(self):
125
"""Return a sequence of all branches local to this control directory.
128
return list(self.get_branches().values())
130
def get_branches(self):
131
"""Get all branches in this control directory, as a dictionary.
133
:return: Dictionary mapping branch names to instances.
136
return {"": self.open_branch()}
137
except (errors.NotBranchError, errors.NoRepositoryPresent):
140
def is_control_filename(self, filename):
141
"""True if filename is the name of a path which is reserved for
144
:param filename: A filename within the root transport of this
147
This is true IF and ONLY IF the filename is part of the namespace reserved
148
for bzr control dirs. Currently this is the '.bzr' directory in the root
149
of the root_transport. it is expected that plugins will need to extend
150
this in the future - for instance to make bzr talk with svn working
153
return self._format.is_control_filename(filename)
155
def needs_format_conversion(self, format=None):
156
"""Return true if this controldir needs convert_format run on it.
158
For instance, if the repository format is out of date but the
159
branch and working tree are not, this should return True.
161
:param format: Optional parameter indicating a specific desired
162
format we plan to arrive at.
164
raise NotImplementedError(self.needs_format_conversion)
166
def create_repository(self, shared=False):
167
"""Create a new repository in this control directory.
169
:param shared: If a shared repository should be created
170
:return: The newly created repository
172
raise NotImplementedError(self.create_repository)
174
def destroy_repository(self):
175
"""Destroy the repository in this ControlDir."""
176
raise NotImplementedError(self.destroy_repository)
178
def create_branch(self, name=None, repository=None,
179
append_revisions_only=None):
180
"""Create a branch in this ControlDir.
182
:param name: Name of the colocated branch to create, None for
183
the user selected branch or "" for the active branch.
184
:param append_revisions_only: Whether this branch should only allow
185
appending new revisions to its history.
187
The controldirs format will control what branch format is created.
188
For more control see BranchFormatXX.create(a_controldir).
190
raise NotImplementedError(self.create_branch)
192
def destroy_branch(self, name=None):
193
"""Destroy a branch in this ControlDir.
195
:param name: Name of the branch to destroy, None for the
196
user selected branch or "" for the active branch.
197
:raise NotBranchError: When the branch does not exist
199
raise NotImplementedError(self.destroy_branch)
201
def create_workingtree(self, revision_id=None, from_branch=None,
202
accelerator_tree=None, hardlink=False):
203
"""Create a working tree at this ControlDir.
205
:param revision_id: create it as of this revision id.
206
:param from_branch: override controldir branch
207
(for lightweight checkouts)
208
:param accelerator_tree: A tree which can be used for retrieving file
209
contents more quickly than the revision tree, i.e. a workingtree.
210
The revision tree will be used for cases where accelerator_tree's
211
content is different.
213
raise NotImplementedError(self.create_workingtree)
215
def destroy_workingtree(self):
216
"""Destroy the working tree at this ControlDir.
218
Formats that do not support this may raise UnsupportedOperation.
220
raise NotImplementedError(self.destroy_workingtree)
222
def destroy_workingtree_metadata(self):
223
"""Destroy the control files for the working tree at this ControlDir.
225
The contents of working tree files are not affected.
226
Formats that do not support this may raise UnsupportedOperation.
228
raise NotImplementedError(self.destroy_workingtree_metadata)
230
def find_branch_format(self, name=None):
231
"""Find the branch 'format' for this controldir.
233
This might be a synthetic object for e.g. RemoteBranch and SVN.
235
raise NotImplementedError(self.find_branch_format)
237
def get_branch_reference(self, name=None):
238
"""Return the referenced URL for the branch in this controldir.
240
:param name: Optional colocated branch name
241
:raises NotBranchError: If there is no Branch.
242
:raises NoColocatedBranchSupport: If a branch name was specified
243
but colocated branches are not supported.
244
:return: The URL the branch in this controldir references if it is a
245
reference branch, or None for regular branches.
248
raise errors.NoColocatedBranchSupport(self)
251
def set_branch_reference(self, target_branch, name=None):
252
"""Set the referenced URL for the branch in this controldir.
254
:param name: Optional colocated branch name
255
:param target_branch: Branch to reference
256
:raises NoColocatedBranchSupport: If a branch name was specified
257
but colocated branches are not supported.
258
:return: The referencing branch
260
raise NotImplementedError(self.set_branch_reference)
262
def open_branch(self, name=None, unsupported=False,
263
ignore_fallbacks=False, possible_transports=None):
264
"""Open the branch object at this ControlDir if one is present.
266
:param unsupported: if True, then no longer supported branch formats can
268
:param ignore_fallbacks: Whether to open fallback repositories
269
:param possible_transports: Transports to use for opening e.g.
270
fallback repositories.
272
raise NotImplementedError(self.open_branch)
274
def open_repository(self, _unsupported=False):
275
"""Open the repository object at this ControlDir if one is present.
277
This will not follow the Branch object pointer - it's strictly a direct
278
open facility. Most client code should use open_branch().repository to
281
:param _unsupported: a private parameter, not part of the api.
283
raise NotImplementedError(self.open_repository)
285
def find_repository(self):
286
"""Find the repository that should be used.
288
This does not require a branch as we use it to find the repo for
289
new branches as well as to hook existing branches up to their
292
raise NotImplementedError(self.find_repository)
294
def open_workingtree(self, unsupported=False,
295
recommend_upgrade=True, from_branch=None):
296
"""Open the workingtree object at this ControlDir if one is present.
298
:param recommend_upgrade: Optional keyword parameter, when True (the
299
default), emit through the ui module a recommendation that the user
300
upgrade the working tree when the workingtree being opened is old
301
(but still fully supported).
302
:param from_branch: override controldir branch (for lightweight
305
raise NotImplementedError(self.open_workingtree)
307
def has_branch(self, name=None):
308
"""Tell if this controldir contains a branch.
310
Note: if you're going to open the branch, you should just go ahead
311
and try, and not ask permission first. (This method just opens the
312
branch and discards it, and that's somewhat expensive.)
315
self.open_branch(name, ignore_fallbacks=True)
317
except errors.NotBranchError:
320
def _get_selected_branch(self):
321
"""Return the name of the branch selected by the user.
323
:return: Name of the branch selected by the user, or "".
325
branch = self.root_transport.get_segment_parameters().get("branch")
328
return urlutils.unescape(branch)
330
def has_workingtree(self):
331
"""Tell if this controldir contains a working tree.
333
This will still raise an exception if the controldir has a workingtree
334
that is remote & inaccessible.
336
Note: if you're going to open the working tree, you should just go ahead
337
and try, and not ask permission first. (This method just opens the
338
workingtree and discards it, and that's somewhat expensive.)
341
self.open_workingtree(recommend_upgrade=False)
343
except errors.NoWorkingTree:
346
def cloning_metadir(self, require_stacking=False):
347
"""Produce a metadir suitable for cloning or sprouting with.
349
These operations may produce workingtrees (yes, even though they're
350
"cloning" something that doesn't have a tree), so a viable workingtree
351
format must be selected.
353
:require_stacking: If True, non-stackable formats will be upgraded
354
to similar stackable formats.
355
:returns: a ControlDirFormat with all component formats either set
356
appropriately or set to None if that component should not be
359
raise NotImplementedError(self.cloning_metadir)
361
def checkout_metadir(self):
362
"""Produce a metadir suitable for checkouts of this controldir.
364
:returns: A ControlDirFormat with all component formats
365
either set appropriately or set to None if that component
366
should not be created.
368
return self.cloning_metadir()
370
def sprout(self, url, revision_id=None, force_new_repo=False,
371
recurse='down', possible_transports=None,
372
accelerator_tree=None, hardlink=False, stacked=False,
373
source_branch=None, create_tree_if_local=True,
375
"""Create a copy of this controldir prepared for use as a new line of
378
If url's last component does not exist, it will be created.
380
Attributes related to the identity of the source branch like
381
branch nickname will be cleaned, a working tree is created
382
whether one existed before or not; and a local branch is always
385
:param revision_id: if revision_id is not None, then the clone
386
operation may tune itself to download less data.
387
:param accelerator_tree: A tree which can be used for retrieving file
388
contents more quickly than the revision tree, i.e. a workingtree.
389
The revision tree will be used for cases where accelerator_tree's
390
content is different.
391
:param hardlink: If true, hard-link files from accelerator_tree,
393
:param stacked: If true, create a stacked branch referring to the
394
location of this control directory.
395
:param create_tree_if_local: If true, a working-tree will be created
396
when working locally.
398
raise NotImplementedError(self.sprout)
400
def push_branch(self, source, revision_id=None, overwrite=False,
401
remember=False, create_prefix=False, lossy=False,
403
"""Push the source branch into this ControlDir."""
405
# If we can open a branch, use its direct repository, otherwise see
406
# if there is a repository without a branch.
408
br_to = self.open_branch()
409
except errors.NotBranchError:
410
# Didn't find a branch, can we find a repository?
411
repository_to = self.find_repository()
413
# Found a branch, so we must have found a repository
414
repository_to = br_to.repository
416
push_result = PushResult()
417
push_result.source_branch = source
419
# We have a repository but no branch, copy the revisions, and then
421
if revision_id is None:
422
# No revision supplied by the user, default to the branch
424
revision_id = source.last_revision()
425
repository_to.fetch(source.repository, revision_id=revision_id)
426
br_to = source.sprout(
427
self, revision_id=revision_id, lossy=lossy,
428
tag_selector=tag_selector)
429
if source.get_push_location() is None or remember:
430
# FIXME: Should be done only if we succeed ? -- vila 2012-01-18
431
source.set_push_location(br_to.base)
432
push_result.stacked_on = None
433
push_result.branch_push_result = None
434
push_result.old_revno = None
435
push_result.old_revid = _mod_revision.NULL_REVISION
436
push_result.target_branch = br_to
437
push_result.master_branch = None
438
push_result.workingtree_updated = False
440
# We have successfully opened the branch, remember if necessary:
441
if source.get_push_location() is None or remember:
442
# FIXME: Should be done only if we succeed ? -- vila 2012-01-18
443
source.set_push_location(br_to.base)
445
tree_to = self.open_workingtree()
446
except errors.NotLocalUrl:
447
push_result.branch_push_result = source.push(
448
br_to, overwrite, stop_revision=revision_id, lossy=lossy,
449
tag_selector=tag_selector)
450
push_result.workingtree_updated = False
451
except errors.NoWorkingTree:
452
push_result.branch_push_result = source.push(
453
br_to, overwrite, stop_revision=revision_id, lossy=lossy,
454
tag_selector=tag_selector)
455
push_result.workingtree_updated = None # Not applicable
457
with tree_to.lock_write():
458
push_result.branch_push_result = source.push(
459
tree_to.branch, overwrite, stop_revision=revision_id,
460
lossy=lossy, tag_selector=tag_selector)
462
push_result.workingtree_updated = True
463
push_result.old_revno = push_result.branch_push_result.old_revno
464
push_result.old_revid = push_result.branch_push_result.old_revid
465
push_result.target_branch = \
466
push_result.branch_push_result.target_branch
469
def _get_tree_branch(self, name=None):
470
"""Return the branch and tree, if any, for this controldir.
472
:param name: Name of colocated branch to open.
474
Return None for tree if not present or inaccessible.
475
Raise NotBranchError if no branch is present.
476
:return: (tree, branch)
479
tree = self.open_workingtree()
480
except (errors.NoWorkingTree, errors.NotLocalUrl):
482
branch = self.open_branch(name=name)
485
branch = self.open_branch(name=name)
490
def get_config(self):
491
"""Get configuration for this ControlDir."""
492
raise NotImplementedError(self.get_config)
494
def check_conversion_target(self, target_format):
495
"""Check that a controldir as a whole can be converted to a new format."""
496
raise NotImplementedError(self.check_conversion_target)
498
def clone(self, url, revision_id=None, force_new_repo=False,
499
preserve_stacking=False, tag_selector=None):
500
"""Clone this controldir and its contents to url verbatim.
502
:param url: The url create the clone at. If url's last component does
503
not exist, it will be created.
504
:param revision_id: The tip revision-id to use for any branch or
505
working tree. If not None, then the clone operation may tune
506
itself to download less data.
507
:param force_new_repo: Do not use a shared repository for the target
508
even if one is available.
509
:param preserve_stacking: When cloning a stacked branch, stack the
510
new branch on top of the other branch's stacked-on branch.
512
return self.clone_on_transport(_mod_transport.get_transport(url),
513
revision_id=revision_id,
514
force_new_repo=force_new_repo,
515
preserve_stacking=preserve_stacking,
516
tag_selector=tag_selector)
518
def clone_on_transport(self, transport, revision_id=None,
519
force_new_repo=False, preserve_stacking=False, stacked_on=None,
520
create_prefix=False, use_existing_dir=True, no_tree=False,
522
"""Clone this controldir and its contents to transport verbatim.
524
:param transport: The transport for the location to produce the clone
525
at. If the target directory does not exist, it will be created.
526
:param revision_id: The tip revision-id to use for any branch or
527
working tree. If not None, then the clone operation may tune
528
itself to download less data.
529
:param force_new_repo: Do not use a shared repository for the target,
530
even if one is available.
531
:param preserve_stacking: When cloning a stacked branch, stack the
532
new branch on top of the other branch's stacked-on branch.
533
:param create_prefix: Create any missing directories leading up to
535
:param use_existing_dir: Use an existing directory if one exists.
536
:param no_tree: If set to true prevents creation of a working tree.
538
raise NotImplementedError(self.clone_on_transport)
541
def find_controldirs(klass, transport, evaluate=None, list_current=None):
542
"""Find control dirs recursively from current location.
544
This is intended primarily as a building block for more sophisticated
545
functionality, like finding trees under a directory, or finding
546
branches that use a given repository.
548
:param evaluate: An optional callable that yields recurse, value,
549
where recurse controls whether this controldir is recursed into
550
and value is the value to yield. By default, all bzrdirs
551
are recursed into, and the return value is the controldir.
552
:param list_current: if supplied, use this function to list the current
553
directory, instead of Transport.list_dir
554
:return: a generator of found bzrdirs, or whatever evaluate returns.
556
if list_current is None:
557
def list_current(transport):
558
return transport.list_dir('')
560
def evaluate(controldir):
561
return True, controldir
563
pending = [transport]
564
while len(pending) > 0:
565
current_transport = pending.pop()
568
controldir = klass.open_from_transport(current_transport)
569
except (errors.NotBranchError, errors.PermissionDenied,
570
errors.UnknownFormatError):
573
recurse, value = evaluate(controldir)
576
subdirs = list_current(current_transport)
577
except (errors.NoSuchFile, errors.PermissionDenied):
580
for subdir in sorted(subdirs, reverse=True):
581
pending.append(current_transport.clone(subdir))
584
def find_branches(klass, transport):
585
"""Find all branches under a transport.
587
This will find all branches below the transport, including branches
588
inside other branches. Where possible, it will use
589
Repository.find_branches.
591
To list all the branches that use a particular Repository, see
592
Repository.find_branches
594
def evaluate(controldir):
596
repository = controldir.open_repository()
597
except errors.NoRepositoryPresent:
600
return False, ([], repository)
601
return True, (controldir.list_branches(), None)
603
for branches, repo in klass.find_controldirs(
604
transport, evaluate=evaluate):
606
ret.extend(repo.find_branches())
607
if branches is not None:
612
def create_branch_and_repo(klass, base, force_new_repo=False, format=None):
613
"""Create a new ControlDir, Branch and Repository at the url 'base'.
615
This will use the current default ControlDirFormat unless one is
616
specified, and use whatever
617
repository format that that uses via controldir.create_branch and
618
create_repository. If a shared repository is available that is used
621
The created Branch object is returned.
623
:param base: The URL to create the branch at.
624
:param force_new_repo: If True a new repository is always created.
625
:param format: If supplied, the format of branch to create. If not
626
supplied, the default is used.
628
controldir = klass.create(base, format)
629
controldir._find_or_create_repository(force_new_repo)
630
return controldir.create_branch()
633
def create_branch_convenience(klass, base, force_new_repo=False,
634
force_new_tree=None, format=None,
635
possible_transports=None):
636
"""Create a new ControlDir, Branch and Repository at the url 'base'.
638
This is a convenience function - it will use an existing repository
639
if possible, can be told explicitly whether to create a working tree or
642
This will use the current default ControlDirFormat unless one is
643
specified, and use whatever
644
repository format that that uses via ControlDir.create_branch and
645
create_repository. If a shared repository is available that is used
646
preferentially. Whatever repository is used, its tree creation policy
649
The created Branch object is returned.
650
If a working tree cannot be made due to base not being a file:// url,
651
no error is raised unless force_new_tree is True, in which case no
652
data is created on disk and NotLocalUrl is raised.
654
:param base: The URL to create the branch at.
655
:param force_new_repo: If True a new repository is always created.
656
:param force_new_tree: If True or False force creation of a tree or
657
prevent such creation respectively.
658
:param format: Override for the controldir format to create.
659
:param possible_transports: An optional reusable transports list.
662
# check for non local urls
663
t = _mod_transport.get_transport(base, possible_transports)
664
if not isinstance(t, local.LocalTransport):
665
raise errors.NotLocalUrl(base)
666
controldir = klass.create(base, format, possible_transports)
667
repo = controldir._find_or_create_repository(force_new_repo)
668
result = controldir.create_branch()
669
if force_new_tree or (repo.make_working_trees() and
670
force_new_tree is None):
672
controldir.create_workingtree()
673
except errors.NotLocalUrl:
678
def create_standalone_workingtree(klass, base, format=None):
679
"""Create a new ControlDir, WorkingTree, Branch and Repository at 'base'.
681
'base' must be a local path or a file:// url.
683
This will use the current default ControlDirFormat unless one is
684
specified, and use whatever
685
repository format that that uses for bzrdirformat.create_workingtree,
686
create_branch and create_repository.
688
:param format: Override for the controldir format to create.
689
:return: The WorkingTree object.
691
t = _mod_transport.get_transport(base)
692
if not isinstance(t, local.LocalTransport):
693
raise errors.NotLocalUrl(base)
694
controldir = klass.create_branch_and_repo(base,
696
format=format).controldir
697
return controldir.create_workingtree()
700
def open_unsupported(klass, base):
701
"""Open a branch which is not supported."""
702
return klass.open(base, _unsupported=True)
705
def open(klass, base, possible_transports=None, probers=None,
707
"""Open an existing controldir, rooted at 'base' (url).
709
:param _unsupported: a private parameter to the ControlDir class.
711
t = _mod_transport.get_transport(base, possible_transports)
712
return klass.open_from_transport(t, probers=probers,
713
_unsupported=_unsupported)
716
def open_from_transport(klass, transport, _unsupported=False,
718
"""Open a controldir within a particular directory.
720
:param transport: Transport containing the controldir.
721
:param _unsupported: private.
723
for hook in klass.hooks['pre_open']:
725
# Keep initial base since 'transport' may be modified while following
727
base = transport.base
729
def find_format(transport):
730
return transport, ControlDirFormat.find_format(transport,
733
def redirected(transport, e, redirection_notice):
734
redirected_transport = transport._redirected_to(e.source, e.target)
735
if redirected_transport is None:
736
raise errors.NotBranchError(base)
737
trace.note(gettext('{0} is{1} redirected to {2}').format(
738
transport.base, e.permanently, redirected_transport.base))
739
return redirected_transport
742
transport, format = _mod_transport.do_catching_redirections(
743
find_format, transport, redirected)
744
except errors.TooManyRedirections:
745
raise errors.NotBranchError(base)
747
format.check_support_status(_unsupported)
748
return format.open(transport, _found=True)
751
def open_containing(klass, url, possible_transports=None):
752
"""Open an existing branch which contains url.
754
:param url: url to search from.
756
See open_containing_from_transport for more detail.
758
transport = _mod_transport.get_transport(url, possible_transports)
759
return klass.open_containing_from_transport(transport)
762
def open_containing_from_transport(klass, a_transport):
763
"""Open an existing branch which contains a_transport.base.
765
This probes for a branch at a_transport, and searches upwards from there.
767
Basically we keep looking up until we find the control directory or
768
run into the root. If there isn't one, raises NotBranchError.
769
If there is one and it is either an unrecognised format or an unsupported
770
format, UnknownFormatError or UnsupportedFormatError are raised.
771
If there is one, it is returned, along with the unused portion of url.
773
:return: The ControlDir that contains the path, and a Unicode path
774
for the rest of the URL.
776
# this gets the normalised url back. I.e. '.' -> the full path.
777
url = a_transport.base
780
result = klass.open_from_transport(a_transport)
781
return result, urlutils.unescape(a_transport.relpath(url))
782
except errors.NotBranchError:
784
except errors.PermissionDenied:
787
new_t = a_transport.clone('..')
788
except urlutils.InvalidURLJoin:
789
# reached the root, whatever that may be
790
raise errors.NotBranchError(path=url)
791
if new_t.base == a_transport.base:
792
# reached the root, whatever that may be
793
raise errors.NotBranchError(path=url)
797
def open_tree_or_branch(klass, location):
798
"""Return the branch and working tree at a location.
800
If there is no tree at the location, tree will be None.
801
If there is no branch at the location, an exception will be
803
:return: (tree, branch)
805
controldir = klass.open(location)
806
return controldir._get_tree_branch()
809
def open_containing_tree_or_branch(klass, location,
810
possible_transports=None):
811
"""Return the branch and working tree contained by a location.
813
Returns (tree, branch, relpath).
814
If there is no tree at containing the location, tree will be None.
815
If there is no branch containing the location, an exception will be
817
relpath is the portion of the path that is contained by the branch.
819
controldir, relpath = klass.open_containing(location,
820
possible_transports=possible_transports)
821
tree, branch = controldir._get_tree_branch()
822
return tree, branch, relpath
825
def open_containing_tree_branch_or_repository(klass, location):
826
"""Return the working tree, branch and repo contained by a location.
828
Returns (tree, branch, repository, relpath).
829
If there is no tree containing the location, tree will be None.
830
If there is no branch containing the location, branch will be None.
831
If there is no repository containing the location, repository will be
833
relpath is the portion of the path that is contained by the innermost
836
If no tree, branch or repository is found, a NotBranchError is raised.
838
controldir, relpath = klass.open_containing(location)
840
tree, branch = controldir._get_tree_branch()
841
except errors.NotBranchError:
843
repo = controldir.find_repository()
844
return None, None, repo, relpath
845
except (errors.NoRepositoryPresent):
846
raise errors.NotBranchError(location)
847
return tree, branch, branch.repository, relpath
850
def create(klass, base, format=None, possible_transports=None):
851
"""Create a new ControlDir at the url 'base'.
853
:param format: If supplied, the format of branch to create. If not
854
supplied, the default is used.
855
:param possible_transports: If supplied, a list of transports that
856
can be reused to share a remote connection.
858
if klass is not ControlDir:
859
raise AssertionError("ControlDir.create always creates the"
860
"default format, not one of %r" % klass)
861
t = _mod_transport.get_transport(base, possible_transports)
864
format = ControlDirFormat.get_default_format()
865
return format.initialize_on_transport(t)
868
class ControlDirHooks(hooks.Hooks):
869
"""Hooks for ControlDir operations."""
872
"""Create the default hooks."""
873
hooks.Hooks.__init__(self, "breezy.controldir", "ControlDir.hooks")
874
self.add_hook('pre_open',
875
"Invoked before attempting to open a ControlDir with the transport "
876
"that the open will use.", (1, 14))
877
self.add_hook('post_repo_init',
878
"Invoked after a repository has been initialized. "
879
"post_repo_init is called with a "
880
"breezy.controldir.RepoInitHookParams.",
884
# install the default hooks
885
ControlDir.hooks = ControlDirHooks()
888
class ControlComponentFormat(object):
889
"""A component that can live inside of a control directory."""
891
upgrade_recommended = False
893
def get_format_description(self):
894
"""Return the short description for this format."""
895
raise NotImplementedError(self.get_format_description)
897
def is_supported(self):
898
"""Is this format supported?
900
Supported formats must be initializable and openable.
901
Unsupported formats may not support initialization or committing or
902
some other features depending on the reason for not being supported.
906
def check_support_status(self, allow_unsupported, recommend_upgrade=True,
908
"""Give an error or warning on old formats.
910
:param allow_unsupported: If true, allow opening
911
formats that are strongly deprecated, and which may
912
have limited functionality.
914
:param recommend_upgrade: If true (default), warn
915
the user through the ui object that they may wish
916
to upgrade the object.
918
if not allow_unsupported and not self.is_supported():
919
# see open_downlevel to open legacy branches.
920
raise errors.UnsupportedFormatError(format=self)
921
if recommend_upgrade and self.upgrade_recommended:
922
ui.ui_factory.recommend_upgrade(
923
self.get_format_description(), basedir)
926
def get_format_string(cls):
927
raise NotImplementedError(cls.get_format_string)
930
class ControlComponentFormatRegistry(registry.FormatRegistry):
931
"""A registry for control components (branch, workingtree, repository)."""
933
def __init__(self, other_registry=None):
934
super(ControlComponentFormatRegistry, self).__init__(other_registry)
935
self._extra_formats = []
937
def register(self, format):
938
"""Register a new format."""
939
super(ControlComponentFormatRegistry, self).register(
940
format.get_format_string(), format)
942
def remove(self, format):
943
"""Remove a registered format."""
944
super(ControlComponentFormatRegistry, self).remove(
945
format.get_format_string())
947
def register_extra(self, format):
948
"""Register a format that can not be used in a metadir.
950
This is mainly useful to allow custom repository formats, such as older
951
Bazaar formats and foreign formats, to be tested.
953
self._extra_formats.append(registry._ObjectGetter(format))
955
def remove_extra(self, format):
956
"""Remove an extra format.
958
self._extra_formats.remove(registry._ObjectGetter(format))
960
def register_extra_lazy(self, module_name, member_name):
961
"""Register a format lazily.
963
self._extra_formats.append(
964
registry._LazyObjectGetter(module_name, member_name))
966
def _get_extra(self):
967
"""Return getters for extra formats, not usable in meta directories."""
968
return [getter.get_obj for getter in self._extra_formats]
970
def _get_all_lazy(self):
971
"""Return getters for all formats, even those not usable in metadirs."""
972
result = [self._dict[name].get_obj for name in self.keys()]
973
result.extend(self._get_extra())
977
"""Return all formats, even those not usable in metadirs."""
979
for getter in self._get_all_lazy():
986
def _get_all_modules(self):
987
"""Return a set of the modules providing objects."""
989
for name in self.keys():
990
modules.add(self._get_module(name))
991
for getter in self._extra_formats:
992
modules.add(getter.get_module())
996
class Converter(object):
997
"""Converts a disk format object from one format to another."""
999
def convert(self, to_convert, pb):
1000
"""Perform the conversion of to_convert, giving feedback via pb.
1002
:param to_convert: The disk object to convert.
1003
:param pb: a progress bar to use for progress information.
1006
def step(self, message):
1007
"""Update the pb by a step."""
1009
self.pb.update(message, self.count, self.total)
1012
class ControlDirFormat(object):
1013
"""An encapsulation of the initialization and open routines for a format.
1015
Formats provide three things:
1016
* An initialization routine,
1020
Formats are placed in a dict by their format string for reference
1021
during controldir opening. These should be subclasses of ControlDirFormat
1024
Once a format is deprecated, just deprecate the initialize and open
1025
methods on the format class. Do not deprecate the object, as the
1026
object will be created every system load.
1028
:cvar colocated_branches: Whether this formats supports colocated branches.
1029
:cvar supports_workingtrees: This control directory can co-exist with a
1033
_default_format = None
1034
"""The default format used for new control directories."""
1037
"""The registered format probers, e.g. BzrProber.
1039
This is a list of Prober-derived classes.
1042
colocated_branches = False
1043
"""Whether co-located branches are supported for this control dir format.
1046
supports_workingtrees = True
1047
"""Whether working trees can exist in control directories of this format.
1050
fixed_components = False
1051
"""Whether components can not change format independent of the control dir.
1054
upgrade_recommended = False
1055
"""Whether an upgrade from this format is recommended."""
1057
def get_format_description(self):
1058
"""Return the short description for this format."""
1059
raise NotImplementedError(self.get_format_description)
1061
def get_converter(self, format=None):
1062
"""Return the converter to use to convert controldirs needing converts.
1064
This returns a breezy.controldir.Converter object.
1066
This should return the best upgrader to step this format towards the
1067
current default format. In the case of plugins we can/should provide
1068
some means for them to extend the range of returnable converters.
1070
:param format: Optional format to override the default format of the
1073
raise NotImplementedError(self.get_converter)
1075
def is_supported(self):
1076
"""Is this format supported?
1078
Supported formats must be openable.
1079
Unsupported formats may not support initialization or committing or
1080
some other features depending on the reason for not being supported.
1084
def is_initializable(self):
1085
"""Whether new control directories of this format can be initialized.
1087
return self.is_supported()
1089
def check_support_status(self, allow_unsupported, recommend_upgrade=True,
1091
"""Give an error or warning on old formats.
1093
:param allow_unsupported: If true, allow opening
1094
formats that are strongly deprecated, and which may
1095
have limited functionality.
1097
:param recommend_upgrade: If true (default), warn
1098
the user through the ui object that they may wish
1099
to upgrade the object.
1101
if not allow_unsupported and not self.is_supported():
1102
# see open_downlevel to open legacy branches.
1103
raise errors.UnsupportedFormatError(format=self)
1104
if recommend_upgrade and self.upgrade_recommended:
1105
ui.ui_factory.recommend_upgrade(
1106
self.get_format_description(), basedir)
1108
def same_model(self, target_format):
1109
return (self.repository_format.rich_root_data ==
1110
target_format.rich_root_data)
1113
def register_prober(klass, prober):
1114
"""Register a prober that can look for a control dir.
1117
klass._probers.append(prober)
1120
def unregister_prober(klass, prober):
1121
"""Unregister a prober.
1124
klass._probers.remove(prober)
1128
return self.get_format_description().rstrip()
1131
def all_probers(klass):
1132
return klass._probers
1135
def known_formats(klass):
1136
"""Return all the known formats.
1139
for prober_kls in klass.all_probers():
1140
result.extend(prober_kls.known_formats())
1144
def find_format(klass, transport, probers=None):
1145
"""Return the format present at transport."""
1148
klass.all_probers(),
1149
key=lambda prober: prober.priority(transport))
1150
for prober_kls in probers:
1151
prober = prober_kls()
1153
return prober.probe_transport(transport)
1154
except errors.NotBranchError:
1155
# this format does not find a control dir here.
1157
raise errors.NotBranchError(path=transport.base)
1159
def initialize(self, url, possible_transports=None):
1160
"""Create a control dir at this url and return an opened copy.
1162
While not deprecated, this method is very specific and its use will
1163
lead to many round trips to setup a working environment. See
1164
initialize_on_transport_ex for a [nearly] all-in-one method.
1166
Subclasses should typically override initialize_on_transport
1167
instead of this method.
1169
return self.initialize_on_transport(
1170
_mod_transport.get_transport(url, possible_transports))
1172
def initialize_on_transport(self, transport):
1173
"""Initialize a new controldir in the base directory of a Transport."""
1174
raise NotImplementedError(self.initialize_on_transport)
1176
def initialize_on_transport_ex(self, transport, use_existing_dir=False,
1177
create_prefix=False, force_new_repo=False, stacked_on=None,
1178
stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
1179
shared_repo=False, vfs_only=False):
1180
"""Create this format on transport.
1182
The directory to initialize will be created.
1184
:param force_new_repo: Do not use a shared repository for the target,
1185
even if one is available.
1186
:param create_prefix: Create any missing directories leading up to
1188
:param use_existing_dir: Use an existing directory if one exists.
1189
:param stacked_on: A url to stack any created branch on, None to follow
1190
any target stacking policy.
1191
:param stack_on_pwd: If stack_on is relative, the location it is
1193
:param repo_format_name: If non-None, a repository will be
1194
made-or-found. Should none be found, or if force_new_repo is True
1195
the repo_format_name is used to select the format of repository to
1197
:param make_working_trees: Control the setting of make_working_trees
1198
for a new shared repository when one is made. None to use whatever
1199
default the format has.
1200
:param shared_repo: Control whether made repositories are shared or
1202
:param vfs_only: If True do not attempt to use a smart server
1203
:return: repo, controldir, require_stacking, repository_policy. repo is
1204
None if none was created or found, controldir is always valid.
1205
require_stacking is the result of examining the stacked_on
1206
parameter and any stacking policy found for the target.
1208
raise NotImplementedError(self.initialize_on_transport_ex)
1210
def network_name(self):
1211
"""A simple byte string uniquely identifying this format for RPC calls.
1213
Bzr control formats use this disk format string to identify the format
1214
over the wire. Its possible that other control formats have more
1215
complex detection requirements, so we permit them to use any unique and
1216
immutable string they desire.
1218
raise NotImplementedError(self.network_name)
1220
def open(self, transport, _found=False):
1221
"""Return an instance of this format for the dir transport points at.
1223
raise NotImplementedError(self.open)
1226
def _set_default_format(klass, format):
1227
"""Set default format (for testing behavior of defaults only)"""
1228
klass._default_format = format
1231
def get_default_format(klass):
1232
"""Return the current default format."""
1233
return klass._default_format
1235
def supports_transport(self, transport):
1236
"""Check if this format can be opened over a particular transport.
1238
raise NotImplementedError(self.supports_transport)
1241
def is_control_filename(klass, filename):
1242
"""True if filename is the name of a path which is reserved for
1245
:param filename: A filename within the root transport of this
1248
This is true IF and ONLY IF the filename is part of the namespace reserved
1249
for bzr control dirs. Currently this is the '.bzr' directory in the root
1250
of the root_transport. it is expected that plugins will need to extend
1251
this in the future - for instance to make bzr talk with svn working
1254
raise NotImplementedError(self.is_control_filename)
1257
class Prober(object):
1258
"""Abstract class that can be used to detect a particular kind of
1261
At the moment this just contains a single method to probe a particular
1262
transport, but it may be extended in the future to e.g. avoid
1263
multiple levels of probing for Subversion repositories.
1265
See BzrProber and RemoteBzrProber in breezy.bzrdir for the
1266
probers that detect .bzr/ directories and Bazaar smart servers,
1269
Probers should be registered using the register_prober methods on
1273
def probe_transport(self, transport):
1274
"""Return the controldir style format present in a directory.
1276
:raise UnknownFormatError: If a control dir was found but is
1277
in an unknown format.
1278
:raise NotBranchError: If no control directory was found.
1279
:return: A ControlDirFormat instance.
1281
raise NotImplementedError(self.probe_transport)
1284
def known_formats(klass):
1285
"""Return the control dir formats known by this prober.
1287
Multiple probers can return the same formats, so this should
1290
:return: A set of known formats.
1292
raise NotImplementedError(klass.known_formats)
1295
def priority(klass, transport):
1296
"""Priority of this prober.
1298
A lower value means the prober gets checked first.
1302
-10: This is a "server" prober
1304
10: This is a regular file-based prober
1305
100: This is a prober for an unsupported format
1310
class ControlDirFormatInfo(object):
1312
def __init__(self, native, deprecated, hidden, experimental):
1313
self.deprecated = deprecated
1314
self.native = native
1315
self.hidden = hidden
1316
self.experimental = experimental
1319
class ControlDirFormatRegistry(registry.Registry):
1320
"""Registry of user-selectable ControlDir subformats.
1322
Differs from ControlDirFormat._formats in that it provides sub-formats,
1323
e.g. BzrDirMeta1 with weave repository. Also, it's more user-oriented.
1327
"""Create a ControlDirFormatRegistry."""
1328
self._registration_order = list()
1329
super(ControlDirFormatRegistry, self).__init__()
1331
def register(self, key, factory, help, native=True, deprecated=False,
1332
hidden=False, experimental=False):
1333
"""Register a ControlDirFormat factory.
1335
The factory must be a callable that takes one parameter: the key.
1336
It must produce an instance of the ControlDirFormat when called.
1338
This function mainly exists to prevent the info object from being
1341
registry.Registry.register(self, key, factory, help,
1342
ControlDirFormatInfo(native, deprecated, hidden, experimental))
1343
self._registration_order.append(key)
1345
def register_alias(self, key, target, hidden=False):
1346
"""Register a format alias.
1348
:param key: Alias name
1349
:param target: Target format
1350
:param hidden: Whether the alias is hidden
1352
info = self.get_info(target)
1353
registry.Registry.register_alias(self, key, target,
1354
ControlDirFormatInfo(
1355
native=info.native, deprecated=info.deprecated,
1356
hidden=hidden, experimental=info.experimental))
1358
def register_lazy(self, key, module_name, member_name, help, native=True,
1359
deprecated=False, hidden=False, experimental=False):
1360
registry.Registry.register_lazy(self, key, module_name, member_name,
1361
help, ControlDirFormatInfo(native, deprecated, hidden, experimental))
1362
self._registration_order.append(key)
1364
def set_default(self, key):
1365
"""Set the 'default' key to be a clone of the supplied key.
1367
This method must be called once and only once.
1369
self.register_alias('default', key)
1371
def set_default_repository(self, key):
1372
"""Set the FormatRegistry default and Repository default.
1374
This is a transitional method while Repository.set_default_format
1377
if 'default' in self:
1378
self.remove('default')
1379
self.set_default(key)
1380
format = self.get('default')()
1382
def make_controldir(self, key):
1383
return self.get(key)()
1385
def help_topic(self, topic):
1387
default_realkey = None
1388
default_help = self.get_help('default')
1390
for key in self._registration_order:
1391
if key == 'default':
1393
help = self.get_help(key)
1394
if help == default_help:
1395
default_realkey = key
1397
help_pairs.append((key, help))
1399
def wrapped(key, help, info):
1401
help = '(native) ' + help
1402
return ':%s:\n%s\n\n' % (key,
1403
textwrap.fill(help, initial_indent=' ',
1404
subsequent_indent=' ',
1405
break_long_words=False))
1406
if default_realkey is not None:
1407
output += wrapped(default_realkey, '(default) %s' % default_help,
1408
self.get_info('default'))
1409
deprecated_pairs = []
1410
experimental_pairs = []
1411
for key, help in help_pairs:
1412
info = self.get_info(key)
1415
elif info.deprecated:
1416
deprecated_pairs.append((key, help))
1417
elif info.experimental:
1418
experimental_pairs.append((key, help))
1420
output += wrapped(key, help, info)
1421
output += "\nSee :doc:`formats-help` for more about storage formats."
1423
if len(experimental_pairs) > 0:
1424
other_output += "Experimental formats are shown below.\n\n"
1425
for key, help in experimental_pairs:
1426
info = self.get_info(key)
1427
other_output += wrapped(key, help, info)
1430
"No experimental formats are available.\n\n"
1431
if len(deprecated_pairs) > 0:
1432
other_output += "\nDeprecated formats are shown below.\n\n"
1433
for key, help in deprecated_pairs:
1434
info = self.get_info(key)
1435
other_output += wrapped(key, help, info)
1438
"\nNo deprecated formats are available.\n\n"
1440
"\nSee :doc:`formats-help` for more about storage formats."
1442
if topic == 'other-formats':
1448
class RepoInitHookParams(object):
1449
"""Object holding parameters passed to `*_repo_init` hooks.
1451
There are 4 fields that hooks may wish to access:
1453
:ivar repository: Repository created
1454
:ivar format: Repository format
1455
:ivar bzrdir: The controldir for the repository
1456
:ivar shared: The repository is shared
1459
def __init__(self, repository, format, controldir, shared):
1460
"""Create a group of RepoInitHook parameters.
1462
:param repository: Repository created
1463
:param format: Repository format
1464
:param controldir: The controldir for the repository
1465
:param shared: The repository is shared
1467
self.repository = repository
1468
self.format = format
1469
self.controldir = controldir
1470
self.shared = shared
1472
def __eq__(self, other):
1473
return self.__dict__ == other.__dict__
1477
return "<%s for %s>" % (self.__class__.__name__,
1480
return "<%s for %s>" % (self.__class__.__name__,
1484
def is_control_filename(filename):
1485
"""Check if filename is used for control directories."""
1486
# TODO(jelmer): Instead, have a function that returns all control
1488
for key, format in format_registry.items():
1489
if format().is_control_filename(filename):
1495
class RepositoryAcquisitionPolicy(object):
1496
"""Abstract base class for repository acquisition policies.
1498
A repository acquisition policy decides how a ControlDir acquires a repository
1499
for a branch that is being created. The most basic policy decision is
1500
whether to create a new repository or use an existing one.
1503
def __init__(self, stack_on, stack_on_pwd, require_stacking):
1506
:param stack_on: A location to stack on
1507
:param stack_on_pwd: If stack_on is relative, the location it is
1509
:param require_stacking: If True, it is a failure to not stack.
1511
self._stack_on = stack_on
1512
self._stack_on_pwd = stack_on_pwd
1513
self._require_stacking = require_stacking
1515
def configure_branch(self, branch):
1516
"""Apply any configuration data from this policy to the branch.
1518
Default implementation sets repository stacking.
1520
if self._stack_on is None:
1522
if self._stack_on_pwd is None:
1523
stack_on = self._stack_on
1526
stack_on = urlutils.rebase_url(self._stack_on,
1529
except urlutils.InvalidRebaseURLs:
1530
stack_on = self._get_full_stack_on()
1532
branch.set_stacked_on_url(stack_on)
1533
except (_mod_branch.UnstackableBranchFormat,
1534
errors.UnstackableRepositoryFormat):
1535
if self._require_stacking:
1538
def requires_stacking(self):
1539
"""Return True if this policy requires stacking."""
1540
return self._stack_on is not None and self._require_stacking
1542
def _get_full_stack_on(self):
1543
"""Get a fully-qualified URL for the stack_on location."""
1544
if self._stack_on is None:
1546
if self._stack_on_pwd is None:
1547
return self._stack_on
1549
return urlutils.join(self._stack_on_pwd, self._stack_on)
1551
def _add_fallback(self, repository, possible_transports=None):
1552
"""Add a fallback to the supplied repository, if stacking is set."""
1553
stack_on = self._get_full_stack_on()
1554
if stack_on is None:
1557
stacked_dir = ControlDir.open(
1558
stack_on, possible_transports=possible_transports)
1559
except errors.JailBreak:
1560
# We keep the stacking details, but we are in the server code so
1561
# actually stacking is not needed.
1564
stacked_repo = stacked_dir.open_branch().repository
1565
except errors.NotBranchError:
1566
stacked_repo = stacked_dir.open_repository()
1568
repository.add_fallback_repository(stacked_repo)
1569
except errors.UnstackableRepositoryFormat:
1570
if self._require_stacking:
1573
self._require_stacking = True
1575
def acquire_repository(self, make_working_trees=None, shared=False,
1576
possible_transports=None):
1577
"""Acquire a repository for this controlrdir.
1579
Implementations may create a new repository or use a pre-exising
1582
:param make_working_trees: If creating a repository, set
1583
make_working_trees to this value (if non-None)
1584
:param shared: If creating a repository, make it shared if True
1585
:return: A repository, is_new_flag (True if the repository was
1588
raise NotImplementedError(
1589
RepositoryAcquisitionPolicy.acquire_repository)
1592
# Please register new formats after old formats so that formats
1593
# appear in chronological order and format descriptions can build
1595
format_registry = ControlDirFormatRegistry()
1597
network_format_registry = registry.FormatRegistry()
1598
"""Registry of formats indexed by their network name.
1600
The network name for a ControlDirFormat is an identifier that can be used when
1601
referring to formats with smart server operations. See
1602
ControlDirFormat.network_name() for more detail.