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 branch_names(self):
133
"""List all branch names in this control directory.
135
:return: List of branch names
138
self.get_branch_reference()
139
except (errors.NotBranchError, errors.NoRepositoryPresent):
144
def get_branches(self):
145
"""Get all branches in this control directory, as a dictionary.
147
:return: Dictionary mapping branch names to instances.
150
return {"": self.open_branch()}
151
except (errors.NotBranchError, errors.NoRepositoryPresent):
154
def is_control_filename(self, filename):
155
"""True if filename is the name of a path which is reserved for
158
:param filename: A filename within the root transport of this
161
This is true IF and ONLY IF the filename is part of the namespace reserved
162
for bzr control dirs. Currently this is the '.bzr' directory in the root
163
of the root_transport. it is expected that plugins will need to extend
164
this in the future - for instance to make bzr talk with svn working
167
return self._format.is_control_filename(filename)
169
def needs_format_conversion(self, format=None):
170
"""Return true if this controldir needs convert_format run on it.
172
For instance, if the repository format is out of date but the
173
branch and working tree are not, this should return True.
175
:param format: Optional parameter indicating a specific desired
176
format we plan to arrive at.
178
raise NotImplementedError(self.needs_format_conversion)
180
def create_repository(self, shared=False):
181
"""Create a new repository in this control directory.
183
:param shared: If a shared repository should be created
184
:return: The newly created repository
186
raise NotImplementedError(self.create_repository)
188
def destroy_repository(self):
189
"""Destroy the repository in this ControlDir."""
190
raise NotImplementedError(self.destroy_repository)
192
def create_branch(self, name=None, repository=None,
193
append_revisions_only=None):
194
"""Create a branch in this ControlDir.
196
:param name: Name of the colocated branch to create, None for
197
the user selected branch or "" for the active branch.
198
:param append_revisions_only: Whether this branch should only allow
199
appending new revisions to its history.
201
The controldirs format will control what branch format is created.
202
For more control see BranchFormatXX.create(a_controldir).
204
raise NotImplementedError(self.create_branch)
206
def destroy_branch(self, name=None):
207
"""Destroy a branch in this ControlDir.
209
:param name: Name of the branch to destroy, None for the
210
user selected branch or "" for the active branch.
211
:raise NotBranchError: When the branch does not exist
213
raise NotImplementedError(self.destroy_branch)
215
def create_workingtree(self, revision_id=None, from_branch=None,
216
accelerator_tree=None, hardlink=False):
217
"""Create a working tree at this ControlDir.
219
:param revision_id: create it as of this revision id.
220
:param from_branch: override controldir branch
221
(for lightweight checkouts)
222
:param accelerator_tree: A tree which can be used for retrieving file
223
contents more quickly than the revision tree, i.e. a workingtree.
224
The revision tree will be used for cases where accelerator_tree's
225
content is different.
227
raise NotImplementedError(self.create_workingtree)
229
def destroy_workingtree(self):
230
"""Destroy the working tree at this ControlDir.
232
Formats that do not support this may raise UnsupportedOperation.
234
raise NotImplementedError(self.destroy_workingtree)
236
def destroy_workingtree_metadata(self):
237
"""Destroy the control files for the working tree at this ControlDir.
239
The contents of working tree files are not affected.
240
Formats that do not support this may raise UnsupportedOperation.
242
raise NotImplementedError(self.destroy_workingtree_metadata)
244
def find_branch_format(self, name=None):
245
"""Find the branch 'format' for this controldir.
247
This might be a synthetic object for e.g. RemoteBranch and SVN.
249
raise NotImplementedError(self.find_branch_format)
251
def get_branch_reference(self, name=None):
252
"""Return the referenced URL for the branch in this controldir.
254
:param name: Optional colocated branch name
255
:raises NotBranchError: If there is no Branch.
256
:raises NoColocatedBranchSupport: If a branch name was specified
257
but colocated branches are not supported.
258
:return: The URL the branch in this controldir references if it is a
259
reference branch, or None for regular branches.
262
raise errors.NoColocatedBranchSupport(self)
265
def set_branch_reference(self, target_branch, name=None):
266
"""Set the referenced URL for the branch in this controldir.
268
:param name: Optional colocated branch name
269
:param target_branch: Branch to reference
270
:raises NoColocatedBranchSupport: If a branch name was specified
271
but colocated branches are not supported.
272
:return: The referencing branch
274
raise NotImplementedError(self.set_branch_reference)
276
def open_branch(self, name=None, unsupported=False,
277
ignore_fallbacks=False, possible_transports=None):
278
"""Open the branch object at this ControlDir if one is present.
280
:param unsupported: if True, then no longer supported branch formats can
282
:param ignore_fallbacks: Whether to open fallback repositories
283
:param possible_transports: Transports to use for opening e.g.
284
fallback repositories.
286
raise NotImplementedError(self.open_branch)
288
def open_repository(self, _unsupported=False):
289
"""Open the repository object at this ControlDir if one is present.
291
This will not follow the Branch object pointer - it's strictly a direct
292
open facility. Most client code should use open_branch().repository to
295
:param _unsupported: a private parameter, not part of the api.
297
raise NotImplementedError(self.open_repository)
299
def find_repository(self):
300
"""Find the repository that should be used.
302
This does not require a branch as we use it to find the repo for
303
new branches as well as to hook existing branches up to their
306
raise NotImplementedError(self.find_repository)
308
def open_workingtree(self, unsupported=False,
309
recommend_upgrade=True, from_branch=None):
310
"""Open the workingtree object at this ControlDir if one is present.
312
:param recommend_upgrade: Optional keyword parameter, when True (the
313
default), emit through the ui module a recommendation that the user
314
upgrade the working tree when the workingtree being opened is old
315
(but still fully supported).
316
:param from_branch: override controldir branch (for lightweight
319
raise NotImplementedError(self.open_workingtree)
321
def has_branch(self, name=None):
322
"""Tell if this controldir contains a branch.
324
Note: if you're going to open the branch, you should just go ahead
325
and try, and not ask permission first. (This method just opens the
326
branch and discards it, and that's somewhat expensive.)
329
self.open_branch(name, ignore_fallbacks=True)
331
except errors.NotBranchError:
334
def _get_selected_branch(self):
335
"""Return the name of the branch selected by the user.
337
:return: Name of the branch selected by the user, or "".
339
branch = self.root_transport.get_segment_parameters().get("branch")
342
return urlutils.unescape(branch)
344
def has_workingtree(self):
345
"""Tell if this controldir contains a working tree.
347
This will still raise an exception if the controldir has a workingtree
348
that is remote & inaccessible.
350
Note: if you're going to open the working tree, you should just go ahead
351
and try, and not ask permission first. (This method just opens the
352
workingtree and discards it, and that's somewhat expensive.)
355
self.open_workingtree(recommend_upgrade=False)
357
except errors.NoWorkingTree:
360
def cloning_metadir(self, require_stacking=False):
361
"""Produce a metadir suitable for cloning or sprouting with.
363
These operations may produce workingtrees (yes, even though they're
364
"cloning" something that doesn't have a tree), so a viable workingtree
365
format must be selected.
367
:require_stacking: If True, non-stackable formats will be upgraded
368
to similar stackable formats.
369
:returns: a ControlDirFormat with all component formats either set
370
appropriately or set to None if that component should not be
373
raise NotImplementedError(self.cloning_metadir)
375
def checkout_metadir(self):
376
"""Produce a metadir suitable for checkouts of this controldir.
378
:returns: A ControlDirFormat with all component formats
379
either set appropriately or set to None if that component
380
should not be created.
382
return self.cloning_metadir()
384
def sprout(self, url, revision_id=None, force_new_repo=False,
385
recurse='down', possible_transports=None,
386
accelerator_tree=None, hardlink=False, stacked=False,
387
source_branch=None, create_tree_if_local=True,
389
"""Create a copy of this controldir prepared for use as a new line of
392
If url's last component does not exist, it will be created.
394
Attributes related to the identity of the source branch like
395
branch nickname will be cleaned, a working tree is created
396
whether one existed before or not; and a local branch is always
399
:param revision_id: if revision_id is not None, then the clone
400
operation may tune itself to download less data.
401
:param accelerator_tree: A tree which can be used for retrieving file
402
contents more quickly than the revision tree, i.e. a workingtree.
403
The revision tree will be used for cases where accelerator_tree's
404
content is different.
405
:param hardlink: If true, hard-link files from accelerator_tree,
407
:param stacked: If true, create a stacked branch referring to the
408
location of this control directory.
409
:param create_tree_if_local: If true, a working-tree will be created
410
when working locally.
412
raise NotImplementedError(self.sprout)
414
def push_branch(self, source, revision_id=None, overwrite=False,
415
remember=False, create_prefix=False, lossy=False,
417
"""Push the source branch into this ControlDir."""
419
# If we can open a branch, use its direct repository, otherwise see
420
# if there is a repository without a branch.
422
br_to = self.open_branch()
423
except errors.NotBranchError:
424
# Didn't find a branch, can we find a repository?
425
repository_to = self.find_repository()
427
# Found a branch, so we must have found a repository
428
repository_to = br_to.repository
430
push_result = PushResult()
431
push_result.source_branch = source
433
# We have a repository but no branch, copy the revisions, and then
435
if revision_id is None:
436
# No revision supplied by the user, default to the branch
438
revision_id = source.last_revision()
439
repository_to.fetch(source.repository, revision_id=revision_id)
440
br_to = source.sprout(
441
self, revision_id=revision_id, lossy=lossy,
442
tag_selector=tag_selector)
443
if source.get_push_location() is None or remember:
444
# FIXME: Should be done only if we succeed ? -- vila 2012-01-18
445
source.set_push_location(br_to.base)
446
push_result.stacked_on = None
447
push_result.branch_push_result = None
448
push_result.old_revno = None
449
push_result.old_revid = _mod_revision.NULL_REVISION
450
push_result.target_branch = br_to
451
push_result.master_branch = None
452
push_result.workingtree_updated = False
454
# We have successfully opened the branch, remember if necessary:
455
if source.get_push_location() is None or remember:
456
# FIXME: Should be done only if we succeed ? -- vila 2012-01-18
457
source.set_push_location(br_to.base)
459
tree_to = self.open_workingtree()
460
except errors.NotLocalUrl:
461
push_result.branch_push_result = source.push(
462
br_to, overwrite, stop_revision=revision_id, lossy=lossy,
463
tag_selector=tag_selector)
464
push_result.workingtree_updated = False
465
except errors.NoWorkingTree:
466
push_result.branch_push_result = source.push(
467
br_to, overwrite, stop_revision=revision_id, lossy=lossy,
468
tag_selector=tag_selector)
469
push_result.workingtree_updated = None # Not applicable
471
with tree_to.lock_write():
472
push_result.branch_push_result = source.push(
473
tree_to.branch, overwrite, stop_revision=revision_id,
474
lossy=lossy, tag_selector=tag_selector)
476
push_result.workingtree_updated = True
477
push_result.old_revno = push_result.branch_push_result.old_revno
478
push_result.old_revid = push_result.branch_push_result.old_revid
479
push_result.target_branch = \
480
push_result.branch_push_result.target_branch
483
def _get_tree_branch(self, name=None):
484
"""Return the branch and tree, if any, for this controldir.
486
:param name: Name of colocated branch to open.
488
Return None for tree if not present or inaccessible.
489
Raise NotBranchError if no branch is present.
490
:return: (tree, branch)
493
tree = self.open_workingtree()
494
except (errors.NoWorkingTree, errors.NotLocalUrl):
496
branch = self.open_branch(name=name)
499
branch = self.open_branch(name=name)
504
def get_config(self):
505
"""Get configuration for this ControlDir."""
506
raise NotImplementedError(self.get_config)
508
def check_conversion_target(self, target_format):
509
"""Check that a controldir as a whole can be converted to a new format."""
510
raise NotImplementedError(self.check_conversion_target)
512
def clone(self, url, revision_id=None, force_new_repo=False,
513
preserve_stacking=False, tag_selector=None):
514
"""Clone this controldir and its contents to url verbatim.
516
:param url: The url create the clone at. If url's last component does
517
not exist, it will be created.
518
:param revision_id: The tip revision-id to use for any branch or
519
working tree. If not None, then the clone operation may tune
520
itself to download less data.
521
:param force_new_repo: Do not use a shared repository for the target
522
even if one is available.
523
:param preserve_stacking: When cloning a stacked branch, stack the
524
new branch on top of the other branch's stacked-on branch.
526
return self.clone_on_transport(_mod_transport.get_transport(url),
527
revision_id=revision_id,
528
force_new_repo=force_new_repo,
529
preserve_stacking=preserve_stacking,
530
tag_selector=tag_selector)
532
def clone_on_transport(self, transport, revision_id=None,
533
force_new_repo=False, preserve_stacking=False, stacked_on=None,
534
create_prefix=False, use_existing_dir=True, no_tree=False,
536
"""Clone this controldir and its contents to transport verbatim.
538
:param transport: The transport for the location to produce the clone
539
at. If the target directory does not exist, it will be created.
540
:param revision_id: The tip revision-id to use for any branch or
541
working tree. If not None, then the clone operation may tune
542
itself to download less data.
543
:param force_new_repo: Do not use a shared repository for the target,
544
even if one is available.
545
:param preserve_stacking: When cloning a stacked branch, stack the
546
new branch on top of the other branch's stacked-on branch.
547
:param create_prefix: Create any missing directories leading up to
549
:param use_existing_dir: Use an existing directory if one exists.
550
:param no_tree: If set to true prevents creation of a working tree.
552
raise NotImplementedError(self.clone_on_transport)
555
def find_controldirs(klass, transport, evaluate=None, list_current=None):
556
"""Find control dirs recursively from current location.
558
This is intended primarily as a building block for more sophisticated
559
functionality, like finding trees under a directory, or finding
560
branches that use a given repository.
562
:param evaluate: An optional callable that yields recurse, value,
563
where recurse controls whether this controldir is recursed into
564
and value is the value to yield. By default, all bzrdirs
565
are recursed into, and the return value is the controldir.
566
:param list_current: if supplied, use this function to list the current
567
directory, instead of Transport.list_dir
568
:return: a generator of found bzrdirs, or whatever evaluate returns.
570
if list_current is None:
571
def list_current(transport):
572
return transport.list_dir('')
574
def evaluate(controldir):
575
return True, controldir
577
pending = [transport]
578
while len(pending) > 0:
579
current_transport = pending.pop()
582
controldir = klass.open_from_transport(current_transport)
583
except (errors.NotBranchError, errors.PermissionDenied,
584
errors.UnknownFormatError):
587
recurse, value = evaluate(controldir)
590
subdirs = list_current(current_transport)
591
except (errors.NoSuchFile, errors.PermissionDenied):
594
for subdir in sorted(subdirs, reverse=True):
595
pending.append(current_transport.clone(subdir))
598
def find_branches(klass, transport):
599
"""Find all branches under a transport.
601
This will find all branches below the transport, including branches
602
inside other branches. Where possible, it will use
603
Repository.find_branches.
605
To list all the branches that use a particular Repository, see
606
Repository.find_branches
608
def evaluate(controldir):
610
repository = controldir.open_repository()
611
except errors.NoRepositoryPresent:
614
return False, ([], repository)
615
return True, (controldir.list_branches(), None)
617
for branches, repo in klass.find_controldirs(
618
transport, evaluate=evaluate):
620
ret.extend(repo.find_branches())
621
if branches is not None:
626
def create_branch_and_repo(klass, base, force_new_repo=False, format=None):
627
"""Create a new ControlDir, Branch and Repository at the url 'base'.
629
This will use the current default ControlDirFormat unless one is
630
specified, and use whatever
631
repository format that that uses via controldir.create_branch and
632
create_repository. If a shared repository is available that is used
635
The created Branch object is returned.
637
:param base: The URL to create the branch at.
638
:param force_new_repo: If True a new repository is always created.
639
:param format: If supplied, the format of branch to create. If not
640
supplied, the default is used.
642
controldir = klass.create(base, format)
643
controldir._find_or_create_repository(force_new_repo)
644
return controldir.create_branch()
647
def create_branch_convenience(klass, base, force_new_repo=False,
648
force_new_tree=None, format=None,
649
possible_transports=None):
650
"""Create a new ControlDir, Branch and Repository at the url 'base'.
652
This is a convenience function - it will use an existing repository
653
if possible, can be told explicitly whether to create a working tree or
656
This will use the current default ControlDirFormat unless one is
657
specified, and use whatever
658
repository format that that uses via ControlDir.create_branch and
659
create_repository. If a shared repository is available that is used
660
preferentially. Whatever repository is used, its tree creation policy
663
The created Branch object is returned.
664
If a working tree cannot be made due to base not being a file:// url,
665
no error is raised unless force_new_tree is True, in which case no
666
data is created on disk and NotLocalUrl is raised.
668
:param base: The URL to create the branch at.
669
:param force_new_repo: If True a new repository is always created.
670
:param force_new_tree: If True or False force creation of a tree or
671
prevent such creation respectively.
672
:param format: Override for the controldir format to create.
673
:param possible_transports: An optional reusable transports list.
676
# check for non local urls
677
t = _mod_transport.get_transport(base, possible_transports)
678
if not isinstance(t, local.LocalTransport):
679
raise errors.NotLocalUrl(base)
680
controldir = klass.create(base, format, possible_transports)
681
repo = controldir._find_or_create_repository(force_new_repo)
682
result = controldir.create_branch()
683
if force_new_tree or (repo.make_working_trees() and
684
force_new_tree is None):
686
controldir.create_workingtree()
687
except errors.NotLocalUrl:
692
def create_standalone_workingtree(klass, base, format=None):
693
"""Create a new ControlDir, WorkingTree, Branch and Repository at 'base'.
695
'base' must be a local path or a file:// url.
697
This will use the current default ControlDirFormat unless one is
698
specified, and use whatever
699
repository format that that uses for bzrdirformat.create_workingtree,
700
create_branch and create_repository.
702
:param format: Override for the controldir format to create.
703
:return: The WorkingTree object.
705
t = _mod_transport.get_transport(base)
706
if not isinstance(t, local.LocalTransport):
707
raise errors.NotLocalUrl(base)
708
controldir = klass.create_branch_and_repo(base,
710
format=format).controldir
711
return controldir.create_workingtree()
714
def open_unsupported(klass, base):
715
"""Open a branch which is not supported."""
716
return klass.open(base, _unsupported=True)
719
def open(klass, base, possible_transports=None, probers=None,
721
"""Open an existing controldir, rooted at 'base' (url).
723
:param _unsupported: a private parameter to the ControlDir class.
725
t = _mod_transport.get_transport(base, possible_transports)
726
return klass.open_from_transport(t, probers=probers,
727
_unsupported=_unsupported)
730
def open_from_transport(klass, transport, _unsupported=False,
732
"""Open a controldir within a particular directory.
734
:param transport: Transport containing the controldir.
735
:param _unsupported: private.
737
for hook in klass.hooks['pre_open']:
739
# Keep initial base since 'transport' may be modified while following
741
base = transport.base
743
def find_format(transport):
744
return transport, ControlDirFormat.find_format(transport,
747
def redirected(transport, e, redirection_notice):
748
redirected_transport = transport._redirected_to(e.source, e.target)
749
if redirected_transport is None:
750
raise errors.NotBranchError(base)
751
trace.note(gettext('{0} is{1} redirected to {2}').format(
752
transport.base, e.permanently, redirected_transport.base))
753
return redirected_transport
756
transport, format = _mod_transport.do_catching_redirections(
757
find_format, transport, redirected)
758
except errors.TooManyRedirections:
759
raise errors.NotBranchError(base)
761
format.check_support_status(_unsupported)
762
return format.open(transport, _found=True)
765
def open_containing(klass, url, possible_transports=None):
766
"""Open an existing branch which contains url.
768
:param url: url to search from.
770
See open_containing_from_transport for more detail.
772
transport = _mod_transport.get_transport(url, possible_transports)
773
return klass.open_containing_from_transport(transport)
776
def open_containing_from_transport(klass, a_transport):
777
"""Open an existing branch which contains a_transport.base.
779
This probes for a branch at a_transport, and searches upwards from there.
781
Basically we keep looking up until we find the control directory or
782
run into the root. If there isn't one, raises NotBranchError.
783
If there is one and it is either an unrecognised format or an unsupported
784
format, UnknownFormatError or UnsupportedFormatError are raised.
785
If there is one, it is returned, along with the unused portion of url.
787
:return: The ControlDir that contains the path, and a Unicode path
788
for the rest of the URL.
790
# this gets the normalised url back. I.e. '.' -> the full path.
791
url = a_transport.base
794
result = klass.open_from_transport(a_transport)
795
return result, urlutils.unescape(a_transport.relpath(url))
796
except errors.NotBranchError:
798
except errors.PermissionDenied:
801
new_t = a_transport.clone('..')
802
except urlutils.InvalidURLJoin:
803
# reached the root, whatever that may be
804
raise errors.NotBranchError(path=url)
805
if new_t.base == a_transport.base:
806
# reached the root, whatever that may be
807
raise errors.NotBranchError(path=url)
811
def open_tree_or_branch(klass, location, name=None):
812
"""Return the branch and working tree at a location.
814
If there is no tree at the location, tree will be None.
815
If there is no branch at the location, an exception will be
817
:return: (tree, branch)
819
controldir = klass.open(location)
820
return controldir._get_tree_branch(name=name)
823
def open_containing_tree_or_branch(klass, location,
824
possible_transports=None):
825
"""Return the branch and working tree contained by a location.
827
Returns (tree, branch, relpath).
828
If there is no tree at containing the location, tree will be None.
829
If there is no branch containing the location, an exception will be
831
relpath is the portion of the path that is contained by the branch.
833
controldir, relpath = klass.open_containing(location,
834
possible_transports=possible_transports)
835
tree, branch = controldir._get_tree_branch()
836
return tree, branch, relpath
839
def open_containing_tree_branch_or_repository(klass, location):
840
"""Return the working tree, branch and repo contained by a location.
842
Returns (tree, branch, repository, relpath).
843
If there is no tree containing the location, tree will be None.
844
If there is no branch containing the location, branch will be None.
845
If there is no repository containing the location, repository will be
847
relpath is the portion of the path that is contained by the innermost
850
If no tree, branch or repository is found, a NotBranchError is raised.
852
controldir, relpath = klass.open_containing(location)
854
tree, branch = controldir._get_tree_branch()
855
except errors.NotBranchError:
857
repo = controldir.find_repository()
858
return None, None, repo, relpath
859
except (errors.NoRepositoryPresent):
860
raise errors.NotBranchError(location)
861
return tree, branch, branch.repository, relpath
864
def create(klass, base, format=None, possible_transports=None):
865
"""Create a new ControlDir at the url 'base'.
867
:param format: If supplied, the format of branch to create. If not
868
supplied, the default is used.
869
:param possible_transports: If supplied, a list of transports that
870
can be reused to share a remote connection.
872
if klass is not ControlDir:
873
raise AssertionError("ControlDir.create always creates the"
874
"default format, not one of %r" % klass)
875
t = _mod_transport.get_transport(base, possible_transports)
878
format = ControlDirFormat.get_default_format()
879
return format.initialize_on_transport(t)
882
class ControlDirHooks(hooks.Hooks):
883
"""Hooks for ControlDir operations."""
886
"""Create the default hooks."""
887
hooks.Hooks.__init__(self, "breezy.controldir", "ControlDir.hooks")
888
self.add_hook('pre_open',
889
"Invoked before attempting to open a ControlDir with the transport "
890
"that the open will use.", (1, 14))
891
self.add_hook('post_repo_init',
892
"Invoked after a repository has been initialized. "
893
"post_repo_init is called with a "
894
"breezy.controldir.RepoInitHookParams.",
898
# install the default hooks
899
ControlDir.hooks = ControlDirHooks()
902
class ControlComponentFormat(object):
903
"""A component that can live inside of a control directory."""
905
upgrade_recommended = False
907
def get_format_description(self):
908
"""Return the short description for this format."""
909
raise NotImplementedError(self.get_format_description)
911
def is_supported(self):
912
"""Is this format supported?
914
Supported formats must be initializable and openable.
915
Unsupported formats may not support initialization or committing or
916
some other features depending on the reason for not being supported.
920
def check_support_status(self, allow_unsupported, recommend_upgrade=True,
922
"""Give an error or warning on old formats.
924
:param allow_unsupported: If true, allow opening
925
formats that are strongly deprecated, and which may
926
have limited functionality.
928
:param recommend_upgrade: If true (default), warn
929
the user through the ui object that they may wish
930
to upgrade the object.
932
if not allow_unsupported and not self.is_supported():
933
# see open_downlevel to open legacy branches.
934
raise errors.UnsupportedFormatError(format=self)
935
if recommend_upgrade and self.upgrade_recommended:
936
ui.ui_factory.recommend_upgrade(
937
self.get_format_description(), basedir)
940
def get_format_string(cls):
941
raise NotImplementedError(cls.get_format_string)
944
class ControlComponentFormatRegistry(registry.FormatRegistry):
945
"""A registry for control components (branch, workingtree, repository)."""
947
def __init__(self, other_registry=None):
948
super(ControlComponentFormatRegistry, self).__init__(other_registry)
949
self._extra_formats = []
951
def register(self, format):
952
"""Register a new format."""
953
super(ControlComponentFormatRegistry, self).register(
954
format.get_format_string(), format)
956
def remove(self, format):
957
"""Remove a registered format."""
958
super(ControlComponentFormatRegistry, self).remove(
959
format.get_format_string())
961
def register_extra(self, format):
962
"""Register a format that can not be used in a metadir.
964
This is mainly useful to allow custom repository formats, such as older
965
Bazaar formats and foreign formats, to be tested.
967
self._extra_formats.append(registry._ObjectGetter(format))
969
def remove_extra(self, format):
970
"""Remove an extra format.
972
self._extra_formats.remove(registry._ObjectGetter(format))
974
def register_extra_lazy(self, module_name, member_name):
975
"""Register a format lazily.
977
self._extra_formats.append(
978
registry._LazyObjectGetter(module_name, member_name))
980
def _get_extra(self):
981
"""Return getters for extra formats, not usable in meta directories."""
982
return [getter.get_obj for getter in self._extra_formats]
984
def _get_all_lazy(self):
985
"""Return getters for all formats, even those not usable in metadirs."""
986
result = [self._dict[name].get_obj for name in self.keys()]
987
result.extend(self._get_extra())
991
"""Return all formats, even those not usable in metadirs."""
993
for getter in self._get_all_lazy():
1000
def _get_all_modules(self):
1001
"""Return a set of the modules providing objects."""
1003
for name in self.keys():
1004
modules.add(self._get_module(name))
1005
for getter in self._extra_formats:
1006
modules.add(getter.get_module())
1010
class Converter(object):
1011
"""Converts a disk format object from one format to another."""
1013
def convert(self, to_convert, pb):
1014
"""Perform the conversion of to_convert, giving feedback via pb.
1016
:param to_convert: The disk object to convert.
1017
:param pb: a progress bar to use for progress information.
1020
def step(self, message):
1021
"""Update the pb by a step."""
1023
self.pb.update(message, self.count, self.total)
1026
class ControlDirFormat(object):
1027
"""An encapsulation of the initialization and open routines for a format.
1029
Formats provide three things:
1030
* An initialization routine,
1034
Formats are placed in a dict by their format string for reference
1035
during controldir opening. These should be subclasses of ControlDirFormat
1038
Once a format is deprecated, just deprecate the initialize and open
1039
methods on the format class. Do not deprecate the object, as the
1040
object will be created every system load.
1042
:cvar colocated_branches: Whether this formats supports colocated branches.
1043
:cvar supports_workingtrees: This control directory can co-exist with a
1047
_default_format = None
1048
"""The default format used for new control directories."""
1051
"""The registered format probers, e.g. BzrProber.
1053
This is a list of Prober-derived classes.
1056
colocated_branches = False
1057
"""Whether co-located branches are supported for this control dir format.
1060
supports_workingtrees = True
1061
"""Whether working trees can exist in control directories of this format.
1064
fixed_components = False
1065
"""Whether components can not change format independent of the control dir.
1068
upgrade_recommended = False
1069
"""Whether an upgrade from this format is recommended."""
1071
def get_format_description(self):
1072
"""Return the short description for this format."""
1073
raise NotImplementedError(self.get_format_description)
1075
def get_converter(self, format=None):
1076
"""Return the converter to use to convert controldirs needing converts.
1078
This returns a breezy.controldir.Converter object.
1080
This should return the best upgrader to step this format towards the
1081
current default format. In the case of plugins we can/should provide
1082
some means for them to extend the range of returnable converters.
1084
:param format: Optional format to override the default format of the
1087
raise NotImplementedError(self.get_converter)
1089
def is_supported(self):
1090
"""Is this format supported?
1092
Supported formats must be openable.
1093
Unsupported formats may not support initialization or committing or
1094
some other features depending on the reason for not being supported.
1098
def is_initializable(self):
1099
"""Whether new control directories of this format can be initialized.
1101
return self.is_supported()
1103
def check_support_status(self, allow_unsupported, recommend_upgrade=True,
1105
"""Give an error or warning on old formats.
1107
:param allow_unsupported: If true, allow opening
1108
formats that are strongly deprecated, and which may
1109
have limited functionality.
1111
:param recommend_upgrade: If true (default), warn
1112
the user through the ui object that they may wish
1113
to upgrade the object.
1115
if not allow_unsupported and not self.is_supported():
1116
# see open_downlevel to open legacy branches.
1117
raise errors.UnsupportedFormatError(format=self)
1118
if recommend_upgrade and self.upgrade_recommended:
1119
ui.ui_factory.recommend_upgrade(
1120
self.get_format_description(), basedir)
1122
def same_model(self, target_format):
1123
return (self.repository_format.rich_root_data ==
1124
target_format.rich_root_data)
1127
def register_prober(klass, prober):
1128
"""Register a prober that can look for a control dir.
1131
klass._probers.append(prober)
1134
def unregister_prober(klass, prober):
1135
"""Unregister a prober.
1138
klass._probers.remove(prober)
1142
return self.get_format_description().rstrip()
1145
def all_probers(klass):
1146
return klass._probers
1149
def known_formats(klass):
1150
"""Return all the known formats.
1153
for prober_kls in klass.all_probers():
1154
result.extend(prober_kls.known_formats())
1158
def find_format(klass, transport, probers=None):
1159
"""Return the format present at transport."""
1162
klass.all_probers(),
1163
key=lambda prober: prober.priority(transport))
1164
for prober_kls in probers:
1165
prober = prober_kls()
1167
return prober.probe_transport(transport)
1168
except errors.NotBranchError:
1169
# this format does not find a control dir here.
1171
raise errors.NotBranchError(path=transport.base)
1173
def initialize(self, url, possible_transports=None):
1174
"""Create a control dir at this url and return an opened copy.
1176
While not deprecated, this method is very specific and its use will
1177
lead to many round trips to setup a working environment. See
1178
initialize_on_transport_ex for a [nearly] all-in-one method.
1180
Subclasses should typically override initialize_on_transport
1181
instead of this method.
1183
return self.initialize_on_transport(
1184
_mod_transport.get_transport(url, possible_transports))
1186
def initialize_on_transport(self, transport):
1187
"""Initialize a new controldir in the base directory of a Transport."""
1188
raise NotImplementedError(self.initialize_on_transport)
1190
def initialize_on_transport_ex(self, transport, use_existing_dir=False,
1191
create_prefix=False, force_new_repo=False, stacked_on=None,
1192
stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
1193
shared_repo=False, vfs_only=False):
1194
"""Create this format on transport.
1196
The directory to initialize will be created.
1198
:param force_new_repo: Do not use a shared repository for the target,
1199
even if one is available.
1200
:param create_prefix: Create any missing directories leading up to
1202
:param use_existing_dir: Use an existing directory if one exists.
1203
:param stacked_on: A url to stack any created branch on, None to follow
1204
any target stacking policy.
1205
:param stack_on_pwd: If stack_on is relative, the location it is
1207
:param repo_format_name: If non-None, a repository will be
1208
made-or-found. Should none be found, or if force_new_repo is True
1209
the repo_format_name is used to select the format of repository to
1211
:param make_working_trees: Control the setting of make_working_trees
1212
for a new shared repository when one is made. None to use whatever
1213
default the format has.
1214
:param shared_repo: Control whether made repositories are shared or
1216
:param vfs_only: If True do not attempt to use a smart server
1217
:return: repo, controldir, require_stacking, repository_policy. repo is
1218
None if none was created or found, controldir is always valid.
1219
require_stacking is the result of examining the stacked_on
1220
parameter and any stacking policy found for the target.
1222
raise NotImplementedError(self.initialize_on_transport_ex)
1224
def network_name(self):
1225
"""A simple byte string uniquely identifying this format for RPC calls.
1227
Bzr control formats use this disk format string to identify the format
1228
over the wire. Its possible that other control formats have more
1229
complex detection requirements, so we permit them to use any unique and
1230
immutable string they desire.
1232
raise NotImplementedError(self.network_name)
1234
def open(self, transport, _found=False):
1235
"""Return an instance of this format for the dir transport points at.
1237
raise NotImplementedError(self.open)
1240
def _set_default_format(klass, format):
1241
"""Set default format (for testing behavior of defaults only)"""
1242
klass._default_format = format
1245
def get_default_format(klass):
1246
"""Return the current default format."""
1247
return klass._default_format
1249
def supports_transport(self, transport):
1250
"""Check if this format can be opened over a particular transport.
1252
raise NotImplementedError(self.supports_transport)
1255
def is_control_filename(klass, filename):
1256
"""True if filename is the name of a path which is reserved for
1259
:param filename: A filename within the root transport of this
1262
This is true IF and ONLY IF the filename is part of the namespace reserved
1263
for bzr control dirs. Currently this is the '.bzr' directory in the root
1264
of the root_transport. it is expected that plugins will need to extend
1265
this in the future - for instance to make bzr talk with svn working
1268
raise NotImplementedError(self.is_control_filename)
1271
class Prober(object):
1272
"""Abstract class that can be used to detect a particular kind of
1275
At the moment this just contains a single method to probe a particular
1276
transport, but it may be extended in the future to e.g. avoid
1277
multiple levels of probing for Subversion repositories.
1279
See BzrProber and RemoteBzrProber in breezy.bzrdir for the
1280
probers that detect .bzr/ directories and Bazaar smart servers,
1283
Probers should be registered using the register_prober methods on
1287
def probe_transport(self, transport):
1288
"""Return the controldir style format present in a directory.
1290
:raise UnknownFormatError: If a control dir was found but is
1291
in an unknown format.
1292
:raise NotBranchError: If no control directory was found.
1293
:return: A ControlDirFormat instance.
1295
raise NotImplementedError(self.probe_transport)
1298
def known_formats(klass):
1299
"""Return the control dir formats known by this prober.
1301
Multiple probers can return the same formats, so this should
1304
:return: A set of known formats.
1306
raise NotImplementedError(klass.known_formats)
1309
def priority(klass, transport):
1310
"""Priority of this prober.
1312
A lower value means the prober gets checked first.
1316
-10: This is a "server" prober
1318
10: This is a regular file-based prober
1319
100: This is a prober for an unsupported format
1324
class ControlDirFormatInfo(object):
1326
def __init__(self, native, deprecated, hidden, experimental):
1327
self.deprecated = deprecated
1328
self.native = native
1329
self.hidden = hidden
1330
self.experimental = experimental
1333
class ControlDirFormatRegistry(registry.Registry):
1334
"""Registry of user-selectable ControlDir subformats.
1336
Differs from ControlDirFormat._formats in that it provides sub-formats,
1337
e.g. BzrDirMeta1 with weave repository. Also, it's more user-oriented.
1341
"""Create a ControlDirFormatRegistry."""
1342
self._registration_order = list()
1343
super(ControlDirFormatRegistry, self).__init__()
1345
def register(self, key, factory, help, native=True, deprecated=False,
1346
hidden=False, experimental=False):
1347
"""Register a ControlDirFormat factory.
1349
The factory must be a callable that takes one parameter: the key.
1350
It must produce an instance of the ControlDirFormat when called.
1352
This function mainly exists to prevent the info object from being
1355
registry.Registry.register(self, key, factory, help,
1356
ControlDirFormatInfo(native, deprecated, hidden, experimental))
1357
self._registration_order.append(key)
1359
def register_alias(self, key, target, hidden=False):
1360
"""Register a format alias.
1362
:param key: Alias name
1363
:param target: Target format
1364
:param hidden: Whether the alias is hidden
1366
info = self.get_info(target)
1367
registry.Registry.register_alias(self, key, target,
1368
ControlDirFormatInfo(
1369
native=info.native, deprecated=info.deprecated,
1370
hidden=hidden, experimental=info.experimental))
1372
def register_lazy(self, key, module_name, member_name, help, native=True,
1373
deprecated=False, hidden=False, experimental=False):
1374
registry.Registry.register_lazy(self, key, module_name, member_name,
1375
help, ControlDirFormatInfo(native, deprecated, hidden, experimental))
1376
self._registration_order.append(key)
1378
def set_default(self, key):
1379
"""Set the 'default' key to be a clone of the supplied key.
1381
This method must be called once and only once.
1383
self.register_alias('default', key)
1385
def set_default_repository(self, key):
1386
"""Set the FormatRegistry default and Repository default.
1388
This is a transitional method while Repository.set_default_format
1391
if 'default' in self:
1392
self.remove('default')
1393
self.set_default(key)
1394
format = self.get('default')()
1396
def make_controldir(self, key):
1397
return self.get(key)()
1399
def help_topic(self, topic):
1401
default_realkey = None
1402
default_help = self.get_help('default')
1404
for key in self._registration_order:
1405
if key == 'default':
1407
help = self.get_help(key)
1408
if help == default_help:
1409
default_realkey = key
1411
help_pairs.append((key, help))
1413
def wrapped(key, help, info):
1415
help = '(native) ' + help
1416
return ':%s:\n%s\n\n' % (key,
1417
textwrap.fill(help, initial_indent=' ',
1418
subsequent_indent=' ',
1419
break_long_words=False))
1420
if default_realkey is not None:
1421
output += wrapped(default_realkey, '(default) %s' % default_help,
1422
self.get_info('default'))
1423
deprecated_pairs = []
1424
experimental_pairs = []
1425
for key, help in help_pairs:
1426
info = self.get_info(key)
1429
elif info.deprecated:
1430
deprecated_pairs.append((key, help))
1431
elif info.experimental:
1432
experimental_pairs.append((key, help))
1434
output += wrapped(key, help, info)
1435
output += "\nSee :doc:`formats-help` for more about storage formats."
1437
if len(experimental_pairs) > 0:
1438
other_output += "Experimental formats are shown below.\n\n"
1439
for key, help in experimental_pairs:
1440
info = self.get_info(key)
1441
other_output += wrapped(key, help, info)
1444
"No experimental formats are available.\n\n"
1445
if len(deprecated_pairs) > 0:
1446
other_output += "\nDeprecated formats are shown below.\n\n"
1447
for key, help in deprecated_pairs:
1448
info = self.get_info(key)
1449
other_output += wrapped(key, help, info)
1452
"\nNo deprecated formats are available.\n\n"
1454
"\nSee :doc:`formats-help` for more about storage formats."
1456
if topic == 'other-formats':
1462
class RepoInitHookParams(object):
1463
"""Object holding parameters passed to `*_repo_init` hooks.
1465
There are 4 fields that hooks may wish to access:
1467
:ivar repository: Repository created
1468
:ivar format: Repository format
1469
:ivar bzrdir: The controldir for the repository
1470
:ivar shared: The repository is shared
1473
def __init__(self, repository, format, controldir, shared):
1474
"""Create a group of RepoInitHook parameters.
1476
:param repository: Repository created
1477
:param format: Repository format
1478
:param controldir: The controldir for the repository
1479
:param shared: The repository is shared
1481
self.repository = repository
1482
self.format = format
1483
self.controldir = controldir
1484
self.shared = shared
1486
def __eq__(self, other):
1487
return self.__dict__ == other.__dict__
1491
return "<%s for %s>" % (self.__class__.__name__,
1494
return "<%s for %s>" % (self.__class__.__name__,
1498
def is_control_filename(filename):
1499
"""Check if filename is used for control directories."""
1500
# TODO(jelmer): Instead, have a function that returns all control
1502
for key, format in format_registry.items():
1503
if format().is_control_filename(filename):
1509
class RepositoryAcquisitionPolicy(object):
1510
"""Abstract base class for repository acquisition policies.
1512
A repository acquisition policy decides how a ControlDir acquires a repository
1513
for a branch that is being created. The most basic policy decision is
1514
whether to create a new repository or use an existing one.
1517
def __init__(self, stack_on, stack_on_pwd, require_stacking):
1520
:param stack_on: A location to stack on
1521
:param stack_on_pwd: If stack_on is relative, the location it is
1523
:param require_stacking: If True, it is a failure to not stack.
1525
self._stack_on = stack_on
1526
self._stack_on_pwd = stack_on_pwd
1527
self._require_stacking = require_stacking
1529
def configure_branch(self, branch):
1530
"""Apply any configuration data from this policy to the branch.
1532
Default implementation sets repository stacking.
1534
if self._stack_on is None:
1536
if self._stack_on_pwd is None:
1537
stack_on = self._stack_on
1540
stack_on = urlutils.rebase_url(self._stack_on,
1543
except urlutils.InvalidRebaseURLs:
1544
stack_on = self._get_full_stack_on()
1546
branch.set_stacked_on_url(stack_on)
1547
except (_mod_branch.UnstackableBranchFormat,
1548
errors.UnstackableRepositoryFormat):
1549
if self._require_stacking:
1552
def requires_stacking(self):
1553
"""Return True if this policy requires stacking."""
1554
return self._stack_on is not None and self._require_stacking
1556
def _get_full_stack_on(self):
1557
"""Get a fully-qualified URL for the stack_on location."""
1558
if self._stack_on is None:
1560
if self._stack_on_pwd is None:
1561
return self._stack_on
1563
return urlutils.join(self._stack_on_pwd, self._stack_on)
1565
def _add_fallback(self, repository, possible_transports=None):
1566
"""Add a fallback to the supplied repository, if stacking is set."""
1567
stack_on = self._get_full_stack_on()
1568
if stack_on is None:
1571
stacked_dir = ControlDir.open(
1572
stack_on, possible_transports=possible_transports)
1573
except errors.JailBreak:
1574
# We keep the stacking details, but we are in the server code so
1575
# actually stacking is not needed.
1578
stacked_repo = stacked_dir.open_branch().repository
1579
except errors.NotBranchError:
1580
stacked_repo = stacked_dir.open_repository()
1582
repository.add_fallback_repository(stacked_repo)
1583
except errors.UnstackableRepositoryFormat:
1584
if self._require_stacking:
1587
self._require_stacking = True
1589
def acquire_repository(self, make_working_trees=None, shared=False,
1590
possible_transports=None):
1591
"""Acquire a repository for this controlrdir.
1593
Implementations may create a new repository or use a pre-exising
1596
:param make_working_trees: If creating a repository, set
1597
make_working_trees to this value (if non-None)
1598
:param shared: If creating a repository, make it shared if True
1599
:return: A repository, is_new_flag (True if the repository was
1602
raise NotImplementedError(
1603
RepositoryAcquisitionPolicy.acquire_repository)
1606
# Please register new formats after old formats so that formats
1607
# appear in chronological order and format descriptions can build
1609
format_registry = ControlDirFormatRegistry()
1611
network_format_registry = registry.FormatRegistry()
1612
"""Registry of formats indexed by their network name.
1614
The network name for a ControlDirFormat is an identifier that can be used when
1615
referring to formats with smart server operations. See
1616
ControlDirFormat.network_name() for more detail.