1
# Copyright (C) 2006-2011 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""BzrDir logic. The BzrDir is the basic control directory used by bzr.
19
At format 7 this was split out into Branch, Repository and Checkout control
22
Note: This module has a lot of ``open`` functions/methods that return
23
references to in-memory objects. As a rule, there are no matching ``close``
24
methods. To free any associated resources, simply stop referencing the
28
# TODO: Move old formats into a plugin to make this file smaller.
34
from bzrlib.lazy_import import lazy_import
35
lazy_import(globals(), """
36
from stat import S_ISDIR
51
revision as _mod_revision,
52
transport as _mod_transport,
62
from bzrlib.osutils import (
65
from bzrlib.push import (
68
from bzrlib.repofmt import pack_repo
69
from bzrlib.smart.client import _SmartClient
70
from bzrlib.store.versioned import VersionedFileStore
71
from bzrlib.transactions import WriteTransaction
72
from bzrlib.transport import (
73
do_catching_redirections,
76
from bzrlib.weave import (
82
from bzrlib.trace import (
93
from bzrlib.symbol_versioning import (
99
class BzrDir(controldir.ControlDir):
100
"""A .bzr control diretory.
102
BzrDir instances let you create or open any of the things that can be
103
found within .bzr - checkouts, branches and repositories.
106
the transport which this bzr dir is rooted at (i.e. file:///.../.bzr/)
107
:ivar root_transport:
108
a transport connected to the directory this bzr was opened from
109
(i.e. the parent directory holding the .bzr directory).
111
Everything in the bzrdir should have the same file permissions.
113
:cvar hooks: An instance of BzrDirHooks.
116
def break_lock(self):
117
"""Invoke break_lock on the first object in the bzrdir.
119
If there is a tree, the tree is opened and break_lock() called.
120
Otherwise, branch is tried, and finally repository.
122
# XXX: This seems more like a UI function than something that really
123
# belongs in this class.
125
thing_to_unlock = self.open_workingtree()
126
except (errors.NotLocalUrl, errors.NoWorkingTree):
128
thing_to_unlock = self.open_branch()
129
except errors.NotBranchError:
131
thing_to_unlock = self.open_repository()
132
except errors.NoRepositoryPresent:
134
thing_to_unlock.break_lock()
136
def check_conversion_target(self, target_format):
137
"""Check that a bzrdir as a whole can be converted to a new format."""
138
# The only current restriction is that the repository content can be
139
# fetched compatibly with the target.
140
target_repo_format = target_format.repository_format
142
self.open_repository()._format.check_conversion_target(
144
except errors.NoRepositoryPresent:
145
# No repo, no problem.
149
def _check_supported(format, allow_unsupported,
150
recommend_upgrade=True,
152
"""Give an error or warning on old formats.
154
:param format: may be any kind of format - workingtree, branch,
157
:param allow_unsupported: If true, allow opening
158
formats that are strongly deprecated, and which may
159
have limited functionality.
161
:param recommend_upgrade: If true (default), warn
162
the user through the ui object that they may wish
163
to upgrade the object.
165
# TODO: perhaps move this into a base Format class; it's not BzrDir
166
# specific. mbp 20070323
167
if not allow_unsupported and not format.is_supported():
168
# see open_downlevel to open legacy branches.
169
raise errors.UnsupportedFormatError(format=format)
170
if recommend_upgrade \
171
and getattr(format, 'upgrade_recommended', False):
172
ui.ui_factory.recommend_upgrade(
173
format.get_format_description(),
176
def clone_on_transport(self, transport, revision_id=None,
177
force_new_repo=False, preserve_stacking=False, stacked_on=None,
178
create_prefix=False, use_existing_dir=True, no_tree=False):
179
"""Clone this bzrdir and its contents to transport verbatim.
181
:param transport: The transport for the location to produce the clone
182
at. If the target directory does not exist, it will be created.
183
:param revision_id: The tip revision-id to use for any branch or
184
working tree. If not None, then the clone operation may tune
185
itself to download less data.
186
:param force_new_repo: Do not use a shared repository for the target,
187
even if one is available.
188
:param preserve_stacking: When cloning a stacked branch, stack the
189
new branch on top of the other branch's stacked-on branch.
190
:param create_prefix: Create any missing directories leading up to
192
:param use_existing_dir: Use an existing directory if one exists.
193
:param no_tree: If set to true prevents creation of a working tree.
195
# Overview: put together a broad description of what we want to end up
196
# with; then make as few api calls as possible to do it.
198
# We may want to create a repo/branch/tree, if we do so what format
199
# would we want for each:
200
require_stacking = (stacked_on is not None)
201
format = self.cloning_metadir(require_stacking)
203
# Figure out what objects we want:
205
local_repo = self.find_repository()
206
except errors.NoRepositoryPresent:
209
local_branch = self.open_branch()
210
except errors.NotBranchError:
213
# enable fallbacks when branch is not a branch reference
214
if local_branch.repository.has_same_location(local_repo):
215
local_repo = local_branch.repository
216
if preserve_stacking:
218
stacked_on = local_branch.get_stacked_on_url()
219
except (errors.UnstackableBranchFormat,
220
errors.UnstackableRepositoryFormat,
223
# Bug: We create a metadir without knowing if it can support stacking,
224
# we should look up the policy needs first, or just use it as a hint,
227
make_working_trees = local_repo.make_working_trees() and not no_tree
228
want_shared = local_repo.is_shared()
229
repo_format_name = format.repository_format.network_name()
231
make_working_trees = False
233
repo_format_name = None
235
result_repo, result, require_stacking, repository_policy = \
236
format.initialize_on_transport_ex(transport,
237
use_existing_dir=use_existing_dir, create_prefix=create_prefix,
238
force_new_repo=force_new_repo, stacked_on=stacked_on,
239
stack_on_pwd=self.root_transport.base,
240
repo_format_name=repo_format_name,
241
make_working_trees=make_working_trees, shared_repo=want_shared)
244
# If the result repository is in the same place as the
245
# resulting bzr dir, it will have no content, further if the
246
# result is not stacked then we know all content should be
247
# copied, and finally if we are copying up to a specific
248
# revision_id then we can use the pending-ancestry-result which
249
# does not require traversing all of history to describe it.
250
if (result_repo.user_url == result.user_url
251
and not require_stacking and
252
revision_id is not None):
253
fetch_spec = graph.PendingAncestryResult(
254
[revision_id], local_repo)
255
result_repo.fetch(local_repo, fetch_spec=fetch_spec)
257
result_repo.fetch(local_repo, revision_id=revision_id)
261
if result_repo is not None:
262
raise AssertionError('result_repo not None(%r)' % result_repo)
263
# 1 if there is a branch present
264
# make sure its content is available in the target repository
266
if local_branch is not None:
267
result_branch = local_branch.clone(result, revision_id=revision_id,
268
repository_policy=repository_policy)
270
# Cheaper to check if the target is not local, than to try making
272
result.root_transport.local_abspath('.')
273
if result_repo is None or result_repo.make_working_trees():
274
self.open_workingtree().clone(result)
275
except (errors.NoWorkingTree, errors.NotLocalUrl):
279
# TODO: This should be given a Transport, and should chdir up; otherwise
280
# this will open a new connection.
281
def _make_tail(self, url):
282
t = _mod_transport.get_transport(url)
286
def find_bzrdirs(transport, evaluate=None, list_current=None):
287
"""Find bzrdirs recursively from current location.
289
This is intended primarily as a building block for more sophisticated
290
functionality, like finding trees under a directory, or finding
291
branches that use a given repository.
292
:param evaluate: An optional callable that yields recurse, value,
293
where recurse controls whether this bzrdir is recursed into
294
and value is the value to yield. By default, all bzrdirs
295
are recursed into, and the return value is the bzrdir.
296
:param list_current: if supplied, use this function to list the current
297
directory, instead of Transport.list_dir
298
:return: a generator of found bzrdirs, or whatever evaluate returns.
300
if list_current is None:
301
def list_current(transport):
302
return transport.list_dir('')
304
def evaluate(bzrdir):
307
pending = [transport]
308
while len(pending) > 0:
309
current_transport = pending.pop()
312
bzrdir = BzrDir.open_from_transport(current_transport)
313
except (errors.NotBranchError, errors.PermissionDenied):
316
recurse, value = evaluate(bzrdir)
319
subdirs = list_current(current_transport)
320
except (errors.NoSuchFile, errors.PermissionDenied):
323
for subdir in sorted(subdirs, reverse=True):
324
pending.append(current_transport.clone(subdir))
327
def find_branches(transport):
328
"""Find all branches under a transport.
330
This will find all branches below the transport, including branches
331
inside other branches. Where possible, it will use
332
Repository.find_branches.
334
To list all the branches that use a particular Repository, see
335
Repository.find_branches
337
def evaluate(bzrdir):
339
repository = bzrdir.open_repository()
340
except errors.NoRepositoryPresent:
343
return False, ([], repository)
344
return True, (bzrdir.list_branches(), None)
346
for branches, repo in BzrDir.find_bzrdirs(transport,
349
ret.extend(repo.find_branches())
350
if branches is not None:
355
def create_branch_and_repo(base, force_new_repo=False, format=None):
356
"""Create a new BzrDir, Branch and Repository at the url 'base'.
358
This will use the current default BzrDirFormat unless one is
359
specified, and use whatever
360
repository format that that uses via bzrdir.create_branch and
361
create_repository. If a shared repository is available that is used
364
The created Branch object is returned.
366
:param base: The URL to create the branch at.
367
:param force_new_repo: If True a new repository is always created.
368
:param format: If supplied, the format of branch to create. If not
369
supplied, the default is used.
371
bzrdir = BzrDir.create(base, format)
372
bzrdir._find_or_create_repository(force_new_repo)
373
return bzrdir.create_branch()
375
def determine_repository_policy(self, force_new_repo=False, stack_on=None,
376
stack_on_pwd=None, require_stacking=False):
377
"""Return an object representing a policy to use.
379
This controls whether a new repository is created, and the format of
380
that repository, or some existing shared repository used instead.
382
If stack_on is supplied, will not seek a containing shared repo.
384
:param force_new_repo: If True, require a new repository to be created.
385
:param stack_on: If supplied, the location to stack on. If not
386
supplied, a default_stack_on location may be used.
387
:param stack_on_pwd: If stack_on is relative, the location it is
390
def repository_policy(found_bzrdir):
393
config = found_bzrdir.get_config()
395
stack_on = config.get_default_stack_on()
396
if stack_on is not None:
397
stack_on_pwd = found_bzrdir.user_url
399
# does it have a repository ?
401
repository = found_bzrdir.open_repository()
402
except errors.NoRepositoryPresent:
405
if (found_bzrdir.user_url != self.user_url
406
and not repository.is_shared()):
407
# Don't look higher, can't use a higher shared repo.
415
return UseExistingRepository(repository, stack_on,
416
stack_on_pwd, require_stacking=require_stacking), True
418
return CreateRepository(self, stack_on, stack_on_pwd,
419
require_stacking=require_stacking), True
421
if not force_new_repo:
423
policy = self._find_containing(repository_policy)
424
if policy is not None:
428
return UseExistingRepository(self.open_repository(),
429
stack_on, stack_on_pwd,
430
require_stacking=require_stacking)
431
except errors.NoRepositoryPresent:
433
return CreateRepository(self, stack_on, stack_on_pwd,
434
require_stacking=require_stacking)
436
def _find_or_create_repository(self, force_new_repo):
437
"""Create a new repository if needed, returning the repository."""
438
policy = self.determine_repository_policy(force_new_repo)
439
return policy.acquire_repository()[0]
442
def create_branch_convenience(base, force_new_repo=False,
443
force_new_tree=None, format=None,
444
possible_transports=None):
445
"""Create a new BzrDir, Branch and Repository at the url 'base'.
447
This is a convenience function - it will use an existing repository
448
if possible, can be told explicitly whether to create a working tree or
451
This will use the current default BzrDirFormat unless one is
452
specified, and use whatever
453
repository format that that uses via bzrdir.create_branch and
454
create_repository. If a shared repository is available that is used
455
preferentially. Whatever repository is used, its tree creation policy
458
The created Branch object is returned.
459
If a working tree cannot be made due to base not being a file:// url,
460
no error is raised unless force_new_tree is True, in which case no
461
data is created on disk and NotLocalUrl is raised.
463
:param base: The URL to create the branch at.
464
:param force_new_repo: If True a new repository is always created.
465
:param force_new_tree: If True or False force creation of a tree or
466
prevent such creation respectively.
467
:param format: Override for the bzrdir format to create.
468
:param possible_transports: An optional reusable transports list.
471
# check for non local urls
472
t = _mod_transport.get_transport(base, possible_transports)
473
if not isinstance(t, local.LocalTransport):
474
raise errors.NotLocalUrl(base)
475
bzrdir = BzrDir.create(base, format, possible_transports)
476
repo = bzrdir._find_or_create_repository(force_new_repo)
477
result = bzrdir.create_branch()
478
if force_new_tree or (repo.make_working_trees() and
479
force_new_tree is None):
481
bzrdir.create_workingtree()
482
except errors.NotLocalUrl:
487
def create_standalone_workingtree(base, format=None):
488
"""Create a new BzrDir, WorkingTree, Branch and Repository at 'base'.
490
'base' must be a local path or a file:// url.
492
This will use the current default BzrDirFormat unless one is
493
specified, and use whatever
494
repository format that that uses for bzrdirformat.create_workingtree,
495
create_branch and create_repository.
497
:param format: Override for the bzrdir format to create.
498
:return: The WorkingTree object.
500
t = _mod_transport.get_transport(base)
501
if not isinstance(t, local.LocalTransport):
502
raise errors.NotLocalUrl(base)
503
bzrdir = BzrDir.create_branch_and_repo(base,
505
format=format).bzrdir
506
return bzrdir.create_workingtree()
508
@deprecated_method(deprecated_in((2, 3, 0)))
509
def generate_backup_name(self, base):
510
return self._available_backup_name(base)
512
def _available_backup_name(self, base):
513
"""Find a non-existing backup file name based on base.
515
See bzrlib.osutils.available_backup_name about race conditions.
517
return osutils.available_backup_name(base, self.root_transport.has)
519
def backup_bzrdir(self):
520
"""Backup this bzr control directory.
522
:return: Tuple with old path name and new path name
525
pb = ui.ui_factory.nested_progress_bar()
527
old_path = self.root_transport.abspath('.bzr')
528
backup_dir = self._available_backup_name('backup.bzr')
529
new_path = self.root_transport.abspath(backup_dir)
530
ui.ui_factory.note('making backup of %s\n to %s'
531
% (old_path, new_path,))
532
self.root_transport.copy_tree('.bzr', backup_dir)
533
return (old_path, new_path)
537
def retire_bzrdir(self, limit=10000):
538
"""Permanently disable the bzrdir.
540
This is done by renaming it to give the user some ability to recover
541
if there was a problem.
543
This will have horrible consequences if anyone has anything locked or
545
:param limit: number of times to retry
550
to_path = '.bzr.retired.%d' % i
551
self.root_transport.rename('.bzr', to_path)
552
note("renamed %s to %s"
553
% (self.root_transport.abspath('.bzr'), to_path))
555
except (errors.TransportError, IOError, errors.PathError):
562
def _find_containing(self, evaluate):
563
"""Find something in a containing control directory.
565
This method will scan containing control dirs, until it finds what
566
it is looking for, decides that it will never find it, or runs out
567
of containing control directories to check.
569
It is used to implement find_repository and
570
determine_repository_policy.
572
:param evaluate: A function returning (value, stop). If stop is True,
573
the value will be returned.
577
result, stop = evaluate(found_bzrdir)
580
next_transport = found_bzrdir.root_transport.clone('..')
581
if (found_bzrdir.user_url == next_transport.base):
582
# top of the file system
584
# find the next containing bzrdir
586
found_bzrdir = BzrDir.open_containing_from_transport(
588
except errors.NotBranchError:
591
def find_repository(self):
592
"""Find the repository that should be used.
594
This does not require a branch as we use it to find the repo for
595
new branches as well as to hook existing branches up to their
598
def usable_repository(found_bzrdir):
599
# does it have a repository ?
601
repository = found_bzrdir.open_repository()
602
except errors.NoRepositoryPresent:
604
if found_bzrdir.user_url == self.user_url:
605
return repository, True
606
elif repository.is_shared():
607
return repository, True
611
found_repo = self._find_containing(usable_repository)
612
if found_repo is None:
613
raise errors.NoRepositoryPresent(self)
616
def _find_creation_modes(self):
617
"""Determine the appropriate modes for files and directories.
619
They're always set to be consistent with the base directory,
620
assuming that this transport allows setting modes.
622
# TODO: Do we need or want an option (maybe a config setting) to turn
623
# this off or override it for particular locations? -- mbp 20080512
624
if self._mode_check_done:
626
self._mode_check_done = True
628
st = self.transport.stat('.')
629
except errors.TransportNotPossible:
630
self._dir_mode = None
631
self._file_mode = None
633
# Check the directory mode, but also make sure the created
634
# directories and files are read-write for this user. This is
635
# mostly a workaround for filesystems which lie about being able to
636
# write to a directory (cygwin & win32)
637
if (st.st_mode & 07777 == 00000):
638
# FTP allows stat but does not return dir/file modes
639
self._dir_mode = None
640
self._file_mode = None
642
self._dir_mode = (st.st_mode & 07777) | 00700
643
# Remove the sticky and execute bits for files
644
self._file_mode = self._dir_mode & ~07111
646
def _get_file_mode(self):
647
"""Return Unix mode for newly created files, or None.
649
if not self._mode_check_done:
650
self._find_creation_modes()
651
return self._file_mode
653
def _get_dir_mode(self):
654
"""Return Unix mode for newly created directories, or None.
656
if not self._mode_check_done:
657
self._find_creation_modes()
658
return self._dir_mode
660
def get_config(self):
661
"""Get configuration for this BzrDir."""
662
return config.BzrDirConfig(self)
664
def _get_config(self):
665
"""By default, no configuration is available."""
668
def __init__(self, _transport, _format):
669
"""Initialize a Bzr control dir object.
671
Only really common logic should reside here, concrete classes should be
672
made with varying behaviours.
674
:param _format: the format that is creating this BzrDir instance.
675
:param _transport: the transport this dir is based at.
677
self._format = _format
678
# these are also under the more standard names of
679
# control_transport and user_transport
680
self.transport = _transport.clone('.bzr')
681
self.root_transport = _transport
682
self._mode_check_done = False
685
def user_transport(self):
686
return self.root_transport
689
def control_transport(self):
690
return self.transport
692
def is_control_filename(self, filename):
693
"""True if filename is the name of a path which is reserved for bzrdir's.
695
:param filename: A filename within the root transport of this bzrdir.
697
This is true IF and ONLY IF the filename is part of the namespace reserved
698
for bzr control dirs. Currently this is the '.bzr' directory in the root
699
of the root_transport.
701
# this might be better on the BzrDirFormat class because it refers to
702
# all the possible bzrdir disk formats.
703
# This method is tested via the workingtree is_control_filename tests-
704
# it was extracted from WorkingTree.is_control_filename. If the method's
705
# contract is extended beyond the current trivial implementation, please
706
# add new tests for it to the appropriate place.
707
return filename == '.bzr' or filename.startswith('.bzr/')
710
def open_unsupported(base):
711
"""Open a branch which is not supported."""
712
return BzrDir.open(base, _unsupported=True)
715
def open(base, _unsupported=False, possible_transports=None):
716
"""Open an existing bzrdir, rooted at 'base' (url).
718
:param _unsupported: a private parameter to the BzrDir class.
720
t = _mod_transport.get_transport(base, possible_transports)
721
return BzrDir.open_from_transport(t, _unsupported=_unsupported)
724
def open_from_transport(transport, _unsupported=False,
725
_server_formats=True):
726
"""Open a bzrdir within a particular directory.
728
:param transport: Transport containing the bzrdir.
729
:param _unsupported: private.
731
for hook in BzrDir.hooks['pre_open']:
733
# Keep initial base since 'transport' may be modified while following
735
base = transport.base
736
def find_format(transport):
737
return transport, controldir.ControlDirFormat.find_format(
738
transport, _server_formats=_server_formats)
740
def redirected(transport, e, redirection_notice):
741
redirected_transport = transport._redirected_to(e.source, e.target)
742
if redirected_transport is None:
743
raise errors.NotBranchError(base)
744
note('%s is%s redirected to %s',
745
transport.base, e.permanently, redirected_transport.base)
746
return redirected_transport
749
transport, format = do_catching_redirections(find_format,
752
except errors.TooManyRedirections:
753
raise errors.NotBranchError(base)
755
BzrDir._check_supported(format, _unsupported)
756
return format.open(transport, _found=True)
759
def open_containing(url, possible_transports=None):
760
"""Open an existing branch which contains url.
762
:param url: url to search from.
763
See open_containing_from_transport for more detail.
765
transport = _mod_transport.get_transport(url, possible_transports)
766
return BzrDir.open_containing_from_transport(transport)
769
def open_containing_from_transport(a_transport):
770
"""Open an existing branch which contains a_transport.base.
772
This probes for a branch at a_transport, and searches upwards from there.
774
Basically we keep looking up until we find the control directory or
775
run into the root. If there isn't one, raises NotBranchError.
776
If there is one and it is either an unrecognised format or an unsupported
777
format, UnknownFormatError or UnsupportedFormatError are raised.
778
If there is one, it is returned, along with the unused portion of url.
780
:return: The BzrDir that contains the path, and a Unicode path
781
for the rest of the URL.
783
# this gets the normalised url back. I.e. '.' -> the full path.
784
url = a_transport.base
787
result = BzrDir.open_from_transport(a_transport)
788
return result, urlutils.unescape(a_transport.relpath(url))
789
except errors.NotBranchError, e:
792
new_t = a_transport.clone('..')
793
except errors.InvalidURLJoin:
794
# reached the root, whatever that may be
795
raise errors.NotBranchError(path=url)
796
if new_t.base == a_transport.base:
797
# reached the root, whatever that may be
798
raise errors.NotBranchError(path=url)
802
def open_tree_or_branch(klass, location):
803
"""Return the branch and working tree at a location.
805
If there is no tree at the location, tree will be None.
806
If there is no branch at the location, an exception will be
808
:return: (tree, branch)
810
bzrdir = klass.open(location)
811
return bzrdir._get_tree_branch()
814
def open_containing_tree_or_branch(klass, location):
815
"""Return the branch and working tree contained by a location.
817
Returns (tree, branch, relpath).
818
If there is no tree at containing the location, tree will be None.
819
If there is no branch containing the location, an exception will be
821
relpath is the portion of the path that is contained by the branch.
823
bzrdir, relpath = klass.open_containing(location)
824
tree, branch = bzrdir._get_tree_branch()
825
return tree, branch, relpath
828
def open_containing_tree_branch_or_repository(klass, location):
829
"""Return the working tree, branch and repo contained by a location.
831
Returns (tree, branch, repository, relpath).
832
If there is no tree containing the location, tree will be None.
833
If there is no branch containing the location, branch will be None.
834
If there is no repository containing the location, repository will be
836
relpath is the portion of the path that is contained by the innermost
839
If no tree, branch or repository is found, a NotBranchError is raised.
841
bzrdir, relpath = klass.open_containing(location)
843
tree, branch = bzrdir._get_tree_branch()
844
except errors.NotBranchError:
846
repo = bzrdir.find_repository()
847
return None, None, repo, relpath
848
except (errors.NoRepositoryPresent):
849
raise errors.NotBranchError(location)
850
return tree, branch, branch.repository, relpath
852
def _cloning_metadir(self):
853
"""Produce a metadir suitable for cloning with.
855
:returns: (destination_bzrdir_format, source_repository)
857
result_format = self._format.__class__()
860
branch = self.open_branch(ignore_fallbacks=True)
861
source_repository = branch.repository
862
result_format._branch_format = branch._format
863
except errors.NotBranchError:
865
source_repository = self.open_repository()
866
except errors.NoRepositoryPresent:
867
source_repository = None
869
# XXX TODO: This isinstance is here because we have not implemented
870
# the fix recommended in bug # 103195 - to delegate this choice the
872
repo_format = source_repository._format
873
if isinstance(repo_format, remote.RemoteRepositoryFormat):
874
source_repository._ensure_real()
875
repo_format = source_repository._real_repository._format
876
result_format.repository_format = repo_format
878
# TODO: Couldn't we just probe for the format in these cases,
879
# rather than opening the whole tree? It would be a little
880
# faster. mbp 20070401
881
tree = self.open_workingtree(recommend_upgrade=False)
882
except (errors.NoWorkingTree, errors.NotLocalUrl):
883
result_format.workingtree_format = None
885
result_format.workingtree_format = tree._format.__class__()
886
return result_format, source_repository
888
def cloning_metadir(self, require_stacking=False):
889
"""Produce a metadir suitable for cloning or sprouting with.
891
These operations may produce workingtrees (yes, even though they're
892
"cloning" something that doesn't have a tree), so a viable workingtree
893
format must be selected.
895
:require_stacking: If True, non-stackable formats will be upgraded
896
to similar stackable formats.
897
:returns: a BzrDirFormat with all component formats either set
898
appropriately or set to None if that component should not be
901
format, repository = self._cloning_metadir()
902
if format._workingtree_format is None:
904
if repository is None:
905
# No repository either
907
# We have a repository, so set a working tree? (Why? This seems to
908
# contradict the stated return value in the docstring).
909
tree_format = repository._format._matchingbzrdir.workingtree_format
910
format.workingtree_format = tree_format.__class__()
912
format.require_stacking()
916
def create(cls, base, format=None, possible_transports=None):
917
"""Create a new BzrDir at the url 'base'.
919
:param format: If supplied, the format of branch to create. If not
920
supplied, the default is used.
921
:param possible_transports: If supplied, a list of transports that
922
can be reused to share a remote connection.
924
if cls is not BzrDir:
925
raise AssertionError("BzrDir.create always creates the"
926
"default format, not one of %r" % cls)
927
t = _mod_transport.get_transport(base, possible_transports)
930
format = controldir.ControlDirFormat.get_default_format()
931
return format.initialize_on_transport(t)
934
class BzrDirHooks(hooks.Hooks):
935
"""Hooks for BzrDir operations."""
938
"""Create the default hooks."""
939
hooks.Hooks.__init__(self)
940
self.create_hook(hooks.HookPoint('pre_open',
941
"Invoked before attempting to open a BzrDir with the transport "
942
"that the open will use.", (1, 14), None))
943
self.create_hook(hooks.HookPoint('post_repo_init',
944
"Invoked after a repository has been initialized. "
945
"post_repo_init is called with a "
946
"bzrlib.bzrdir.RepoInitHookParams.",
949
# install the default hooks
950
BzrDir.hooks = BzrDirHooks()
953
class RepoInitHookParams(object):
954
"""Object holding parameters passed to *_repo_init hooks.
956
There are 4 fields that hooks may wish to access:
958
:ivar repository: Repository created
959
:ivar format: Repository format
960
:ivar bzrdir: The bzrdir for the repository
961
:ivar shared: The repository is shared
964
def __init__(self, repository, format, a_bzrdir, shared):
965
"""Create a group of RepoInitHook parameters.
967
:param repository: Repository created
968
:param format: Repository format
969
:param bzrdir: The bzrdir for the repository
970
:param shared: The repository is shared
972
self.repository = repository
974
self.bzrdir = a_bzrdir
977
def __eq__(self, other):
978
return self.__dict__ == other.__dict__
982
return "<%s for %s>" % (self.__class__.__name__,
985
return "<%s for %s>" % (self.__class__.__name__,
989
class BzrDirPreSplitOut(BzrDir):
990
"""A common class for the all-in-one formats."""
992
def __init__(self, _transport, _format):
993
"""See BzrDir.__init__."""
994
super(BzrDirPreSplitOut, self).__init__(_transport, _format)
995
self._control_files = lockable_files.LockableFiles(
996
self.get_branch_transport(None),
997
self._format._lock_file_name,
998
self._format._lock_class)
1000
def break_lock(self):
1001
"""Pre-splitout bzrdirs do not suffer from stale locks."""
1002
raise NotImplementedError(self.break_lock)
1004
def cloning_metadir(self, require_stacking=False):
1005
"""Produce a metadir suitable for cloning with."""
1006
if require_stacking:
1007
return controldir.format_registry.make_bzrdir('1.6')
1008
return self._format.__class__()
1010
def clone(self, url, revision_id=None, force_new_repo=False,
1011
preserve_stacking=False):
1012
"""See BzrDir.clone().
1014
force_new_repo has no effect, since this family of formats always
1015
require a new repository.
1016
preserve_stacking has no effect, since no source branch using this
1017
family of formats can be stacked, so there is no stacking to preserve.
1019
self._make_tail(url)
1020
result = self._format._initialize_for_clone(url)
1021
self.open_repository().clone(result, revision_id=revision_id)
1022
from_branch = self.open_branch()
1023
from_branch.clone(result, revision_id=revision_id)
1025
tree = self.open_workingtree()
1026
except errors.NotLocalUrl:
1027
# make a new one, this format always has to have one.
1028
result._init_workingtree()
1033
def create_branch(self, name=None, repository=None):
1034
"""See BzrDir.create_branch."""
1035
if repository is not None:
1036
raise NotImplementedError(
1037
"create_branch(repository=<not None>) on %r" % (self,))
1038
return self._format.get_branch_format().initialize(self, name=name)
1040
def destroy_branch(self, name=None):
1041
"""See BzrDir.destroy_branch."""
1042
raise errors.UnsupportedOperation(self.destroy_branch, self)
1044
def create_repository(self, shared=False):
1045
"""See BzrDir.create_repository."""
1047
raise errors.IncompatibleFormat('shared repository', self._format)
1048
return self.open_repository()
1050
def destroy_repository(self):
1051
"""See BzrDir.destroy_repository."""
1052
raise errors.UnsupportedOperation(self.destroy_repository, self)
1054
def create_workingtree(self, revision_id=None, from_branch=None,
1055
accelerator_tree=None, hardlink=False):
1056
"""See BzrDir.create_workingtree."""
1057
# The workingtree is sometimes created when the bzrdir is created,
1058
# but not when cloning.
1060
# this looks buggy but is not -really-
1061
# because this format creates the workingtree when the bzrdir is
1063
# clone and sprout will have set the revision_id
1064
# and that will have set it for us, its only
1065
# specific uses of create_workingtree in isolation
1066
# that can do wonky stuff here, and that only
1067
# happens for creating checkouts, which cannot be
1068
# done on this format anyway. So - acceptable wart.
1070
warning("can't support hardlinked working trees in %r"
1073
result = self.open_workingtree(recommend_upgrade=False)
1074
except errors.NoSuchFile:
1075
result = self._init_workingtree()
1076
if revision_id is not None:
1077
if revision_id == _mod_revision.NULL_REVISION:
1078
result.set_parent_ids([])
1080
result.set_parent_ids([revision_id])
1083
def _init_workingtree(self):
1084
from bzrlib.workingtree import WorkingTreeFormat2
1086
return WorkingTreeFormat2().initialize(self)
1087
except errors.NotLocalUrl:
1088
# Even though we can't access the working tree, we need to
1089
# create its control files.
1090
return WorkingTreeFormat2()._stub_initialize_on_transport(
1091
self.transport, self._control_files._file_mode)
1093
def destroy_workingtree(self):
1094
"""See BzrDir.destroy_workingtree."""
1095
raise errors.UnsupportedOperation(self.destroy_workingtree, self)
1097
def destroy_workingtree_metadata(self):
1098
"""See BzrDir.destroy_workingtree_metadata."""
1099
raise errors.UnsupportedOperation(self.destroy_workingtree_metadata,
1102
def get_branch_transport(self, branch_format, name=None):
1103
"""See BzrDir.get_branch_transport()."""
1104
if name is not None:
1105
raise errors.NoColocatedBranchSupport(self)
1106
if branch_format is None:
1107
return self.transport
1109
branch_format.get_format_string()
1110
except NotImplementedError:
1111
return self.transport
1112
raise errors.IncompatibleFormat(branch_format, self._format)
1114
def get_repository_transport(self, repository_format):
1115
"""See BzrDir.get_repository_transport()."""
1116
if repository_format is None:
1117
return self.transport
1119
repository_format.get_format_string()
1120
except NotImplementedError:
1121
return self.transport
1122
raise errors.IncompatibleFormat(repository_format, self._format)
1124
def get_workingtree_transport(self, workingtree_format):
1125
"""See BzrDir.get_workingtree_transport()."""
1126
if workingtree_format is None:
1127
return self.transport
1129
workingtree_format.get_format_string()
1130
except NotImplementedError:
1131
return self.transport
1132
raise errors.IncompatibleFormat(workingtree_format, self._format)
1134
def needs_format_conversion(self, format):
1135
"""See BzrDir.needs_format_conversion()."""
1136
return not isinstance(self._format, format.__class__)
1138
def open_branch(self, name=None, unsupported=False,
1139
ignore_fallbacks=False):
1140
"""See BzrDir.open_branch."""
1141
from bzrlib.branch import BzrBranchFormat4
1142
format = BzrBranchFormat4()
1143
self._check_supported(format, unsupported)
1144
return format.open(self, name, _found=True)
1146
def sprout(self, url, revision_id=None, force_new_repo=False,
1147
possible_transports=None, accelerator_tree=None,
1148
hardlink=False, stacked=False, create_tree_if_local=True,
1149
source_branch=None):
1150
"""See BzrDir.sprout()."""
1151
if source_branch is not None:
1152
my_branch = self.open_branch()
1153
if source_branch.base != my_branch.base:
1154
raise AssertionError(
1155
"source branch %r is not within %r with branch %r" %
1156
(source_branch, self, my_branch))
1158
raise errors.UnstackableBranchFormat(
1159
self._format, self.root_transport.base)
1160
if not create_tree_if_local:
1161
raise errors.MustHaveWorkingTree(
1162
self._format, self.root_transport.base)
1163
from bzrlib.workingtree import WorkingTreeFormat2
1164
self._make_tail(url)
1165
result = self._format._initialize_for_clone(url)
1167
self.open_repository().clone(result, revision_id=revision_id)
1168
except errors.NoRepositoryPresent:
1171
self.open_branch().sprout(result, revision_id=revision_id)
1172
except errors.NotBranchError:
1175
# we always want a working tree
1176
WorkingTreeFormat2().initialize(result,
1177
accelerator_tree=accelerator_tree,
1182
class BzrDir4(BzrDirPreSplitOut):
1183
"""A .bzr version 4 control object.
1185
This is a deprecated format and may be removed after sept 2006.
1188
def create_repository(self, shared=False):
1189
"""See BzrDir.create_repository."""
1190
return self._format.repository_format.initialize(self, shared)
1192
def needs_format_conversion(self, format):
1193
"""Format 4 dirs are always in need of conversion."""
1196
def open_repository(self):
1197
"""See BzrDir.open_repository."""
1198
from bzrlib.repofmt.weaverepo import RepositoryFormat4
1199
return RepositoryFormat4().open(self, _found=True)
1202
class BzrDir5(BzrDirPreSplitOut):
1203
"""A .bzr version 5 control object.
1205
This is a deprecated format and may be removed after sept 2006.
1208
def has_workingtree(self):
1209
"""See BzrDir.has_workingtree."""
1212
def open_repository(self):
1213
"""See BzrDir.open_repository."""
1214
from bzrlib.repofmt.weaverepo import RepositoryFormat5
1215
return RepositoryFormat5().open(self, _found=True)
1217
def open_workingtree(self, _unsupported=False,
1218
recommend_upgrade=True):
1219
"""See BzrDir.create_workingtree."""
1220
from bzrlib.workingtree import WorkingTreeFormat2
1221
wt_format = WorkingTreeFormat2()
1222
# we don't warn here about upgrades; that ought to be handled for the
1224
return wt_format.open(self, _found=True)
1227
class BzrDir6(BzrDirPreSplitOut):
1228
"""A .bzr version 6 control object.
1230
This is a deprecated format and may be removed after sept 2006.
1233
def has_workingtree(self):
1234
"""See BzrDir.has_workingtree."""
1237
def open_repository(self):
1238
"""See BzrDir.open_repository."""
1239
from bzrlib.repofmt.weaverepo import RepositoryFormat6
1240
return RepositoryFormat6().open(self, _found=True)
1242
def open_workingtree(self, _unsupported=False,
1243
recommend_upgrade=True):
1244
"""See BzrDir.create_workingtree."""
1245
# we don't warn here about upgrades; that ought to be handled for the
1247
from bzrlib.workingtree import WorkingTreeFormat2
1248
return WorkingTreeFormat2().open(self, _found=True)
1251
class BzrDirMeta1(BzrDir):
1252
"""A .bzr meta version 1 control object.
1254
This is the first control object where the
1255
individual aspects are really split out: there are separate repository,
1256
workingtree and branch subdirectories and any subset of the three can be
1257
present within a BzrDir.
1260
def can_convert_format(self):
1261
"""See BzrDir.can_convert_format()."""
1264
def create_branch(self, name=None, repository=None):
1265
"""See BzrDir.create_branch."""
1266
return self._format.get_branch_format().initialize(self, name=name,
1267
repository=repository)
1269
def destroy_branch(self, name=None):
1270
"""See BzrDir.create_branch."""
1271
if name is not None:
1272
raise errors.NoColocatedBranchSupport(self)
1273
self.transport.delete_tree('branch')
1275
def create_repository(self, shared=False):
1276
"""See BzrDir.create_repository."""
1277
return self._format.repository_format.initialize(self, shared)
1279
def destroy_repository(self):
1280
"""See BzrDir.destroy_repository."""
1281
self.transport.delete_tree('repository')
1283
def create_workingtree(self, revision_id=None, from_branch=None,
1284
accelerator_tree=None, hardlink=False):
1285
"""See BzrDir.create_workingtree."""
1286
return self._format.workingtree_format.initialize(
1287
self, revision_id, from_branch=from_branch,
1288
accelerator_tree=accelerator_tree, hardlink=hardlink)
1290
def destroy_workingtree(self):
1291
"""See BzrDir.destroy_workingtree."""
1292
wt = self.open_workingtree(recommend_upgrade=False)
1293
repository = wt.branch.repository
1294
empty = repository.revision_tree(_mod_revision.NULL_REVISION)
1295
# We ignore the conflicts returned by wt.revert since we're about to
1296
# delete the wt metadata anyway, all that should be left here are
1297
# detritus. But see bug #634470 about subtree .bzr dirs.
1298
conflicts = wt.revert(old_tree=empty)
1299
self.destroy_workingtree_metadata()
1301
def destroy_workingtree_metadata(self):
1302
self.transport.delete_tree('checkout')
1304
def find_branch_format(self, name=None):
1305
"""Find the branch 'format' for this bzrdir.
1307
This might be a synthetic object for e.g. RemoteBranch and SVN.
1309
from bzrlib.branch import BranchFormat
1310
return BranchFormat.find_format(self, name=name)
1312
def _get_mkdir_mode(self):
1313
"""Figure out the mode to use when creating a bzrdir subdir."""
1314
temp_control = lockable_files.LockableFiles(self.transport, '',
1315
lockable_files.TransportLock)
1316
return temp_control._dir_mode
1318
def get_branch_reference(self, name=None):
1319
"""See BzrDir.get_branch_reference()."""
1320
from bzrlib.branch import BranchFormat
1321
format = BranchFormat.find_format(self, name=name)
1322
return format.get_reference(self, name=name)
1324
def get_branch_transport(self, branch_format, name=None):
1325
"""See BzrDir.get_branch_transport()."""
1326
if name is not None:
1327
raise errors.NoColocatedBranchSupport(self)
1328
# XXX: this shouldn't implicitly create the directory if it's just
1329
# promising to get a transport -- mbp 20090727
1330
if branch_format is None:
1331
return self.transport.clone('branch')
1333
branch_format.get_format_string()
1334
except NotImplementedError:
1335
raise errors.IncompatibleFormat(branch_format, self._format)
1337
self.transport.mkdir('branch', mode=self._get_mkdir_mode())
1338
except errors.FileExists:
1340
return self.transport.clone('branch')
1342
def get_repository_transport(self, repository_format):
1343
"""See BzrDir.get_repository_transport()."""
1344
if repository_format is None:
1345
return self.transport.clone('repository')
1347
repository_format.get_format_string()
1348
except NotImplementedError:
1349
raise errors.IncompatibleFormat(repository_format, self._format)
1351
self.transport.mkdir('repository', mode=self._get_mkdir_mode())
1352
except errors.FileExists:
1354
return self.transport.clone('repository')
1356
def get_workingtree_transport(self, workingtree_format):
1357
"""See BzrDir.get_workingtree_transport()."""
1358
if workingtree_format is None:
1359
return self.transport.clone('checkout')
1361
workingtree_format.get_format_string()
1362
except NotImplementedError:
1363
raise errors.IncompatibleFormat(workingtree_format, self._format)
1365
self.transport.mkdir('checkout', mode=self._get_mkdir_mode())
1366
except errors.FileExists:
1368
return self.transport.clone('checkout')
1370
def has_workingtree(self):
1371
"""Tell if this bzrdir contains a working tree.
1373
This will still raise an exception if the bzrdir has a workingtree that
1374
is remote & inaccessible.
1376
Note: if you're going to open the working tree, you should just go
1377
ahead and try, and not ask permission first.
1379
from bzrlib.workingtree import WorkingTreeFormat
1381
WorkingTreeFormat.find_format(self)
1382
except errors.NoWorkingTree:
1386
def needs_format_conversion(self, format):
1387
"""See BzrDir.needs_format_conversion()."""
1388
if not isinstance(self._format, format.__class__):
1389
# it is not a meta dir format, conversion is needed.
1391
# we might want to push this down to the repository?
1393
if not isinstance(self.open_repository()._format,
1394
format.repository_format.__class__):
1395
# the repository needs an upgrade.
1397
except errors.NoRepositoryPresent:
1399
for branch in self.list_branches():
1400
if not isinstance(branch._format,
1401
format.get_branch_format().__class__):
1402
# the branch needs an upgrade.
1405
my_wt = self.open_workingtree(recommend_upgrade=False)
1406
if not isinstance(my_wt._format,
1407
format.workingtree_format.__class__):
1408
# the workingtree needs an upgrade.
1410
except (errors.NoWorkingTree, errors.NotLocalUrl):
1414
def open_branch(self, name=None, unsupported=False,
1415
ignore_fallbacks=False):
1416
"""See BzrDir.open_branch."""
1417
format = self.find_branch_format(name=name)
1418
self._check_supported(format, unsupported)
1419
return format.open(self, name=name,
1420
_found=True, ignore_fallbacks=ignore_fallbacks)
1422
def open_repository(self, unsupported=False):
1423
"""See BzrDir.open_repository."""
1424
from bzrlib.repository import RepositoryFormat
1425
format = RepositoryFormat.find_format(self)
1426
self._check_supported(format, unsupported)
1427
return format.open(self, _found=True)
1429
def open_workingtree(self, unsupported=False,
1430
recommend_upgrade=True):
1431
"""See BzrDir.open_workingtree."""
1432
from bzrlib.workingtree import WorkingTreeFormat
1433
format = WorkingTreeFormat.find_format(self)
1434
self._check_supported(format, unsupported,
1436
basedir=self.root_transport.base)
1437
return format.open(self, _found=True)
1439
def _get_config(self):
1440
return config.TransportConfig(self.transport, 'control.conf')
1443
class BzrProber(controldir.Prober):
1444
"""Prober for formats that use a .bzr/ control directory."""
1447
"""The known .bzr formats."""
1450
def register_bzrdir_format(klass, format):
1451
klass._formats[format.get_format_string()] = format
1454
def unregister_bzrdir_format(klass, format):
1455
del klass._formats[format.get_format_string()]
1458
def probe_transport(klass, transport):
1459
"""Return the .bzrdir style format present in a directory."""
1461
format_string = transport.get_bytes(".bzr/branch-format")
1462
except errors.NoSuchFile:
1463
raise errors.NotBranchError(path=transport.base)
1465
return klass._formats[format_string]
1467
raise errors.UnknownFormatError(format=format_string, kind='bzrdir')
1470
controldir.ControlDirFormat.register_prober(BzrProber)
1473
class RemoteBzrProber(controldir.Prober):
1474
"""Prober for remote servers that provide a Bazaar smart server."""
1477
def probe_transport(klass, transport):
1478
"""Return a RemoteBzrDirFormat object if it looks possible."""
1480
medium = transport.get_smart_medium()
1481
except (NotImplementedError, AttributeError,
1482
errors.TransportNotPossible, errors.NoSmartMedium,
1483
errors.SmartProtocolError):
1484
# no smart server, so not a branch for this format type.
1485
raise errors.NotBranchError(path=transport.base)
1487
# Decline to open it if the server doesn't support our required
1488
# version (3) so that the VFS-based transport will do it.
1489
if medium.should_probe():
1491
server_version = medium.protocol_version()
1492
except errors.SmartProtocolError:
1493
# Apparently there's no usable smart server there, even though
1494
# the medium supports the smart protocol.
1495
raise errors.NotBranchError(path=transport.base)
1496
if server_version != '2':
1497
raise errors.NotBranchError(path=transport.base)
1498
return RemoteBzrDirFormat()
1501
class BzrDirFormat(controldir.ControlDirFormat):
1502
"""ControlDirFormat base class for .bzr/ directories.
1504
Formats are placed in a dict by their format string for reference
1505
during bzrdir opening. These should be subclasses of BzrDirFormat
1508
Once a format is deprecated, just deprecate the initialize and open
1509
methods on the format class. Do not deprecate the object, as the
1510
object will be created every system load.
1513
_lock_file_name = 'branch-lock'
1515
# _lock_class must be set in subclasses to the lock type, typ.
1516
# TransportLock or LockDir
1518
def get_format_string(self):
1519
"""Return the ASCII format string that identifies this format."""
1520
raise NotImplementedError(self.get_format_string)
1522
def initialize_on_transport(self, transport):
1523
"""Initialize a new bzrdir in the base directory of a Transport."""
1525
# can we hand off the request to the smart server rather than using
1527
client_medium = transport.get_smart_medium()
1528
except errors.NoSmartMedium:
1529
return self._initialize_on_transport_vfs(transport)
1531
# Current RPC's only know how to create bzr metadir1 instances, so
1532
# we still delegate to vfs methods if the requested format is not a
1534
if type(self) != BzrDirMetaFormat1:
1535
return self._initialize_on_transport_vfs(transport)
1536
remote_format = RemoteBzrDirFormat()
1537
self._supply_sub_formats_to(remote_format)
1538
return remote_format.initialize_on_transport(transport)
1540
def initialize_on_transport_ex(self, transport, use_existing_dir=False,
1541
create_prefix=False, force_new_repo=False, stacked_on=None,
1542
stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
1543
shared_repo=False, vfs_only=False):
1544
"""Create this format on transport.
1546
The directory to initialize will be created.
1548
:param force_new_repo: Do not use a shared repository for the target,
1549
even if one is available.
1550
:param create_prefix: Create any missing directories leading up to
1552
:param use_existing_dir: Use an existing directory if one exists.
1553
:param stacked_on: A url to stack any created branch on, None to follow
1554
any target stacking policy.
1555
:param stack_on_pwd: If stack_on is relative, the location it is
1557
:param repo_format_name: If non-None, a repository will be
1558
made-or-found. Should none be found, or if force_new_repo is True
1559
the repo_format_name is used to select the format of repository to
1561
:param make_working_trees: Control the setting of make_working_trees
1562
for a new shared repository when one is made. None to use whatever
1563
default the format has.
1564
:param shared_repo: Control whether made repositories are shared or
1566
:param vfs_only: If True do not attempt to use a smart server
1567
:return: repo, bzrdir, require_stacking, repository_policy. repo is
1568
None if none was created or found, bzrdir is always valid.
1569
require_stacking is the result of examining the stacked_on
1570
parameter and any stacking policy found for the target.
1573
# Try to hand off to a smart server
1575
client_medium = transport.get_smart_medium()
1576
except errors.NoSmartMedium:
1579
# TODO: lookup the local format from a server hint.
1580
remote_dir_format = RemoteBzrDirFormat()
1581
remote_dir_format._network_name = self.network_name()
1582
self._supply_sub_formats_to(remote_dir_format)
1583
return remote_dir_format.initialize_on_transport_ex(transport,
1584
use_existing_dir=use_existing_dir, create_prefix=create_prefix,
1585
force_new_repo=force_new_repo, stacked_on=stacked_on,
1586
stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
1587
make_working_trees=make_working_trees, shared_repo=shared_repo)
1588
# XXX: Refactor the create_prefix/no_create_prefix code into a
1589
# common helper function
1590
# The destination may not exist - if so make it according to policy.
1591
def make_directory(transport):
1592
transport.mkdir('.')
1594
def redirected(transport, e, redirection_notice):
1595
note(redirection_notice)
1596
return transport._redirected_to(e.source, e.target)
1598
transport = do_catching_redirections(make_directory, transport,
1600
except errors.FileExists:
1601
if not use_existing_dir:
1603
except errors.NoSuchFile:
1604
if not create_prefix:
1606
transport.create_prefix()
1608
require_stacking = (stacked_on is not None)
1609
# Now the target directory exists, but doesn't have a .bzr
1610
# directory. So we need to create it, along with any work to create
1611
# all of the dependent branches, etc.
1613
result = self.initialize_on_transport(transport)
1614
if repo_format_name:
1616
# use a custom format
1617
result._format.repository_format = \
1618
repository.network_format_registry.get(repo_format_name)
1619
except AttributeError:
1620
# The format didn't permit it to be set.
1622
# A repository is desired, either in-place or shared.
1623
repository_policy = result.determine_repository_policy(
1624
force_new_repo, stacked_on, stack_on_pwd,
1625
require_stacking=require_stacking)
1626
result_repo, is_new_repo = repository_policy.acquire_repository(
1627
make_working_trees, shared_repo)
1628
if not require_stacking and repository_policy._require_stacking:
1629
require_stacking = True
1630
result._format.require_stacking()
1631
result_repo.lock_write()
1634
repository_policy = None
1635
return result_repo, result, require_stacking, repository_policy
1637
def _initialize_on_transport_vfs(self, transport):
1638
"""Initialize a new bzrdir using VFS calls.
1640
:param transport: The transport to create the .bzr directory in.
1643
# Since we are creating a .bzr directory, inherit the
1644
# mode from the root directory
1645
temp_control = lockable_files.LockableFiles(transport,
1646
'', lockable_files.TransportLock)
1647
temp_control._transport.mkdir('.bzr',
1648
# FIXME: RBC 20060121 don't peek under
1650
mode=temp_control._dir_mode)
1651
if sys.platform == 'win32' and isinstance(transport, local.LocalTransport):
1652
win32utils.set_file_attr_hidden(transport._abspath('.bzr'))
1653
file_mode = temp_control._file_mode
1655
bzrdir_transport = transport.clone('.bzr')
1656
utf8_files = [('README',
1657
"This is a Bazaar control directory.\n"
1658
"Do not change any files in this directory.\n"
1659
"See http://bazaar.canonical.com/ for more information about Bazaar.\n"),
1660
('branch-format', self.get_format_string()),
1662
# NB: no need to escape relative paths that are url safe.
1663
control_files = lockable_files.LockableFiles(bzrdir_transport,
1664
self._lock_file_name, self._lock_class)
1665
control_files.create_lock()
1666
control_files.lock_write()
1668
for (filename, content) in utf8_files:
1669
bzrdir_transport.put_bytes(filename, content,
1672
control_files.unlock()
1673
return self.open(transport, _found=True)
1675
def open(self, transport, _found=False):
1676
"""Return an instance of this format for the dir transport points at.
1678
_found is a private parameter, do not use it.
1681
found_format = controldir.ControlDirFormat.find_format(transport)
1682
if not isinstance(found_format, self.__class__):
1683
raise AssertionError("%s was asked to open %s, but it seems to need "
1685
% (self, transport, found_format))
1686
# Allow subclasses - use the found format.
1687
self._supply_sub_formats_to(found_format)
1688
return found_format._open(transport)
1689
return self._open(transport)
1691
def _open(self, transport):
1692
"""Template method helper for opening BzrDirectories.
1694
This performs the actual open and any additional logic or parameter
1697
raise NotImplementedError(self._open)
1700
def register_format(klass, format):
1701
BzrProber.register_bzrdir_format(format)
1702
# bzr native formats have a network name of their format string.
1703
controldir.network_format_registry.register(format.get_format_string(), format.__class__)
1704
controldir.ControlDirFormat.register_format(format)
1706
def _supply_sub_formats_to(self, other_format):
1707
"""Give other_format the same values for sub formats as this has.
1709
This method is expected to be used when parameterising a
1710
RemoteBzrDirFormat instance with the parameters from a
1711
BzrDirMetaFormat1 instance.
1713
:param other_format: other_format is a format which should be
1714
compatible with whatever sub formats are supported by self.
1719
def unregister_format(klass, format):
1720
BzrProber.unregister_bzrdir_format(format)
1721
controldir.ControlDirFormat.unregister_format(format)
1722
controldir.network_format_registry.remove(format.get_format_string())
1725
class BzrDirFormat4(BzrDirFormat):
1726
"""Bzr dir format 4.
1728
This format is a combined format for working tree, branch and repository.
1730
- Format 1 working trees [always]
1731
- Format 4 branches [always]
1732
- Format 4 repositories [always]
1734
This format is deprecated: it indexes texts using a text it which is
1735
removed in format 5; write support for this format has been removed.
1738
_lock_class = lockable_files.TransportLock
1740
fixed_components = True
1742
def get_format_string(self):
1743
"""See BzrDirFormat.get_format_string()."""
1744
return "Bazaar-NG branch, format 0.0.4\n"
1746
def get_format_description(self):
1747
"""See BzrDirFormat.get_format_description()."""
1748
return "All-in-one format 4"
1750
def get_converter(self, format=None):
1751
"""See BzrDirFormat.get_converter()."""
1752
# there is one and only one upgrade path here.
1753
return ConvertBzrDir4To5()
1755
def initialize_on_transport(self, transport):
1756
"""Format 4 branches cannot be created."""
1757
raise errors.UninitializableFormat(self)
1759
def is_supported(self):
1760
"""Format 4 is not supported.
1762
It is not supported because the model changed from 4 to 5 and the
1763
conversion logic is expensive - so doing it on the fly was not
1768
def network_name(self):
1769
return self.get_format_string()
1771
def _open(self, transport):
1772
"""See BzrDirFormat._open."""
1773
return BzrDir4(transport, self)
1775
def __return_repository_format(self):
1776
"""Circular import protection."""
1777
from bzrlib.repofmt.weaverepo import RepositoryFormat4
1778
return RepositoryFormat4()
1779
repository_format = property(__return_repository_format)
1782
class BzrDirFormatAllInOne(BzrDirFormat):
1783
"""Common class for formats before meta-dirs."""
1785
fixed_components = True
1787
def initialize_on_transport_ex(self, transport, use_existing_dir=False,
1788
create_prefix=False, force_new_repo=False, stacked_on=None,
1789
stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
1791
"""See BzrDirFormat.initialize_on_transport_ex."""
1792
require_stacking = (stacked_on is not None)
1793
# Format 5 cannot stack, but we've been asked to - actually init
1795
if require_stacking:
1796
format = BzrDirMetaFormat1()
1797
return format.initialize_on_transport_ex(transport,
1798
use_existing_dir=use_existing_dir, create_prefix=create_prefix,
1799
force_new_repo=force_new_repo, stacked_on=stacked_on,
1800
stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
1801
make_working_trees=make_working_trees, shared_repo=shared_repo)
1802
return BzrDirFormat.initialize_on_transport_ex(self, transport,
1803
use_existing_dir=use_existing_dir, create_prefix=create_prefix,
1804
force_new_repo=force_new_repo, stacked_on=stacked_on,
1805
stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
1806
make_working_trees=make_working_trees, shared_repo=shared_repo)
1809
class BzrDirFormat5(BzrDirFormatAllInOne):
1810
"""Bzr control format 5.
1812
This format is a combined format for working tree, branch and repository.
1814
- Format 2 working trees [always]
1815
- Format 4 branches [always]
1816
- Format 5 repositories [always]
1817
Unhashed stores in the repository.
1820
_lock_class = lockable_files.TransportLock
1822
def get_format_string(self):
1823
"""See BzrDirFormat.get_format_string()."""
1824
return "Bazaar-NG branch, format 5\n"
1826
def get_branch_format(self):
1827
from bzrlib import branch
1828
return branch.BzrBranchFormat4()
1830
def get_format_description(self):
1831
"""See BzrDirFormat.get_format_description()."""
1832
return "All-in-one format 5"
1834
def get_converter(self, format=None):
1835
"""See BzrDirFormat.get_converter()."""
1836
# there is one and only one upgrade path here.
1837
return ConvertBzrDir5To6()
1839
def _initialize_for_clone(self, url):
1840
return self.initialize_on_transport(
1841
_mod_transport.get_transport(url), _cloning=True)
1843
def initialize_on_transport(self, transport, _cloning=False):
1844
"""Format 5 dirs always have working tree, branch and repository.
1846
Except when they are being cloned.
1848
from bzrlib.branch import BzrBranchFormat4
1849
from bzrlib.repofmt.weaverepo import RepositoryFormat5
1850
result = (super(BzrDirFormat5, self).initialize_on_transport(transport))
1851
RepositoryFormat5().initialize(result, _internal=True)
1853
branch = BzrBranchFormat4().initialize(result)
1854
result._init_workingtree()
1857
def network_name(self):
1858
return self.get_format_string()
1860
def _open(self, transport):
1861
"""See BzrDirFormat._open."""
1862
return BzrDir5(transport, self)
1864
def __return_repository_format(self):
1865
"""Circular import protection."""
1866
from bzrlib.repofmt.weaverepo import RepositoryFormat5
1867
return RepositoryFormat5()
1868
repository_format = property(__return_repository_format)
1871
class BzrDirFormat6(BzrDirFormatAllInOne):
1872
"""Bzr control format 6.
1874
This format is a combined format for working tree, branch and repository.
1876
- Format 2 working trees [always]
1877
- Format 4 branches [always]
1878
- Format 6 repositories [always]
1881
_lock_class = lockable_files.TransportLock
1883
def get_format_string(self):
1884
"""See BzrDirFormat.get_format_string()."""
1885
return "Bazaar-NG branch, format 6\n"
1887
def get_format_description(self):
1888
"""See BzrDirFormat.get_format_description()."""
1889
return "All-in-one format 6"
1891
def get_branch_format(self):
1892
from bzrlib import branch
1893
return branch.BzrBranchFormat4()
1895
def get_converter(self, format=None):
1896
"""See BzrDirFormat.get_converter()."""
1897
# there is one and only one upgrade path here.
1898
return ConvertBzrDir6ToMeta()
1900
def _initialize_for_clone(self, url):
1901
return self.initialize_on_transport(
1902
_mod_transport.get_transport(url), _cloning=True)
1904
def initialize_on_transport(self, transport, _cloning=False):
1905
"""Format 6 dirs always have working tree, branch and repository.
1907
Except when they are being cloned.
1909
from bzrlib.branch import BzrBranchFormat4
1910
from bzrlib.repofmt.weaverepo import RepositoryFormat6
1911
result = super(BzrDirFormat6, self).initialize_on_transport(transport)
1912
RepositoryFormat6().initialize(result, _internal=True)
1914
branch = BzrBranchFormat4().initialize(result)
1915
result._init_workingtree()
1918
def network_name(self):
1919
return self.get_format_string()
1921
def _open(self, transport):
1922
"""See BzrDirFormat._open."""
1923
return BzrDir6(transport, self)
1925
def __return_repository_format(self):
1926
"""Circular import protection."""
1927
from bzrlib.repofmt.weaverepo import RepositoryFormat6
1928
return RepositoryFormat6()
1929
repository_format = property(__return_repository_format)
1932
class BzrDirMetaFormat1(BzrDirFormat):
1933
"""Bzr meta control format 1
1935
This is the first format with split out working tree, branch and repository
1938
- Format 3 working trees [optional]
1939
- Format 5 branches [optional]
1940
- Format 7 repositories [optional]
1943
_lock_class = lockdir.LockDir
1945
fixed_components = False
1948
self._workingtree_format = None
1949
self._branch_format = None
1950
self._repository_format = None
1952
def __eq__(self, other):
1953
if other.__class__ is not self.__class__:
1955
if other.repository_format != self.repository_format:
1957
if other.workingtree_format != self.workingtree_format:
1961
def __ne__(self, other):
1962
return not self == other
1964
def get_branch_format(self):
1965
if self._branch_format is None:
1966
from bzrlib.branch import format_registry as branch_format_registry
1967
self._branch_format = branch_format_registry.get_default()
1968
return self._branch_format
1970
def set_branch_format(self, format):
1971
self._branch_format = format
1973
def require_stacking(self, stack_on=None, possible_transports=None,
1975
"""We have a request to stack, try to ensure the formats support it.
1977
:param stack_on: If supplied, it is the URL to a branch that we want to
1978
stack on. Check to see if that format supports stacking before
1981
# Stacking is desired. requested by the target, but does the place it
1982
# points at support stacking? If it doesn't then we should
1983
# not implicitly upgrade. We check this here.
1984
new_repo_format = None
1985
new_branch_format = None
1987
# a bit of state for get_target_branch so that we don't try to open it
1988
# 2 times, for both repo *and* branch
1989
target = [None, False, None] # target_branch, checked, upgrade anyway
1990
def get_target_branch():
1992
# We've checked, don't check again
1994
if stack_on is None:
1995
# No target format, that means we want to force upgrading
1996
target[:] = [None, True, True]
1999
target_dir = BzrDir.open(stack_on,
2000
possible_transports=possible_transports)
2001
except errors.NotBranchError:
2002
# Nothing there, don't change formats
2003
target[:] = [None, True, False]
2005
except errors.JailBreak:
2006
# JailBreak, JFDI and upgrade anyway
2007
target[:] = [None, True, True]
2010
target_branch = target_dir.open_branch()
2011
except errors.NotBranchError:
2012
# No branch, don't upgrade formats
2013
target[:] = [None, True, False]
2015
target[:] = [target_branch, True, False]
2018
if (not _skip_repo and
2019
not self.repository_format.supports_external_lookups):
2020
# We need to upgrade the Repository.
2021
target_branch, _, do_upgrade = get_target_branch()
2022
if target_branch is None:
2023
# We don't have a target branch, should we upgrade anyway?
2025
# stack_on is inaccessible, JFDI.
2026
# TODO: bad monkey, hard-coded formats...
2027
if self.repository_format.rich_root_data:
2028
new_repo_format = pack_repo.RepositoryFormatKnitPack5RichRoot()
2030
new_repo_format = pack_repo.RepositoryFormatKnitPack5()
2032
# If the target already supports stacking, then we know the
2033
# project is already able to use stacking, so auto-upgrade
2035
new_repo_format = target_branch.repository._format
2036
if not new_repo_format.supports_external_lookups:
2037
# target doesn't, source doesn't, so don't auto upgrade
2039
new_repo_format = None
2040
if new_repo_format is not None:
2041
self.repository_format = new_repo_format
2042
note('Source repository format does not support stacking,'
2043
' using format:\n %s',
2044
new_repo_format.get_format_description())
2046
if not self.get_branch_format().supports_stacking():
2047
# We just checked the repo, now lets check if we need to
2048
# upgrade the branch format
2049
target_branch, _, do_upgrade = get_target_branch()
2050
if target_branch is None:
2052
# TODO: bad monkey, hard-coded formats...
2053
new_branch_format = branch.BzrBranchFormat7()
2055
new_branch_format = target_branch._format
2056
if not new_branch_format.supports_stacking():
2057
new_branch_format = None
2058
if new_branch_format is not None:
2059
# Does support stacking, use its format.
2060
self.set_branch_format(new_branch_format)
2061
note('Source branch format does not support stacking,'
2062
' using format:\n %s',
2063
new_branch_format.get_format_description())
2065
def get_converter(self, format=None):
2066
"""See BzrDirFormat.get_converter()."""
2068
format = BzrDirFormat.get_default_format()
2069
if not isinstance(self, format.__class__):
2070
# converting away from metadir is not implemented
2071
raise NotImplementedError(self.get_converter)
2072
return ConvertMetaToMeta(format)
2074
def get_format_string(self):
2075
"""See BzrDirFormat.get_format_string()."""
2076
return "Bazaar-NG meta directory, format 1\n"
2078
def get_format_description(self):
2079
"""See BzrDirFormat.get_format_description()."""
2080
return "Meta directory format 1"
2082
def network_name(self):
2083
return self.get_format_string()
2085
def _open(self, transport):
2086
"""See BzrDirFormat._open."""
2087
# Create a new format instance because otherwise initialisation of new
2088
# metadirs share the global default format object leading to alias
2090
format = BzrDirMetaFormat1()
2091
self._supply_sub_formats_to(format)
2092
return BzrDirMeta1(transport, format)
2094
def __return_repository_format(self):
2095
"""Circular import protection."""
2096
if self._repository_format:
2097
return self._repository_format
2098
from bzrlib.repository import format_registry
2099
return format_registry.get_default()
2101
def _set_repository_format(self, value):
2102
"""Allow changing the repository format for metadir formats."""
2103
self._repository_format = value
2105
repository_format = property(__return_repository_format,
2106
_set_repository_format)
2108
def _supply_sub_formats_to(self, other_format):
2109
"""Give other_format the same values for sub formats as this has.
2111
This method is expected to be used when parameterising a
2112
RemoteBzrDirFormat instance with the parameters from a
2113
BzrDirMetaFormat1 instance.
2115
:param other_format: other_format is a format which should be
2116
compatible with whatever sub formats are supported by self.
2119
if getattr(self, '_repository_format', None) is not None:
2120
other_format.repository_format = self.repository_format
2121
if self._branch_format is not None:
2122
other_format._branch_format = self._branch_format
2123
if self._workingtree_format is not None:
2124
other_format.workingtree_format = self.workingtree_format
2126
def __get_workingtree_format(self):
2127
if self._workingtree_format is None:
2128
from bzrlib.workingtree import (
2129
format_registry as wt_format_registry,
2131
self._workingtree_format = wt_format_registry.get_default()
2132
return self._workingtree_format
2134
def __set_workingtree_format(self, wt_format):
2135
self._workingtree_format = wt_format
2137
workingtree_format = property(__get_workingtree_format,
2138
__set_workingtree_format)
2141
# Register bzr formats
2142
BzrDirFormat.register_format(BzrDirFormat4())
2143
BzrDirFormat.register_format(BzrDirFormat5())
2144
BzrDirFormat.register_format(BzrDirFormat6())
2145
__default_format = BzrDirMetaFormat1()
2146
BzrDirFormat.register_format(__default_format)
2147
controldir.ControlDirFormat._default_format = __default_format
2150
class Converter(object):
2151
"""Converts a disk format object from one format to another."""
2153
def convert(self, to_convert, pb):
2154
"""Perform the conversion of to_convert, giving feedback via pb.
2156
:param to_convert: The disk object to convert.
2157
:param pb: a progress bar to use for progress information.
2160
def step(self, message):
2161
"""Update the pb by a step."""
2163
self.pb.update(message, self.count, self.total)
2166
class ConvertBzrDir4To5(Converter):
2167
"""Converts format 4 bzr dirs to format 5."""
2170
super(ConvertBzrDir4To5, self).__init__()
2171
self.converted_revs = set()
2172
self.absent_revisions = set()
2176
def convert(self, to_convert, pb):
2177
"""See Converter.convert()."""
2178
self.bzrdir = to_convert
2180
warnings.warn("pb parameter to convert() is deprecated")
2181
self.pb = ui.ui_factory.nested_progress_bar()
2183
ui.ui_factory.note('starting upgrade from format 4 to 5')
2184
if isinstance(self.bzrdir.transport, local.LocalTransport):
2185
self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
2186
self._convert_to_weaves()
2187
return BzrDir.open(self.bzrdir.user_url)
2191
def _convert_to_weaves(self):
2192
ui.ui_factory.note('note: upgrade may be faster if all store files are ungzipped first')
2195
stat = self.bzrdir.transport.stat('weaves')
2196
if not S_ISDIR(stat.st_mode):
2197
self.bzrdir.transport.delete('weaves')
2198
self.bzrdir.transport.mkdir('weaves')
2199
except errors.NoSuchFile:
2200
self.bzrdir.transport.mkdir('weaves')
2201
# deliberately not a WeaveFile as we want to build it up slowly.
2202
self.inv_weave = Weave('inventory')
2203
# holds in-memory weaves for all files
2204
self.text_weaves = {}
2205
self.bzrdir.transport.delete('branch-format')
2206
self.branch = self.bzrdir.open_branch()
2207
self._convert_working_inv()
2208
rev_history = self.branch.revision_history()
2209
# to_read is a stack holding the revisions we still need to process;
2210
# appending to it adds new highest-priority revisions
2211
self.known_revisions = set(rev_history)
2212
self.to_read = rev_history[-1:]
2214
rev_id = self.to_read.pop()
2215
if (rev_id not in self.revisions
2216
and rev_id not in self.absent_revisions):
2217
self._load_one_rev(rev_id)
2219
to_import = self._make_order()
2220
for i, rev_id in enumerate(to_import):
2221
self.pb.update('converting revision', i, len(to_import))
2222
self._convert_one_rev(rev_id)
2224
self._write_all_weaves()
2225
self._write_all_revs()
2226
ui.ui_factory.note('upgraded to weaves:')
2227
ui.ui_factory.note(' %6d revisions and inventories' % len(self.revisions))
2228
ui.ui_factory.note(' %6d revisions not present' % len(self.absent_revisions))
2229
ui.ui_factory.note(' %6d texts' % self.text_count)
2230
self._cleanup_spare_files_after_format4()
2231
self.branch._transport.put_bytes(
2233
BzrDirFormat5().get_format_string(),
2234
mode=self.bzrdir._get_file_mode())
2236
def _cleanup_spare_files_after_format4(self):
2237
# FIXME working tree upgrade foo.
2238
for n in 'merged-patches', 'pending-merged-patches':
2240
## assert os.path.getsize(p) == 0
2241
self.bzrdir.transport.delete(n)
2242
except errors.NoSuchFile:
2244
self.bzrdir.transport.delete_tree('inventory-store')
2245
self.bzrdir.transport.delete_tree('text-store')
2247
def _convert_working_inv(self):
2248
inv = xml4.serializer_v4.read_inventory(
2249
self.branch._transport.get('inventory'))
2250
new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv, working=True)
2251
self.branch._transport.put_bytes('inventory', new_inv_xml,
2252
mode=self.bzrdir._get_file_mode())
2254
def _write_all_weaves(self):
2255
controlweaves = VersionedFileStore(self.bzrdir.transport, prefixed=False,
2256
versionedfile_class=WeaveFile)
2257
weave_transport = self.bzrdir.transport.clone('weaves')
2258
weaves = VersionedFileStore(weave_transport, prefixed=False,
2259
versionedfile_class=WeaveFile)
2260
transaction = WriteTransaction()
2264
for file_id, file_weave in self.text_weaves.items():
2265
self.pb.update('writing weave', i, len(self.text_weaves))
2266
weaves._put_weave(file_id, file_weave, transaction)
2268
self.pb.update('inventory', 0, 1)
2269
controlweaves._put_weave('inventory', self.inv_weave, transaction)
2270
self.pb.update('inventory', 1, 1)
2274
def _write_all_revs(self):
2275
"""Write all revisions out in new form."""
2276
self.bzrdir.transport.delete_tree('revision-store')
2277
self.bzrdir.transport.mkdir('revision-store')
2278
revision_transport = self.bzrdir.transport.clone('revision-store')
2280
from bzrlib.xml5 import serializer_v5
2281
from bzrlib.repofmt.weaverepo import RevisionTextStore
2282
revision_store = RevisionTextStore(revision_transport,
2283
serializer_v5, False, versionedfile.PrefixMapper(),
2284
lambda:True, lambda:True)
2286
for i, rev_id in enumerate(self.converted_revs):
2287
self.pb.update('write revision', i, len(self.converted_revs))
2288
text = serializer_v5.write_revision_to_string(
2289
self.revisions[rev_id])
2291
revision_store.add_lines(key, None, osutils.split_lines(text))
2295
def _load_one_rev(self, rev_id):
2296
"""Load a revision object into memory.
2298
Any parents not either loaded or abandoned get queued to be
2300
self.pb.update('loading revision',
2301
len(self.revisions),
2302
len(self.known_revisions))
2303
if not self.branch.repository.has_revision(rev_id):
2305
ui.ui_factory.note('revision {%s} not present in branch; '
2306
'will be converted as a ghost' %
2308
self.absent_revisions.add(rev_id)
2310
rev = self.branch.repository.get_revision(rev_id)
2311
for parent_id in rev.parent_ids:
2312
self.known_revisions.add(parent_id)
2313
self.to_read.append(parent_id)
2314
self.revisions[rev_id] = rev
2316
def _load_old_inventory(self, rev_id):
2317
f = self.branch.repository.inventory_store.get(rev_id)
2319
old_inv_xml = f.read()
2322
inv = xml4.serializer_v4.read_inventory_from_string(old_inv_xml)
2323
inv.revision_id = rev_id
2324
rev = self.revisions[rev_id]
2327
def _load_updated_inventory(self, rev_id):
2328
inv_xml = self.inv_weave.get_text(rev_id)
2329
inv = xml5.serializer_v5.read_inventory_from_string(inv_xml, rev_id)
2332
def _convert_one_rev(self, rev_id):
2333
"""Convert revision and all referenced objects to new format."""
2334
rev = self.revisions[rev_id]
2335
inv = self._load_old_inventory(rev_id)
2336
present_parents = [p for p in rev.parent_ids
2337
if p not in self.absent_revisions]
2338
self._convert_revision_contents(rev, inv, present_parents)
2339
self._store_new_inv(rev, inv, present_parents)
2340
self.converted_revs.add(rev_id)
2342
def _store_new_inv(self, rev, inv, present_parents):
2343
new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
2344
new_inv_sha1 = sha_string(new_inv_xml)
2345
self.inv_weave.add_lines(rev.revision_id,
2347
new_inv_xml.splitlines(True))
2348
rev.inventory_sha1 = new_inv_sha1
2350
def _convert_revision_contents(self, rev, inv, present_parents):
2351
"""Convert all the files within a revision.
2353
Also upgrade the inventory to refer to the text revision ids."""
2354
rev_id = rev.revision_id
2355
mutter('converting texts of revision {%s}',
2357
parent_invs = map(self._load_updated_inventory, present_parents)
2358
entries = inv.iter_entries()
2360
for path, ie in entries:
2361
self._convert_file_version(rev, ie, parent_invs)
2363
def _convert_file_version(self, rev, ie, parent_invs):
2364
"""Convert one version of one file.
2366
The file needs to be added into the weave if it is a merge
2367
of >=2 parents or if it's changed from its parent.
2369
file_id = ie.file_id
2370
rev_id = rev.revision_id
2371
w = self.text_weaves.get(file_id)
2374
self.text_weaves[file_id] = w
2375
text_changed = False
2376
parent_candiate_entries = ie.parent_candidates(parent_invs)
2377
heads = graph.Graph(self).heads(parent_candiate_entries.keys())
2378
# XXX: Note that this is unordered - and this is tolerable because
2379
# the previous code was also unordered.
2380
previous_entries = dict((head, parent_candiate_entries[head]) for head
2382
self.snapshot_ie(previous_entries, ie, w, rev_id)
2384
def get_parent_map(self, revision_ids):
2385
"""See graph.StackedParentsProvider.get_parent_map"""
2386
return dict((revision_id, self.revisions[revision_id])
2387
for revision_id in revision_ids
2388
if revision_id in self.revisions)
2390
def snapshot_ie(self, previous_revisions, ie, w, rev_id):
2391
# TODO: convert this logic, which is ~= snapshot to
2392
# a call to:. This needs the path figured out. rather than a work_tree
2393
# a v4 revision_tree can be given, or something that looks enough like
2394
# one to give the file content to the entry if it needs it.
2395
# and we need something that looks like a weave store for snapshot to
2397
#ie.snapshot(rev, PATH, previous_revisions, REVISION_TREE, InMemoryWeaveStore(self.text_weaves))
2398
if len(previous_revisions) == 1:
2399
previous_ie = previous_revisions.values()[0]
2400
if ie._unchanged(previous_ie):
2401
ie.revision = previous_ie.revision
2404
f = self.branch.repository._text_store.get(ie.text_id)
2406
file_lines = f.readlines()
2409
w.add_lines(rev_id, previous_revisions, file_lines)
2410
self.text_count += 1
2412
w.add_lines(rev_id, previous_revisions, [])
2413
ie.revision = rev_id
2415
def _make_order(self):
2416
"""Return a suitable order for importing revisions.
2418
The order must be such that an revision is imported after all
2419
its (present) parents.
2421
todo = set(self.revisions.keys())
2422
done = self.absent_revisions.copy()
2425
# scan through looking for a revision whose parents
2427
for rev_id in sorted(list(todo)):
2428
rev = self.revisions[rev_id]
2429
parent_ids = set(rev.parent_ids)
2430
if parent_ids.issubset(done):
2431
# can take this one now
2432
order.append(rev_id)
2438
class ConvertBzrDir5To6(Converter):
2439
"""Converts format 5 bzr dirs to format 6."""
2441
def convert(self, to_convert, pb):
2442
"""See Converter.convert()."""
2443
self.bzrdir = to_convert
2444
pb = ui.ui_factory.nested_progress_bar()
2446
ui.ui_factory.note('starting upgrade from format 5 to 6')
2447
self._convert_to_prefixed()
2448
return BzrDir.open(self.bzrdir.user_url)
2452
def _convert_to_prefixed(self):
2453
from bzrlib.store import TransportStore
2454
self.bzrdir.transport.delete('branch-format')
2455
for store_name in ["weaves", "revision-store"]:
2456
ui.ui_factory.note("adding prefixes to %s" % store_name)
2457
store_transport = self.bzrdir.transport.clone(store_name)
2458
store = TransportStore(store_transport, prefixed=True)
2459
for urlfilename in store_transport.list_dir('.'):
2460
filename = urlutils.unescape(urlfilename)
2461
if (filename.endswith(".weave") or
2462
filename.endswith(".gz") or
2463
filename.endswith(".sig")):
2464
file_id, suffix = os.path.splitext(filename)
2468
new_name = store._mapper.map((file_id,)) + suffix
2469
# FIXME keep track of the dirs made RBC 20060121
2471
store_transport.move(filename, new_name)
2472
except errors.NoSuchFile: # catches missing dirs strangely enough
2473
store_transport.mkdir(osutils.dirname(new_name))
2474
store_transport.move(filename, new_name)
2475
self.bzrdir.transport.put_bytes(
2477
BzrDirFormat6().get_format_string(),
2478
mode=self.bzrdir._get_file_mode())
2481
class ConvertBzrDir6ToMeta(Converter):
2482
"""Converts format 6 bzr dirs to metadirs."""
2484
def convert(self, to_convert, pb):
2485
"""See Converter.convert()."""
2486
from bzrlib.repofmt.weaverepo import RepositoryFormat7
2487
from bzrlib.branch import BzrBranchFormat5
2488
self.bzrdir = to_convert
2489
self.pb = ui.ui_factory.nested_progress_bar()
2491
self.total = 20 # the steps we know about
2492
self.garbage_inventories = []
2493
self.dir_mode = self.bzrdir._get_dir_mode()
2494
self.file_mode = self.bzrdir._get_file_mode()
2496
ui.ui_factory.note('starting upgrade from format 6 to metadir')
2497
self.bzrdir.transport.put_bytes(
2499
"Converting to format 6",
2500
mode=self.file_mode)
2501
# its faster to move specific files around than to open and use the apis...
2502
# first off, nuke ancestry.weave, it was never used.
2504
self.step('Removing ancestry.weave')
2505
self.bzrdir.transport.delete('ancestry.weave')
2506
except errors.NoSuchFile:
2508
# find out whats there
2509
self.step('Finding branch files')
2510
last_revision = self.bzrdir.open_branch().last_revision()
2511
bzrcontents = self.bzrdir.transport.list_dir('.')
2512
for name in bzrcontents:
2513
if name.startswith('basis-inventory.'):
2514
self.garbage_inventories.append(name)
2515
# create new directories for repository, working tree and branch
2516
repository_names = [('inventory.weave', True),
2517
('revision-store', True),
2519
self.step('Upgrading repository ')
2520
self.bzrdir.transport.mkdir('repository', mode=self.dir_mode)
2521
self.make_lock('repository')
2522
# we hard code the formats here because we are converting into
2523
# the meta format. The meta format upgrader can take this to a
2524
# future format within each component.
2525
self.put_format('repository', RepositoryFormat7())
2526
for entry in repository_names:
2527
self.move_entry('repository', entry)
2529
self.step('Upgrading branch ')
2530
self.bzrdir.transport.mkdir('branch', mode=self.dir_mode)
2531
self.make_lock('branch')
2532
self.put_format('branch', BzrBranchFormat5())
2533
branch_files = [('revision-history', True),
2534
('branch-name', True),
2536
for entry in branch_files:
2537
self.move_entry('branch', entry)
2539
checkout_files = [('pending-merges', True),
2540
('inventory', True),
2541
('stat-cache', False)]
2542
# If a mandatory checkout file is not present, the branch does not have
2543
# a functional checkout. Do not create a checkout in the converted
2545
for name, mandatory in checkout_files:
2546
if mandatory and name not in bzrcontents:
2547
has_checkout = False
2551
if not has_checkout:
2552
ui.ui_factory.note('No working tree.')
2553
# If some checkout files are there, we may as well get rid of them.
2554
for name, mandatory in checkout_files:
2555
if name in bzrcontents:
2556
self.bzrdir.transport.delete(name)
2558
from bzrlib.workingtree import WorkingTreeFormat3
2559
self.step('Upgrading working tree')
2560
self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
2561
self.make_lock('checkout')
2563
'checkout', WorkingTreeFormat3())
2564
self.bzrdir.transport.delete_multi(
2565
self.garbage_inventories, self.pb)
2566
for entry in checkout_files:
2567
self.move_entry('checkout', entry)
2568
if last_revision is not None:
2569
self.bzrdir.transport.put_bytes(
2570
'checkout/last-revision', last_revision)
2571
self.bzrdir.transport.put_bytes(
2573
BzrDirMetaFormat1().get_format_string(),
2574
mode=self.file_mode)
2576
return BzrDir.open(self.bzrdir.user_url)
2578
def make_lock(self, name):
2579
"""Make a lock for the new control dir name."""
2580
self.step('Make %s lock' % name)
2581
ld = lockdir.LockDir(self.bzrdir.transport,
2583
file_modebits=self.file_mode,
2584
dir_modebits=self.dir_mode)
2587
def move_entry(self, new_dir, entry):
2588
"""Move then entry name into new_dir."""
2590
mandatory = entry[1]
2591
self.step('Moving %s' % name)
2593
self.bzrdir.transport.move(name, '%s/%s' % (new_dir, name))
2594
except errors.NoSuchFile:
2598
def put_format(self, dirname, format):
2599
self.bzrdir.transport.put_bytes('%s/format' % dirname,
2600
format.get_format_string(),
2604
class ConvertMetaToMeta(Converter):
2605
"""Converts the components of metadirs."""
2607
def __init__(self, target_format):
2608
"""Create a metadir to metadir converter.
2610
:param target_format: The final metadir format that is desired.
2612
self.target_format = target_format
2614
def convert(self, to_convert, pb):
2615
"""See Converter.convert()."""
2616
self.bzrdir = to_convert
2617
self.pb = ui.ui_factory.nested_progress_bar()
2620
self.step('checking repository format')
2622
repo = self.bzrdir.open_repository()
2623
except errors.NoRepositoryPresent:
2626
if not isinstance(repo._format, self.target_format.repository_format.__class__):
2627
from bzrlib.repository import CopyConverter
2628
ui.ui_factory.note('starting repository conversion')
2629
converter = CopyConverter(self.target_format.repository_format)
2630
converter.convert(repo, pb)
2631
for branch in self.bzrdir.list_branches():
2632
# TODO: conversions of Branch and Tree should be done by
2633
# InterXFormat lookups/some sort of registry.
2634
# Avoid circular imports
2635
from bzrlib import branch as _mod_branch
2636
old = branch._format.__class__
2637
new = self.target_format.get_branch_format().__class__
2639
if (old == _mod_branch.BzrBranchFormat5 and
2640
new in (_mod_branch.BzrBranchFormat6,
2641
_mod_branch.BzrBranchFormat7,
2642
_mod_branch.BzrBranchFormat8)):
2643
branch_converter = _mod_branch.Converter5to6()
2644
elif (old == _mod_branch.BzrBranchFormat6 and
2645
new in (_mod_branch.BzrBranchFormat7,
2646
_mod_branch.BzrBranchFormat8)):
2647
branch_converter = _mod_branch.Converter6to7()
2648
elif (old == _mod_branch.BzrBranchFormat7 and
2649
new is _mod_branch.BzrBranchFormat8):
2650
branch_converter = _mod_branch.Converter7to8()
2652
raise errors.BadConversionTarget("No converter", new,
2654
branch_converter.convert(branch)
2655
branch = self.bzrdir.open_branch()
2656
old = branch._format.__class__
2658
tree = self.bzrdir.open_workingtree(recommend_upgrade=False)
2659
except (errors.NoWorkingTree, errors.NotLocalUrl):
2662
# TODO: conversions of Branch and Tree should be done by
2663
# InterXFormat lookups
2664
if (isinstance(tree, workingtree.WorkingTree3) and
2665
not isinstance(tree, workingtree_4.DirStateWorkingTree) and
2666
isinstance(self.target_format.workingtree_format,
2667
workingtree_4.DirStateWorkingTreeFormat)):
2668
workingtree_4.Converter3to4().convert(tree)
2669
if (isinstance(tree, workingtree_4.DirStateWorkingTree) and
2670
not isinstance(tree, workingtree_4.WorkingTree5) and
2671
isinstance(self.target_format.workingtree_format,
2672
workingtree_4.WorkingTreeFormat5)):
2673
workingtree_4.Converter4to5().convert(tree)
2674
if (isinstance(tree, workingtree_4.DirStateWorkingTree) and
2675
not isinstance(tree, workingtree_4.WorkingTree6) and
2676
isinstance(self.target_format.workingtree_format,
2677
workingtree_4.WorkingTreeFormat6)):
2678
workingtree_4.Converter4or5to6().convert(tree)
2683
# This is not in remote.py because it's relatively small, and needs to be
2684
# registered. Putting it in remote.py creates a circular import problem.
2685
# we can make it a lazy object if the control formats is turned into something
2687
class RemoteBzrDirFormat(BzrDirMetaFormat1):
2688
"""Format representing bzrdirs accessed via a smart server"""
2690
supports_workingtrees = False
2693
BzrDirMetaFormat1.__init__(self)
2694
# XXX: It's a bit ugly that the network name is here, because we'd
2695
# like to believe that format objects are stateless or at least
2696
# immutable, However, we do at least avoid mutating the name after
2697
# it's returned. See <https://bugs.launchpad.net/bzr/+bug/504102>
2698
self._network_name = None
2701
return "%s(_network_name=%r)" % (self.__class__.__name__,
2704
def get_format_description(self):
2705
if self._network_name:
2706
real_format = controldir.network_format_registry.get(self._network_name)
2707
return 'Remote: ' + real_format.get_format_description()
2708
return 'bzr remote bzrdir'
2710
def get_format_string(self):
2711
raise NotImplementedError(self.get_format_string)
2713
def network_name(self):
2714
if self._network_name:
2715
return self._network_name
2717
raise AssertionError("No network name set.")
2719
def initialize_on_transport(self, transport):
2721
# hand off the request to the smart server
2722
client_medium = transport.get_smart_medium()
2723
except errors.NoSmartMedium:
2724
# TODO: lookup the local format from a server hint.
2725
local_dir_format = BzrDirMetaFormat1()
2726
return local_dir_format.initialize_on_transport(transport)
2727
client = _SmartClient(client_medium)
2728
path = client.remote_path_from_transport(transport)
2730
response = client.call('BzrDirFormat.initialize', path)
2731
except errors.ErrorFromSmartServer, err:
2732
remote._translate_error(err, path=path)
2733
if response[0] != 'ok':
2734
raise errors.SmartProtocolError('unexpected response code %s' % (response,))
2735
format = RemoteBzrDirFormat()
2736
self._supply_sub_formats_to(format)
2737
return remote.RemoteBzrDir(transport, format)
2739
def parse_NoneTrueFalse(self, arg):
2746
raise AssertionError("invalid arg %r" % arg)
2748
def _serialize_NoneTrueFalse(self, arg):
2755
def _serialize_NoneString(self, arg):
2758
def initialize_on_transport_ex(self, transport, use_existing_dir=False,
2759
create_prefix=False, force_new_repo=False, stacked_on=None,
2760
stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
2763
# hand off the request to the smart server
2764
client_medium = transport.get_smart_medium()
2765
except errors.NoSmartMedium:
2768
# Decline to open it if the server doesn't support our required
2769
# version (3) so that the VFS-based transport will do it.
2770
if client_medium.should_probe():
2772
server_version = client_medium.protocol_version()
2773
if server_version != '2':
2777
except errors.SmartProtocolError:
2778
# Apparently there's no usable smart server there, even though
2779
# the medium supports the smart protocol.
2784
client = _SmartClient(client_medium)
2785
path = client.remote_path_from_transport(transport)
2786
if client_medium._is_remote_before((1, 16)):
2789
# TODO: lookup the local format from a server hint.
2790
local_dir_format = BzrDirMetaFormat1()
2791
self._supply_sub_formats_to(local_dir_format)
2792
return local_dir_format.initialize_on_transport_ex(transport,
2793
use_existing_dir=use_existing_dir, create_prefix=create_prefix,
2794
force_new_repo=force_new_repo, stacked_on=stacked_on,
2795
stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
2796
make_working_trees=make_working_trees, shared_repo=shared_repo,
2798
return self._initialize_on_transport_ex_rpc(client, path, transport,
2799
use_existing_dir, create_prefix, force_new_repo, stacked_on,
2800
stack_on_pwd, repo_format_name, make_working_trees, shared_repo)
2802
def _initialize_on_transport_ex_rpc(self, client, path, transport,
2803
use_existing_dir, create_prefix, force_new_repo, stacked_on,
2804
stack_on_pwd, repo_format_name, make_working_trees, shared_repo):
2806
args.append(self._serialize_NoneTrueFalse(use_existing_dir))
2807
args.append(self._serialize_NoneTrueFalse(create_prefix))
2808
args.append(self._serialize_NoneTrueFalse(force_new_repo))
2809
args.append(self._serialize_NoneString(stacked_on))
2810
# stack_on_pwd is often/usually our transport
2813
stack_on_pwd = transport.relpath(stack_on_pwd)
2814
if not stack_on_pwd:
2816
except errors.PathNotChild:
2818
args.append(self._serialize_NoneString(stack_on_pwd))
2819
args.append(self._serialize_NoneString(repo_format_name))
2820
args.append(self._serialize_NoneTrueFalse(make_working_trees))
2821
args.append(self._serialize_NoneTrueFalse(shared_repo))
2822
request_network_name = self._network_name or \
2823
BzrDirFormat.get_default_format().network_name()
2825
response = client.call('BzrDirFormat.initialize_ex_1.16',
2826
request_network_name, path, *args)
2827
except errors.UnknownSmartMethod:
2828
client._medium._remember_remote_is_before((1,16))
2829
local_dir_format = BzrDirMetaFormat1()
2830
self._supply_sub_formats_to(local_dir_format)
2831
return local_dir_format.initialize_on_transport_ex(transport,
2832
use_existing_dir=use_existing_dir, create_prefix=create_prefix,
2833
force_new_repo=force_new_repo, stacked_on=stacked_on,
2834
stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
2835
make_working_trees=make_working_trees, shared_repo=shared_repo,
2837
except errors.ErrorFromSmartServer, err:
2838
remote._translate_error(err, path=path)
2839
repo_path = response[0]
2840
bzrdir_name = response[6]
2841
require_stacking = response[7]
2842
require_stacking = self.parse_NoneTrueFalse(require_stacking)
2843
format = RemoteBzrDirFormat()
2844
format._network_name = bzrdir_name
2845
self._supply_sub_formats_to(format)
2846
bzrdir = remote.RemoteBzrDir(transport, format, _client=client)
2848
repo_format = remote.response_tuple_to_repo_format(response[1:])
2849
if repo_path == '.':
2852
repo_bzrdir_format = RemoteBzrDirFormat()
2853
repo_bzrdir_format._network_name = response[5]
2854
repo_bzr = remote.RemoteBzrDir(transport.clone(repo_path),
2858
final_stack = response[8] or None
2859
final_stack_pwd = response[9] or None
2861
final_stack_pwd = urlutils.join(
2862
transport.base, final_stack_pwd)
2863
remote_repo = remote.RemoteRepository(repo_bzr, repo_format)
2864
if len(response) > 10:
2865
# Updated server verb that locks remotely.
2866
repo_lock_token = response[10] or None
2867
remote_repo.lock_write(repo_lock_token, _skip_rpc=True)
2869
remote_repo.dont_leave_lock_in_place()
2871
remote_repo.lock_write()
2872
policy = UseExistingRepository(remote_repo, final_stack,
2873
final_stack_pwd, require_stacking)
2874
policy.acquire_repository()
2878
bzrdir._format.set_branch_format(self.get_branch_format())
2879
if require_stacking:
2880
# The repo has already been created, but we need to make sure that
2881
# we'll make a stackable branch.
2882
bzrdir._format.require_stacking(_skip_repo=True)
2883
return remote_repo, bzrdir, require_stacking, policy
2885
def _open(self, transport):
2886
return remote.RemoteBzrDir(transport, self)
2888
def __eq__(self, other):
2889
if not isinstance(other, RemoteBzrDirFormat):
2891
return self.get_format_description() == other.get_format_description()
2893
def __return_repository_format(self):
2894
# Always return a RemoteRepositoryFormat object, but if a specific bzr
2895
# repository format has been asked for, tell the RemoteRepositoryFormat
2896
# that it should use that for init() etc.
2897
result = remote.RemoteRepositoryFormat()
2898
custom_format = getattr(self, '_repository_format', None)
2900
if isinstance(custom_format, remote.RemoteRepositoryFormat):
2901
return custom_format
2903
# We will use the custom format to create repositories over the
2904
# wire; expose its details like rich_root_data for code to
2906
result._custom_format = custom_format
2909
def get_branch_format(self):
2910
result = BzrDirMetaFormat1.get_branch_format(self)
2911
if not isinstance(result, remote.RemoteBranchFormat):
2912
new_result = remote.RemoteBranchFormat()
2913
new_result._custom_format = result
2915
self.set_branch_format(new_result)
2919
repository_format = property(__return_repository_format,
2920
BzrDirMetaFormat1._set_repository_format) #.im_func)
2923
controldir.ControlDirFormat.register_server_prober(RemoteBzrProber)
2926
class RepositoryAcquisitionPolicy(object):
2927
"""Abstract base class for repository acquisition policies.
2929
A repository acquisition policy decides how a BzrDir acquires a repository
2930
for a branch that is being created. The most basic policy decision is
2931
whether to create a new repository or use an existing one.
2933
def __init__(self, stack_on, stack_on_pwd, require_stacking):
2936
:param stack_on: A location to stack on
2937
:param stack_on_pwd: If stack_on is relative, the location it is
2939
:param require_stacking: If True, it is a failure to not stack.
2941
self._stack_on = stack_on
2942
self._stack_on_pwd = stack_on_pwd
2943
self._require_stacking = require_stacking
2945
def configure_branch(self, branch):
2946
"""Apply any configuration data from this policy to the branch.
2948
Default implementation sets repository stacking.
2950
if self._stack_on is None:
2952
if self._stack_on_pwd is None:
2953
stack_on = self._stack_on
2956
stack_on = urlutils.rebase_url(self._stack_on,
2959
except errors.InvalidRebaseURLs:
2960
stack_on = self._get_full_stack_on()
2962
branch.set_stacked_on_url(stack_on)
2963
except (errors.UnstackableBranchFormat,
2964
errors.UnstackableRepositoryFormat):
2965
if self._require_stacking:
2968
def requires_stacking(self):
2969
"""Return True if this policy requires stacking."""
2970
return self._stack_on is not None and self._require_stacking
2972
def _get_full_stack_on(self):
2973
"""Get a fully-qualified URL for the stack_on location."""
2974
if self._stack_on is None:
2976
if self._stack_on_pwd is None:
2977
return self._stack_on
2979
return urlutils.join(self._stack_on_pwd, self._stack_on)
2981
def _add_fallback(self, repository, possible_transports=None):
2982
"""Add a fallback to the supplied repository, if stacking is set."""
2983
stack_on = self._get_full_stack_on()
2984
if stack_on is None:
2987
stacked_dir = BzrDir.open(stack_on,
2988
possible_transports=possible_transports)
2989
except errors.JailBreak:
2990
# We keep the stacking details, but we are in the server code so
2991
# actually stacking is not needed.
2994
stacked_repo = stacked_dir.open_branch().repository
2995
except errors.NotBranchError:
2996
stacked_repo = stacked_dir.open_repository()
2998
repository.add_fallback_repository(stacked_repo)
2999
except errors.UnstackableRepositoryFormat:
3000
if self._require_stacking:
3003
self._require_stacking = True
3005
def acquire_repository(self, make_working_trees=None, shared=False):
3006
"""Acquire a repository for this bzrdir.
3008
Implementations may create a new repository or use a pre-exising
3010
:param make_working_trees: If creating a repository, set
3011
make_working_trees to this value (if non-None)
3012
:param shared: If creating a repository, make it shared if True
3013
:return: A repository, is_new_flag (True if the repository was
3016
raise NotImplemented(RepositoryAcquisitionPolicy.acquire_repository)
3019
class CreateRepository(RepositoryAcquisitionPolicy):
3020
"""A policy of creating a new repository"""
3022
def __init__(self, bzrdir, stack_on=None, stack_on_pwd=None,
3023
require_stacking=False):
3026
:param bzrdir: The bzrdir to create the repository on.
3027
:param stack_on: A location to stack on
3028
:param stack_on_pwd: If stack_on is relative, the location it is
3031
RepositoryAcquisitionPolicy.__init__(self, stack_on, stack_on_pwd,
3033
self._bzrdir = bzrdir
3035
def acquire_repository(self, make_working_trees=None, shared=False):
3036
"""Implementation of RepositoryAcquisitionPolicy.acquire_repository
3038
Creates the desired repository in the bzrdir we already have.
3040
stack_on = self._get_full_stack_on()
3042
format = self._bzrdir._format
3043
format.require_stacking(stack_on=stack_on,
3044
possible_transports=[self._bzrdir.root_transport])
3045
if not self._require_stacking:
3046
# We have picked up automatic stacking somewhere.
3047
note('Using default stacking branch %s at %s', self._stack_on,
3049
repository = self._bzrdir.create_repository(shared=shared)
3050
self._add_fallback(repository,
3051
possible_transports=[self._bzrdir.transport])
3052
if make_working_trees is not None:
3053
repository.set_make_working_trees(make_working_trees)
3054
return repository, True
3057
class UseExistingRepository(RepositoryAcquisitionPolicy):
3058
"""A policy of reusing an existing repository"""
3060
def __init__(self, repository, stack_on=None, stack_on_pwd=None,
3061
require_stacking=False):
3064
:param repository: The repository to use.
3065
:param stack_on: A location to stack on
3066
:param stack_on_pwd: If stack_on is relative, the location it is
3069
RepositoryAcquisitionPolicy.__init__(self, stack_on, stack_on_pwd,
3071
self._repository = repository
3073
def acquire_repository(self, make_working_trees=None, shared=False):
3074
"""Implementation of RepositoryAcquisitionPolicy.acquire_repository
3076
Returns an existing repository to use.
3078
self._add_fallback(self._repository,
3079
possible_transports=[self._repository.bzrdir.transport])
3080
return self._repository, False
3083
def register_metadir(registry, key,
3084
repository_format, help, native=True, deprecated=False,
3090
"""Register a metadir subformat.
3092
These all use a BzrDirMetaFormat1 bzrdir, but can be parameterized
3093
by the Repository/Branch/WorkingTreeformats.
3095
:param repository_format: The fully-qualified repository format class
3097
:param branch_format: Fully-qualified branch format class name as
3099
:param tree_format: Fully-qualified tree format class name as
3102
# This should be expanded to support setting WorkingTree and Branch
3103
# formats, once BzrDirMetaFormat1 supports that.
3104
def _load(full_name):
3105
mod_name, factory_name = full_name.rsplit('.', 1)
3107
factory = pyutils.get_named_object(mod_name, factory_name)
3108
except ImportError, e:
3109
raise ImportError('failed to load %s: %s' % (full_name, e))
3110
except AttributeError:
3111
raise AttributeError('no factory %s in module %r'
3112
% (full_name, sys.modules[mod_name]))
3116
bd = BzrDirMetaFormat1()
3117
if branch_format is not None:
3118
bd.set_branch_format(_load(branch_format))
3119
if tree_format is not None:
3120
bd.workingtree_format = _load(tree_format)
3121
if repository_format is not None:
3122
bd.repository_format = _load(repository_format)
3124
registry.register(key, helper, help, native, deprecated, hidden,
3125
experimental, alias)
3127
# The pre-0.8 formats have their repository format network name registered in
3128
# repository.py. MetaDir formats have their repository format network name
3129
# inferred from their disk format string.
3130
controldir.format_registry.register('weave', BzrDirFormat6,
3131
'Pre-0.8 format. Slower than knit and does not'
3132
' support checkouts or shared repositories.',
3135
register_metadir(controldir.format_registry, 'metaweave',
3136
'bzrlib.repofmt.weaverepo.RepositoryFormat7',
3137
'Transitional format in 0.8. Slower than knit.',
3138
branch_format='bzrlib.branch.BzrBranchFormat5',
3139
tree_format='bzrlib.workingtree.WorkingTreeFormat3',
3142
register_metadir(controldir.format_registry, 'knit',
3143
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
3144
'Format using knits. Recommended for interoperation with bzr <= 0.14.',
3145
branch_format='bzrlib.branch.BzrBranchFormat5',
3146
tree_format='bzrlib.workingtree.WorkingTreeFormat3',
3149
register_metadir(controldir.format_registry, 'dirstate',
3150
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
3151
help='New in 0.15: Fast local operations. Compatible with bzr 0.8 and '
3152
'above when accessed over the network.',
3153
branch_format='bzrlib.branch.BzrBranchFormat5',
3154
# this uses bzrlib.workingtree.WorkingTreeFormat4 because importing
3155
# directly from workingtree_4 triggers a circular import.
3156
tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
3159
register_metadir(controldir.format_registry, 'dirstate-tags',
3160
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
3161
help='New in 0.15: Fast local operations and improved scaling for '
3162
'network operations. Additionally adds support for tags.'
3163
' Incompatible with bzr < 0.15.',
3164
branch_format='bzrlib.branch.BzrBranchFormat6',
3165
tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
3168
register_metadir(controldir.format_registry, 'rich-root',
3169
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit4',
3170
help='New in 1.0. Better handling of tree roots. Incompatible with'
3172
branch_format='bzrlib.branch.BzrBranchFormat6',
3173
tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
3176
register_metadir(controldir.format_registry, 'dirstate-with-subtree',
3177
'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
3178
help='New in 0.15: Fast local operations and improved scaling for '
3179
'network operations. Additionally adds support for versioning nested '
3180
'bzr branches. Incompatible with bzr < 0.15.',
3181
branch_format='bzrlib.branch.BzrBranchFormat6',
3182
tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
3186
register_metadir(controldir.format_registry, 'pack-0.92',
3187
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack1',
3188
help='New in 0.92: Pack-based format with data compatible with '
3189
'dirstate-tags format repositories. Interoperates with '
3190
'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
3192
branch_format='bzrlib.branch.BzrBranchFormat6',
3193
tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
3195
register_metadir(controldir.format_registry, 'pack-0.92-subtree',
3196
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack3',
3197
help='New in 0.92: Pack-based format with data compatible with '
3198
'dirstate-with-subtree format repositories. Interoperates with '
3199
'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
3201
branch_format='bzrlib.branch.BzrBranchFormat6',
3202
tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
3206
register_metadir(controldir.format_registry, 'rich-root-pack',
3207
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack4',
3208
help='New in 1.0: A variant of pack-0.92 that supports rich-root data '
3209
'(needed for bzr-svn and bzr-git).',
3210
branch_format='bzrlib.branch.BzrBranchFormat6',
3211
tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
3214
register_metadir(controldir.format_registry, '1.6',
3215
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5',
3216
help='A format that allows a branch to indicate that there is another '
3217
'(stacked) repository that should be used to access data that is '
3218
'not present locally.',
3219
branch_format='bzrlib.branch.BzrBranchFormat7',
3220
tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
3223
register_metadir(controldir.format_registry, '1.6.1-rich-root',
3224
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5RichRoot',
3225
help='A variant of 1.6 that supports rich-root data '
3226
'(needed for bzr-svn and bzr-git).',
3227
branch_format='bzrlib.branch.BzrBranchFormat7',
3228
tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
3231
register_metadir(controldir.format_registry, '1.9',
3232
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
3233
help='A repository format using B+tree indexes. These indexes '
3234
'are smaller in size, have smarter caching and provide faster '
3235
'performance for most operations.',
3236
branch_format='bzrlib.branch.BzrBranchFormat7',
3237
tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
3240
register_metadir(controldir.format_registry, '1.9-rich-root',
3241
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
3242
help='A variant of 1.9 that supports rich-root data '
3243
'(needed for bzr-svn and bzr-git).',
3244
branch_format='bzrlib.branch.BzrBranchFormat7',
3245
tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
3248
register_metadir(controldir.format_registry, '1.14',
3249
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
3250
help='A working-tree format that supports content filtering.',
3251
branch_format='bzrlib.branch.BzrBranchFormat7',
3252
tree_format='bzrlib.workingtree_4.WorkingTreeFormat5',
3254
register_metadir(controldir.format_registry, '1.14-rich-root',
3255
'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
3256
help='A variant of 1.14 that supports rich-root data '
3257
'(needed for bzr-svn and bzr-git).',
3258
branch_format='bzrlib.branch.BzrBranchFormat7',
3259
tree_format='bzrlib.workingtree_4.WorkingTreeFormat5',
3261
# The following un-numbered 'development' formats should always just be aliases.
3262
register_metadir(controldir.format_registry, 'development-subtree',
3263
'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2aSubtree',
3264
help='Current development format, subtree variant. Can convert data to and '
3265
'from pack-0.92-subtree (and anything compatible with '
3266
'pack-0.92-subtree) format repositories. Repositories and branches in '
3267
'this format can only be read by bzr.dev. Please read '
3268
'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
3270
branch_format='bzrlib.branch.BzrBranchFormat7',
3271
tree_format='bzrlib.workingtree_4.WorkingTreeFormat6',
3274
alias=False, # Restore to being an alias when an actual development subtree format is added
3275
# This current non-alias status is simply because we did not introduce a
3276
# chk based subtree format.
3278
register_metadir(controldir.format_registry, 'development5-subtree',
3279
'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment2Subtree',
3280
help='Development format, subtree variant. Can convert data to and '
3281
'from pack-0.92-subtree (and anything compatible with '
3282
'pack-0.92-subtree) format repositories. Repositories and branches in '
3283
'this format can only be read by bzr.dev. Please read '
3284
'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
3286
branch_format='bzrlib.branch.BzrBranchFormat7',
3287
tree_format='bzrlib.workingtree_4.WorkingTreeFormat6',
3293
# And the development formats above will have aliased one of the following:
3295
# Finally, the current format.
3296
register_metadir(controldir.format_registry, '2a',
3297
'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2a',
3298
help='First format for bzr 2.0 series.\n'
3299
'Uses group-compress storage.\n'
3300
'Provides rich roots which are a one-way transition.\n',
3301
# 'storage in packs, 255-way hashed CHK inventory, bencode revision, group compress, '
3302
# 'rich roots. Supported by bzr 1.16 and later.',
3303
branch_format='bzrlib.branch.BzrBranchFormat7',
3304
tree_format='bzrlib.workingtree_4.WorkingTreeFormat6',
3308
# The following format should be an alias for the rich root equivalent
3309
# of the default format
3310
register_metadir(controldir.format_registry, 'default-rich-root',
3311
'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2a',
3312
branch_format='bzrlib.branch.BzrBranchFormat7',
3313
tree_format='bzrlib.workingtree_4.WorkingTreeFormat6',
3318
# The current format that is made on 'bzr init'.
3319
format_name = config.GlobalConfig().get_user_option('default_format')
3320
if format_name is None:
3321
controldir.format_registry.set_default('2a')
3323
controldir.format_registry.set_default(format_name)
3325
# XXX 2010-08-20 JRV: There is still a lot of code relying on
3326
# bzrlib.bzrdir.format_registry existing. When BzrDir.create/BzrDir.open/etc
3327
# get changed to ControlDir.create/ControlDir.open/etc this should be removed.
3328
format_registry = controldir.format_registry