1
# Copyright (C) 2005, 2006 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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
23
# TODO: remove unittest dependency; put that stuff inside the test suite
25
# TODO: The Format probe_transport seems a bit redundant with just trying to
26
# open the bzrdir. -- mbp
28
# TODO: Can we move specific formats into separate modules to make this file
31
from cStringIO import StringIO
35
from bzrlib.lazy_import import lazy_import
36
lazy_import(globals(), """
37
from copy import deepcopy
38
from stat import S_ISDIR
47
revision as _mod_revision,
48
repository as _mod_repository,
53
from bzrlib.osutils import (
58
from bzrlib.store.revision.text import TextRevisionStore
59
from bzrlib.store.text import TextStore
60
from bzrlib.store.versioned import WeaveStore
61
from bzrlib.transactions import WriteTransaction
62
from bzrlib.transport import get_transport
63
from bzrlib.weave import Weave
66
from bzrlib.trace import mutter
67
from bzrlib.transport.local import LocalTransport
71
"""A .bzr control diretory.
73
BzrDir instances let you create or open any of the things that can be
74
found within .bzr - checkouts, branches and repositories.
77
the transport which this bzr dir is rooted at (i.e. file:///.../.bzr/)
79
a transport connected to the directory this bzr was opened from.
83
"""Invoke break_lock on the first object in the bzrdir.
85
If there is a tree, the tree is opened and break_lock() called.
86
Otherwise, branch is tried, and finally repository.
89
thing_to_unlock = self.open_workingtree()
90
except (errors.NotLocalUrl, errors.NoWorkingTree):
92
thing_to_unlock = self.open_branch()
93
except errors.NotBranchError:
95
thing_to_unlock = self.open_repository()
96
except errors.NoRepositoryPresent:
98
thing_to_unlock.break_lock()
100
def can_convert_format(self):
101
"""Return true if this bzrdir is one whose format we can convert from."""
104
def check_conversion_target(self, target_format):
105
target_repo_format = target_format.repository_format
106
source_repo_format = self._format.repository_format
107
source_repo_format.check_conversion_target(target_repo_format)
110
def _check_supported(format, allow_unsupported):
111
"""Check whether format is a supported format.
113
If allow_unsupported is True, this is a no-op.
115
if not allow_unsupported and not format.is_supported():
116
# see open_downlevel to open legacy branches.
117
raise errors.UnsupportedFormatError(format=format)
119
def clone(self, url, revision_id=None, basis=None, force_new_repo=False):
120
"""Clone this bzrdir and its contents to url verbatim.
122
If urls last component does not exist, it will be created.
124
if revision_id is not None, then the clone operation may tune
125
itself to download less data.
126
:param force_new_repo: Do not use a shared repository for the target
127
even if one is available.
130
basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
131
result = self._format.initialize(url)
133
local_repo = self.find_repository()
134
except errors.NoRepositoryPresent:
137
# may need to copy content in
139
result_repo = local_repo.clone(
141
revision_id=revision_id,
143
result_repo.set_make_working_trees(local_repo.make_working_trees())
146
result_repo = result.find_repository()
147
# fetch content this dir needs.
149
# XXX FIXME RBC 20060214 need tests for this when the basis
151
result_repo.fetch(basis_repo, revision_id=revision_id)
152
result_repo.fetch(local_repo, revision_id=revision_id)
153
except errors.NoRepositoryPresent:
154
# needed to make one anyway.
155
result_repo = local_repo.clone(
157
revision_id=revision_id,
159
result_repo.set_make_working_trees(local_repo.make_working_trees())
160
# 1 if there is a branch present
161
# make sure its content is available in the target repository
164
self.open_branch().clone(result, revision_id=revision_id)
165
except errors.NotBranchError:
168
self.open_workingtree().clone(result, basis=basis_tree)
169
except (errors.NoWorkingTree, errors.NotLocalUrl):
173
def _get_basis_components(self, basis):
174
"""Retrieve the basis components that are available at basis."""
176
return None, None, None
178
basis_tree = basis.open_workingtree()
179
basis_branch = basis_tree.branch
180
basis_repo = basis_branch.repository
181
except (errors.NoWorkingTree, errors.NotLocalUrl):
184
basis_branch = basis.open_branch()
185
basis_repo = basis_branch.repository
186
except errors.NotBranchError:
189
basis_repo = basis.open_repository()
190
except errors.NoRepositoryPresent:
192
return basis_repo, basis_branch, basis_tree
194
# TODO: This should be given a Transport, and should chdir up; otherwise
195
# this will open a new connection.
196
def _make_tail(self, url):
197
head, tail = urlutils.split(url)
198
if tail and tail != '.':
199
t = get_transport(head)
202
except errors.FileExists:
205
# TODO: Should take a Transport
207
def create(cls, base):
208
"""Create a new BzrDir at the url 'base'.
210
This will call the current default formats initialize with base
211
as the only parameter.
213
If you need a specific format, consider creating an instance
214
of that and calling initialize().
216
if cls is not BzrDir:
217
raise AssertionError("BzrDir.create always creates the default format, "
218
"not one of %r" % cls)
219
head, tail = urlutils.split(base)
220
if tail and tail != '.':
221
t = get_transport(head)
224
except errors.FileExists:
226
return BzrDirFormat.get_default_format().initialize(safe_unicode(base))
228
def create_branch(self):
229
"""Create a branch in this BzrDir.
231
The bzrdirs format will control what branch format is created.
232
For more control see BranchFormatXX.create(a_bzrdir).
234
raise NotImplementedError(self.create_branch)
237
def create_branch_and_repo(base, force_new_repo=False):
238
"""Create a new BzrDir, Branch and Repository at the url 'base'.
240
This will use the current default BzrDirFormat, and use whatever
241
repository format that that uses via bzrdir.create_branch and
242
create_repository. If a shared repository is available that is used
245
The created Branch object is returned.
247
:param base: The URL to create the branch at.
248
:param force_new_repo: If True a new repository is always created.
250
bzrdir = BzrDir.create(base)
251
bzrdir._find_or_create_repository(force_new_repo)
252
return bzrdir.create_branch()
254
def _find_or_create_repository(self, force_new_repo):
255
"""Create a new repository if needed, returning the repository."""
257
return self.create_repository()
259
return self.find_repository()
260
except errors.NoRepositoryPresent:
261
return self.create_repository()
264
def create_branch_convenience(base, force_new_repo=False,
265
force_new_tree=None, format=None):
266
"""Create a new BzrDir, Branch and Repository at the url 'base'.
268
This is a convenience function - it will use an existing repository
269
if possible, can be told explicitly whether to create a working tree or
272
This will use the current default BzrDirFormat, and use whatever
273
repository format that that uses via bzrdir.create_branch and
274
create_repository. If a shared repository is available that is used
275
preferentially. Whatever repository is used, its tree creation policy
278
The created Branch object is returned.
279
If a working tree cannot be made due to base not being a file:// url,
280
no error is raised unless force_new_tree is True, in which case no
281
data is created on disk and NotLocalUrl is raised.
283
:param base: The URL to create the branch at.
284
:param force_new_repo: If True a new repository is always created.
285
:param force_new_tree: If True or False force creation of a tree or
286
prevent such creation respectively.
287
:param format: Override for the for the bzrdir format to create
290
# check for non local urls
291
t = get_transport(safe_unicode(base))
292
if not isinstance(t, LocalTransport):
293
raise errors.NotLocalUrl(base)
295
bzrdir = BzrDir.create(base)
297
bzrdir = format.initialize(base)
298
repo = bzrdir._find_or_create_repository(force_new_repo)
299
result = bzrdir.create_branch()
300
if force_new_tree or (repo.make_working_trees() and
301
force_new_tree is None):
303
bzrdir.create_workingtree()
304
except errors.NotLocalUrl:
309
def create_repository(base, shared=False):
310
"""Create a new BzrDir and Repository at the url 'base'.
312
This will use the current default BzrDirFormat, and use whatever
313
repository format that that uses for bzrdirformat.create_repository.
315
:param shared: Create a shared repository rather than a standalone
317
The Repository object is returned.
319
This must be overridden as an instance method in child classes, where
320
it should take no parameters and construct whatever repository format
321
that child class desires.
323
bzrdir = BzrDir.create(base)
324
return bzrdir.create_repository(shared)
327
def create_standalone_workingtree(base):
328
"""Create a new BzrDir, WorkingTree, Branch and Repository at 'base'.
330
'base' must be a local path or a file:// url.
332
This will use the current default BzrDirFormat, and use whatever
333
repository format that that uses for bzrdirformat.create_workingtree,
334
create_branch and create_repository.
336
:return: The WorkingTree object.
338
t = get_transport(safe_unicode(base))
339
if not isinstance(t, LocalTransport):
340
raise errors.NotLocalUrl(base)
341
bzrdir = BzrDir.create_branch_and_repo(safe_unicode(base),
342
force_new_repo=True).bzrdir
343
return bzrdir.create_workingtree()
345
def create_workingtree(self, revision_id=None):
346
"""Create a working tree at this BzrDir.
348
revision_id: create it as of this revision id.
350
raise NotImplementedError(self.create_workingtree)
352
def destroy_workingtree(self):
353
"""Destroy the working tree at this BzrDir.
355
Formats that do not support this may raise UnsupportedOperation.
357
raise NotImplementedError(self.destroy_workingtree)
359
def destroy_workingtree_metadata(self):
360
"""Destroy the control files for the working tree at this BzrDir.
362
The contents of working tree files are not affected.
363
Formats that do not support this may raise UnsupportedOperation.
365
raise NotImplementedError(self.destroy_workingtree_metadata)
367
def find_repository(self):
368
"""Find the repository that should be used for a_bzrdir.
370
This does not require a branch as we use it to find the repo for
371
new branches as well as to hook existing branches up to their
375
return self.open_repository()
376
except errors.NoRepositoryPresent:
378
next_transport = self.root_transport.clone('..')
380
# find the next containing bzrdir
382
found_bzrdir = BzrDir.open_containing_from_transport(
384
except errors.NotBranchError:
386
raise errors.NoRepositoryPresent(self)
387
# does it have a repository ?
389
repository = found_bzrdir.open_repository()
390
except errors.NoRepositoryPresent:
391
next_transport = found_bzrdir.root_transport.clone('..')
392
if (found_bzrdir.root_transport.base == next_transport.base):
393
# top of the file system
397
if ((found_bzrdir.root_transport.base ==
398
self.root_transport.base) or repository.is_shared()):
401
raise errors.NoRepositoryPresent(self)
402
raise errors.NoRepositoryPresent(self)
404
def get_branch_transport(self, branch_format):
405
"""Get the transport for use by branch format in this BzrDir.
407
Note that bzr dirs that do not support format strings will raise
408
IncompatibleFormat if the branch format they are given has
409
a format string, and vice versa.
411
If branch_format is None, the transport is returned with no
412
checking. if it is not None, then the returned transport is
413
guaranteed to point to an existing directory ready for use.
415
raise NotImplementedError(self.get_branch_transport)
417
def get_repository_transport(self, repository_format):
418
"""Get the transport for use by repository format in this BzrDir.
420
Note that bzr dirs that do not support format strings will raise
421
IncompatibleFormat if the repository format they are given has
422
a format string, and vice versa.
424
If repository_format is None, the transport is returned with no
425
checking. if it is not None, then the returned transport is
426
guaranteed to point to an existing directory ready for use.
428
raise NotImplementedError(self.get_repository_transport)
430
def get_workingtree_transport(self, tree_format):
431
"""Get the transport for use by workingtree format in this BzrDir.
433
Note that bzr dirs that do not support format strings will raise
434
IncompatibleFormat if the workingtree format they are given has
435
a format string, and vice versa.
437
If workingtree_format is None, the transport is returned with no
438
checking. if it is not None, then the returned transport is
439
guaranteed to point to an existing directory ready for use.
441
raise NotImplementedError(self.get_workingtree_transport)
443
def __init__(self, _transport, _format):
444
"""Initialize a Bzr control dir object.
446
Only really common logic should reside here, concrete classes should be
447
made with varying behaviours.
449
:param _format: the format that is creating this BzrDir instance.
450
:param _transport: the transport this dir is based at.
452
self._format = _format
453
self.transport = _transport.clone('.bzr')
454
self.root_transport = _transport
456
def is_control_filename(self, filename):
457
"""True if filename is the name of a path which is reserved for bzrdir's.
459
:param filename: A filename within the root transport of this bzrdir.
461
This is true IF and ONLY IF the filename is part of the namespace reserved
462
for bzr control dirs. Currently this is the '.bzr' directory in the root
463
of the root_transport. it is expected that plugins will need to extend
464
this in the future - for instance to make bzr talk with svn working
467
# this might be better on the BzrDirFormat class because it refers to
468
# all the possible bzrdir disk formats.
469
# This method is tested via the workingtree is_control_filename tests-
470
# it was extracted from WorkingTree.is_control_filename. If the methods
471
# contract is extended beyond the current trivial implementation please
472
# add new tests for it to the appropriate place.
473
return filename == '.bzr' or filename.startswith('.bzr/')
475
def needs_format_conversion(self, format=None):
476
"""Return true if this bzrdir needs convert_format run on it.
478
For instance, if the repository format is out of date but the
479
branch and working tree are not, this should return True.
481
:param format: Optional parameter indicating a specific desired
482
format we plan to arrive at.
484
raise NotImplementedError(self.needs_format_conversion)
487
def open_unsupported(base):
488
"""Open a branch which is not supported."""
489
return BzrDir.open(base, _unsupported=True)
492
def open(base, _unsupported=False):
493
"""Open an existing bzrdir, rooted at 'base' (url)
495
_unsupported is a private parameter to the BzrDir class.
497
t = get_transport(base)
498
return BzrDir.open_from_transport(t, _unsupported=_unsupported)
501
def open_from_transport(transport, _unsupported=False):
502
"""Open a bzrdir within a particular directory.
504
:param transport: Transport containing the bzrdir.
505
:param _unsupported: private.
507
format = BzrDirFormat.find_format(transport)
508
BzrDir._check_supported(format, _unsupported)
509
return format.open(transport, _found=True)
511
def open_branch(self, unsupported=False):
512
"""Open the branch object at this BzrDir if one is present.
514
If unsupported is True, then no longer supported branch formats can
517
TODO: static convenience version of this?
519
raise NotImplementedError(self.open_branch)
522
def open_containing(url):
523
"""Open an existing branch which contains url.
525
:param url: url to search from.
526
See open_containing_from_transport for more detail.
528
return BzrDir.open_containing_from_transport(get_transport(url))
531
def open_containing_from_transport(a_transport):
532
"""Open an existing branch which contains a_transport.base
534
This probes for a branch at a_transport, and searches upwards from there.
536
Basically we keep looking up until we find the control directory or
537
run into the root. If there isn't one, raises NotBranchError.
538
If there is one and it is either an unrecognised format or an unsupported
539
format, UnknownFormatError or UnsupportedFormatError are raised.
540
If there is one, it is returned, along with the unused portion of url.
542
:return: The BzrDir that contains the path, and a Unicode path
543
for the rest of the URL.
545
# this gets the normalised url back. I.e. '.' -> the full path.
546
url = a_transport.base
549
result = BzrDir.open_from_transport(a_transport)
550
return result, urlutils.unescape(a_transport.relpath(url))
551
except errors.NotBranchError, e:
553
new_t = a_transport.clone('..')
554
if new_t.base == a_transport.base:
555
# reached the root, whatever that may be
556
raise errors.NotBranchError(path=url)
559
def open_repository(self, _unsupported=False):
560
"""Open the repository object at this BzrDir if one is present.
562
This will not follow the Branch object pointer - its strictly a direct
563
open facility. Most client code should use open_branch().repository to
566
_unsupported is a private parameter, not part of the api.
567
TODO: static convenience version of this?
569
raise NotImplementedError(self.open_repository)
571
def open_workingtree(self, _unsupported=False):
572
"""Open the workingtree object at this BzrDir if one is present.
574
TODO: static convenience version of this?
576
raise NotImplementedError(self.open_workingtree)
578
def has_branch(self):
579
"""Tell if this bzrdir contains a branch.
581
Note: if you're going to open the branch, you should just go ahead
582
and try, and not ask permission first. (This method just opens the
583
branch and discards it, and that's somewhat expensive.)
588
except errors.NotBranchError:
591
def has_workingtree(self):
592
"""Tell if this bzrdir contains a working tree.
594
This will still raise an exception if the bzrdir has a workingtree that
595
is remote & inaccessible.
597
Note: if you're going to open the working tree, you should just go ahead
598
and try, and not ask permission first. (This method just opens the
599
workingtree and discards it, and that's somewhat expensive.)
602
self.open_workingtree()
604
except errors.NoWorkingTree:
607
def cloning_metadir(self, basis=None):
608
"""Produce a metadir suitable for cloning with"""
609
def related_repository(bzrdir):
611
branch = bzrdir.open_branch()
612
return branch.repository
613
except errors.NotBranchError:
615
return bzrdir.open_repository()
616
result_format = self._format.__class__()
619
source_repository = related_repository(self)
620
except errors.NoRepositoryPresent:
623
source_repository = related_repository(self)
624
result_format.repository_format = source_repository._format
625
except errors.NoRepositoryPresent:
629
def sprout(self, url, revision_id=None, basis=None, force_new_repo=False):
630
"""Create a copy of this bzrdir prepared for use as a new line of
633
If urls last component does not exist, it will be created.
635
Attributes related to the identity of the source branch like
636
branch nickname will be cleaned, a working tree is created
637
whether one existed before or not; and a local branch is always
640
if revision_id is not None, then the clone operation may tune
641
itself to download less data.
644
cloning_format = self.cloning_metadir(basis)
645
result = cloning_format.initialize(url)
646
basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
648
source_branch = self.open_branch()
649
source_repository = source_branch.repository
650
except errors.NotBranchError:
653
source_repository = self.open_repository()
654
except errors.NoRepositoryPresent:
655
# copy the entire basis one if there is one
656
# but there is no repository.
657
source_repository = basis_repo
662
result_repo = result.find_repository()
663
except errors.NoRepositoryPresent:
665
if source_repository is None and result_repo is not None:
667
elif source_repository is None and result_repo is None:
668
# no repo available, make a new one
669
result.create_repository()
670
elif source_repository is not None and result_repo is None:
671
# have source, and want to make a new target repo
672
# we don't clone the repo because that preserves attributes
673
# like is_shared(), and we have not yet implemented a
674
# repository sprout().
675
result_repo = result.create_repository()
676
if result_repo is not None:
677
# fetch needed content into target.
679
# XXX FIXME RBC 20060214 need tests for this when the basis
681
result_repo.fetch(basis_repo, revision_id=revision_id)
682
if source_repository is not None:
683
result_repo.fetch(source_repository, revision_id=revision_id)
684
if source_branch is not None:
685
source_branch.sprout(result, revision_id=revision_id)
687
result.create_branch()
688
# TODO: jam 20060426 we probably need a test in here in the
689
# case that the newly sprouted branch is a remote one
690
if result_repo is None or result_repo.make_working_trees():
691
wt = result.create_workingtree()
692
if wt.inventory.root is None:
694
wt.set_root_id(self.open_workingtree.get_root_id())
695
except errors.NoWorkingTree:
700
class BzrDirPreSplitOut(BzrDir):
701
"""A common class for the all-in-one formats."""
703
def __init__(self, _transport, _format):
704
"""See BzrDir.__init__."""
705
super(BzrDirPreSplitOut, self).__init__(_transport, _format)
706
assert self._format._lock_class == lockable_files.TransportLock
707
assert self._format._lock_file_name == 'branch-lock'
708
self._control_files = lockable_files.LockableFiles(
709
self.get_branch_transport(None),
710
self._format._lock_file_name,
711
self._format._lock_class)
713
def break_lock(self):
714
"""Pre-splitout bzrdirs do not suffer from stale locks."""
715
raise NotImplementedError(self.break_lock)
717
def clone(self, url, revision_id=None, basis=None, force_new_repo=False):
718
"""See BzrDir.clone()."""
719
from bzrlib.workingtree import WorkingTreeFormat2
721
result = self._format._initialize_for_clone(url)
722
basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
723
self.open_repository().clone(result, revision_id=revision_id, basis=basis_repo)
724
from_branch = self.open_branch()
725
from_branch.clone(result, revision_id=revision_id)
727
self.open_workingtree().clone(result, basis=basis_tree)
728
except errors.NotLocalUrl:
729
# make a new one, this format always has to have one.
731
WorkingTreeFormat2().initialize(result)
732
except errors.NotLocalUrl:
733
# but we cannot do it for remote trees.
734
to_branch = result.open_branch()
735
WorkingTreeFormat2().stub_initialize_remote(to_branch.control_files)
738
def create_branch(self):
739
"""See BzrDir.create_branch."""
740
return self.open_branch()
742
def create_repository(self, shared=False):
743
"""See BzrDir.create_repository."""
745
raise errors.IncompatibleFormat('shared repository', self._format)
746
return self.open_repository()
748
def create_workingtree(self, revision_id=None):
749
"""See BzrDir.create_workingtree."""
750
# this looks buggy but is not -really-
751
# clone and sprout will have set the revision_id
752
# and that will have set it for us, its only
753
# specific uses of create_workingtree in isolation
754
# that can do wonky stuff here, and that only
755
# happens for creating checkouts, which cannot be
756
# done on this format anyway. So - acceptable wart.
757
result = self.open_workingtree()
758
if revision_id is not None:
759
if revision_id == _mod_revision.NULL_REVISION:
760
result.set_parent_ids([])
762
result.set_parent_ids([revision_id])
765
def destroy_workingtree(self):
766
"""See BzrDir.destroy_workingtree."""
767
raise errors.UnsupportedOperation(self.destroy_workingtree, self)
769
def destroy_workingtree_metadata(self):
770
"""See BzrDir.destroy_workingtree_metadata."""
771
raise errors.UnsupportedOperation(self.destroy_workingtree_metadata,
774
def get_branch_transport(self, branch_format):
775
"""See BzrDir.get_branch_transport()."""
776
if branch_format is None:
777
return self.transport
779
branch_format.get_format_string()
780
except NotImplementedError:
781
return self.transport
782
raise errors.IncompatibleFormat(branch_format, self._format)
784
def get_repository_transport(self, repository_format):
785
"""See BzrDir.get_repository_transport()."""
786
if repository_format is None:
787
return self.transport
789
repository_format.get_format_string()
790
except NotImplementedError:
791
return self.transport
792
raise errors.IncompatibleFormat(repository_format, self._format)
794
def get_workingtree_transport(self, workingtree_format):
795
"""See BzrDir.get_workingtree_transport()."""
796
if workingtree_format is None:
797
return self.transport
799
workingtree_format.get_format_string()
800
except NotImplementedError:
801
return self.transport
802
raise errors.IncompatibleFormat(workingtree_format, self._format)
804
def needs_format_conversion(self, format=None):
805
"""See BzrDir.needs_format_conversion()."""
806
# if the format is not the same as the system default,
807
# an upgrade is needed.
809
format = BzrDirFormat.get_default_format()
810
return not isinstance(self._format, format.__class__)
812
def open_branch(self, unsupported=False):
813
"""See BzrDir.open_branch."""
814
from bzrlib.branch import BzrBranchFormat4
815
format = BzrBranchFormat4()
816
self._check_supported(format, unsupported)
817
return format.open(self, _found=True)
819
def sprout(self, url, revision_id=None, basis=None, force_new_repo=False):
820
"""See BzrDir.sprout()."""
821
from bzrlib.workingtree import WorkingTreeFormat2
823
result = self._format._initialize_for_clone(url)
824
basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
826
self.open_repository().clone(result, revision_id=revision_id, basis=basis_repo)
827
except errors.NoRepositoryPresent:
830
self.open_branch().sprout(result, revision_id=revision_id)
831
except errors.NotBranchError:
833
# we always want a working tree
834
WorkingTreeFormat2().initialize(result)
838
class BzrDir4(BzrDirPreSplitOut):
839
"""A .bzr version 4 control object.
841
This is a deprecated format and may be removed after sept 2006.
844
def create_repository(self, shared=False):
845
"""See BzrDir.create_repository."""
846
return self._format.repository_format.initialize(self, shared)
848
def needs_format_conversion(self, format=None):
849
"""Format 4 dirs are always in need of conversion."""
852
def open_repository(self):
853
"""See BzrDir.open_repository."""
854
from bzrlib.repository import RepositoryFormat4
855
return RepositoryFormat4().open(self, _found=True)
858
class BzrDir5(BzrDirPreSplitOut):
859
"""A .bzr version 5 control object.
861
This is a deprecated format and may be removed after sept 2006.
864
def open_repository(self):
865
"""See BzrDir.open_repository."""
866
from bzrlib.repository import RepositoryFormat5
867
return RepositoryFormat5().open(self, _found=True)
869
def open_workingtree(self, _unsupported=False):
870
"""See BzrDir.create_workingtree."""
871
from bzrlib.workingtree import WorkingTreeFormat2
872
return WorkingTreeFormat2().open(self, _found=True)
875
class BzrDir6(BzrDirPreSplitOut):
876
"""A .bzr version 6 control object.
878
This is a deprecated format and may be removed after sept 2006.
881
def open_repository(self):
882
"""See BzrDir.open_repository."""
883
from bzrlib.repository import RepositoryFormat6
884
return RepositoryFormat6().open(self, _found=True)
886
def open_workingtree(self, _unsupported=False):
887
"""See BzrDir.create_workingtree."""
888
from bzrlib.workingtree import WorkingTreeFormat2
889
return WorkingTreeFormat2().open(self, _found=True)
892
class BzrDirMeta1(BzrDir):
893
"""A .bzr meta version 1 control object.
895
This is the first control object where the
896
individual aspects are really split out: there are separate repository,
897
workingtree and branch subdirectories and any subset of the three can be
898
present within a BzrDir.
901
def can_convert_format(self):
902
"""See BzrDir.can_convert_format()."""
905
def create_branch(self):
906
"""See BzrDir.create_branch."""
907
from bzrlib.branch import BranchFormat
908
return BranchFormat.get_default_format().initialize(self)
910
def create_repository(self, shared=False):
911
"""See BzrDir.create_repository."""
912
return self._format.repository_format.initialize(self, shared)
914
def create_workingtree(self, revision_id=None):
915
"""See BzrDir.create_workingtree."""
916
from bzrlib.workingtree import WorkingTreeFormat
917
return WorkingTreeFormat.get_default_format().initialize(self, revision_id)
919
def destroy_workingtree(self):
920
"""See BzrDir.destroy_workingtree."""
921
wt = self.open_workingtree()
922
repository = wt.branch.repository
923
empty = repository.revision_tree(_mod_revision.NULL_REVISION)
924
wt.revert([], old_tree=empty)
925
self.destroy_workingtree_metadata()
927
def destroy_workingtree_metadata(self):
928
self.transport.delete_tree('checkout')
930
def _get_mkdir_mode(self):
931
"""Figure out the mode to use when creating a bzrdir subdir."""
932
temp_control = lockable_files.LockableFiles(self.transport, '',
933
lockable_files.TransportLock)
934
return temp_control._dir_mode
936
def get_branch_transport(self, branch_format):
937
"""See BzrDir.get_branch_transport()."""
938
if branch_format is None:
939
return self.transport.clone('branch')
941
branch_format.get_format_string()
942
except NotImplementedError:
943
raise errors.IncompatibleFormat(branch_format, self._format)
945
self.transport.mkdir('branch', mode=self._get_mkdir_mode())
946
except errors.FileExists:
948
return self.transport.clone('branch')
950
def get_repository_transport(self, repository_format):
951
"""See BzrDir.get_repository_transport()."""
952
if repository_format is None:
953
return self.transport.clone('repository')
955
repository_format.get_format_string()
956
except NotImplementedError:
957
raise errors.IncompatibleFormat(repository_format, self._format)
959
self.transport.mkdir('repository', mode=self._get_mkdir_mode())
960
except errors.FileExists:
962
return self.transport.clone('repository')
964
def get_workingtree_transport(self, workingtree_format):
965
"""See BzrDir.get_workingtree_transport()."""
966
if workingtree_format is None:
967
return self.transport.clone('checkout')
969
workingtree_format.get_format_string()
970
except NotImplementedError:
971
raise errors.IncompatibleFormat(workingtree_format, self._format)
973
self.transport.mkdir('checkout', mode=self._get_mkdir_mode())
974
except errors.FileExists:
976
return self.transport.clone('checkout')
978
def needs_format_conversion(self, format=None):
979
"""See BzrDir.needs_format_conversion()."""
981
format = BzrDirFormat.get_default_format()
982
if not isinstance(self._format, format.__class__):
983
# it is not a meta dir format, conversion is needed.
985
# we might want to push this down to the repository?
987
if not isinstance(self.open_repository()._format,
988
format.repository_format.__class__):
989
# the repository needs an upgrade.
991
except errors.NoRepositoryPresent:
993
# currently there are no other possible conversions for meta1 formats.
996
def open_branch(self, unsupported=False):
997
"""See BzrDir.open_branch."""
998
from bzrlib.branch import BranchFormat
999
format = BranchFormat.find_format(self)
1000
self._check_supported(format, unsupported)
1001
return format.open(self, _found=True)
1003
def open_repository(self, unsupported=False):
1004
"""See BzrDir.open_repository."""
1005
from bzrlib.repository import RepositoryFormat
1006
format = RepositoryFormat.find_format(self)
1007
self._check_supported(format, unsupported)
1008
return format.open(self, _found=True)
1010
def open_workingtree(self, unsupported=False):
1011
"""See BzrDir.open_workingtree."""
1012
from bzrlib.workingtree import WorkingTreeFormat
1013
format = WorkingTreeFormat.find_format(self)
1014
self._check_supported(format, unsupported)
1015
return format.open(self, _found=True)
1018
class BzrDirFormat(object):
1019
"""An encapsulation of the initialization and open routines for a format.
1021
Formats provide three things:
1022
* An initialization routine,
1026
Formats are placed in an dict by their format string for reference
1027
during bzrdir opening. These should be subclasses of BzrDirFormat
1030
Once a format is deprecated, just deprecate the initialize and open
1031
methods on the format class. Do not deprecate the object, as the
1032
object will be created every system load.
1035
_default_format = None
1036
"""The default format used for new .bzr dirs."""
1039
"""The known formats."""
1041
_control_formats = []
1042
"""The registered control formats - .bzr, ....
1044
This is a list of BzrDirFormat objects.
1047
_lock_file_name = 'branch-lock'
1049
# _lock_class must be set in subclasses to the lock type, typ.
1050
# TransportLock or LockDir
1053
def find_format(klass, transport):
1054
"""Return the format present at transport."""
1055
for format in klass._control_formats:
1057
return format.probe_transport(transport)
1058
except errors.NotBranchError:
1059
# this format does not find a control dir here.
1061
raise errors.NotBranchError(path=transport.base)
1064
def probe_transport(klass, transport):
1065
"""Return the .bzrdir style transport present at URL."""
1067
format_string = transport.get(".bzr/branch-format").read()
1068
except errors.NoSuchFile:
1069
raise errors.NotBranchError(path=transport.base)
1072
return klass._formats[format_string]
1074
raise errors.UnknownFormatError(format=format_string)
1077
def get_default_format(klass):
1078
"""Return the current default format."""
1079
return klass._default_format
1081
def get_format_string(self):
1082
"""Return the ASCII format string that identifies this format."""
1083
raise NotImplementedError(self.get_format_string)
1085
def get_format_description(self):
1086
"""Return the short description for this format."""
1087
raise NotImplementedError(self.get_format_description)
1089
def get_converter(self, format=None):
1090
"""Return the converter to use to convert bzrdirs needing converts.
1092
This returns a bzrlib.bzrdir.Converter object.
1094
This should return the best upgrader to step this format towards the
1095
current default format. In the case of plugins we can/should provide
1096
some means for them to extend the range of returnable converters.
1098
:param format: Optional format to override the default format of the
1101
raise NotImplementedError(self.get_converter)
1103
def initialize(self, url):
1104
"""Create a bzr control dir at this url and return an opened copy.
1106
Subclasses should typically override initialize_on_transport
1107
instead of this method.
1109
return self.initialize_on_transport(get_transport(url))
1111
def initialize_on_transport(self, transport):
1112
"""Initialize a new bzrdir in the base directory of a Transport."""
1113
# Since we don't have a .bzr directory, inherit the
1114
# mode from the root directory
1115
temp_control = lockable_files.LockableFiles(transport,
1116
'', lockable_files.TransportLock)
1117
temp_control._transport.mkdir('.bzr',
1118
# FIXME: RBC 20060121 don't peek under
1120
mode=temp_control._dir_mode)
1121
file_mode = temp_control._file_mode
1123
mutter('created control directory in ' + transport.base)
1124
control = transport.clone('.bzr')
1125
utf8_files = [('README',
1126
"This is a Bazaar-NG control directory.\n"
1127
"Do not change any files in this directory.\n"),
1128
('branch-format', self.get_format_string()),
1130
# NB: no need to escape relative paths that are url safe.
1131
control_files = lockable_files.LockableFiles(control,
1132
self._lock_file_name, self._lock_class)
1133
control_files.create_lock()
1134
control_files.lock_write()
1136
for file, content in utf8_files:
1137
control_files.put_utf8(file, content)
1139
control_files.unlock()
1140
return self.open(transport, _found=True)
1142
def is_supported(self):
1143
"""Is this format supported?
1145
Supported formats must be initializable and openable.
1146
Unsupported formats may not support initialization or committing or
1147
some other features depending on the reason for not being supported.
1151
def same_model(self, target_format):
1152
return (self.repository_format.rich_root_data ==
1153
target_format.rich_root_data)
1156
def known_formats(klass):
1157
"""Return all the known formats.
1159
Concrete formats should override _known_formats.
1161
# There is double indirection here to make sure that control
1162
# formats used by more than one dir format will only be probed
1163
# once. This can otherwise be quite expensive for remote connections.
1165
for format in klass._control_formats:
1166
result.update(format._known_formats())
1170
def _known_formats(klass):
1171
"""Return the known format instances for this control format."""
1172
return set(klass._formats.values())
1174
def open(self, transport, _found=False):
1175
"""Return an instance of this format for the dir transport points at.
1177
_found is a private parameter, do not use it.
1180
found_format = BzrDirFormat.find_format(transport)
1181
if not isinstance(found_format, self.__class__):
1182
raise AssertionError("%s was asked to open %s, but it seems to need "
1184
% (self, transport, found_format))
1185
return self._open(transport)
1187
def _open(self, transport):
1188
"""Template method helper for opening BzrDirectories.
1190
This performs the actual open and any additional logic or parameter
1193
raise NotImplementedError(self._open)
1196
def register_format(klass, format):
1197
klass._formats[format.get_format_string()] = format
1200
def register_control_format(klass, format):
1201
"""Register a format that does not use '.bzrdir' for its control dir.
1203
TODO: This should be pulled up into a 'ControlDirFormat' base class
1204
which BzrDirFormat can inherit from, and renamed to register_format
1205
there. It has been done without that for now for simplicity of
1208
klass._control_formats.append(format)
1211
def set_default_format(klass, format):
1212
klass._default_format = format
1215
return self.get_format_string()[:-1]
1218
def unregister_format(klass, format):
1219
assert klass._formats[format.get_format_string()] is format
1220
del klass._formats[format.get_format_string()]
1223
def unregister_control_format(klass, format):
1224
klass._control_formats.remove(format)
1227
# register BzrDirFormat as a control format
1228
BzrDirFormat.register_control_format(BzrDirFormat)
1231
class BzrDirFormat4(BzrDirFormat):
1232
"""Bzr dir format 4.
1234
This format is a combined format for working tree, branch and repository.
1236
- Format 1 working trees [always]
1237
- Format 4 branches [always]
1238
- Format 4 repositories [always]
1240
This format is deprecated: it indexes texts using a text it which is
1241
removed in format 5; write support for this format has been removed.
1244
_lock_class = lockable_files.TransportLock
1246
def get_format_string(self):
1247
"""See BzrDirFormat.get_format_string()."""
1248
return "Bazaar-NG branch, format 0.0.4\n"
1250
def get_format_description(self):
1251
"""See BzrDirFormat.get_format_description()."""
1252
return "All-in-one format 4"
1254
def get_converter(self, format=None):
1255
"""See BzrDirFormat.get_converter()."""
1256
# there is one and only one upgrade path here.
1257
return ConvertBzrDir4To5()
1259
def initialize_on_transport(self, transport):
1260
"""Format 4 branches cannot be created."""
1261
raise errors.UninitializableFormat(self)
1263
def is_supported(self):
1264
"""Format 4 is not supported.
1266
It is not supported because the model changed from 4 to 5 and the
1267
conversion logic is expensive - so doing it on the fly was not
1272
def _open(self, transport):
1273
"""See BzrDirFormat._open."""
1274
return BzrDir4(transport, self)
1276
def __return_repository_format(self):
1277
"""Circular import protection."""
1278
from bzrlib.repository import RepositoryFormat4
1279
return RepositoryFormat4()
1280
repository_format = property(__return_repository_format)
1283
class BzrDirFormat5(BzrDirFormat):
1284
"""Bzr control format 5.
1286
This format is a combined format for working tree, branch and repository.
1288
- Format 2 working trees [always]
1289
- Format 4 branches [always]
1290
- Format 5 repositories [always]
1291
Unhashed stores in the repository.
1294
_lock_class = lockable_files.TransportLock
1296
def get_format_string(self):
1297
"""See BzrDirFormat.get_format_string()."""
1298
return "Bazaar-NG branch, format 5\n"
1300
def get_format_description(self):
1301
"""See BzrDirFormat.get_format_description()."""
1302
return "All-in-one format 5"
1304
def get_converter(self, format=None):
1305
"""See BzrDirFormat.get_converter()."""
1306
# there is one and only one upgrade path here.
1307
return ConvertBzrDir5To6()
1309
def _initialize_for_clone(self, url):
1310
return self.initialize_on_transport(get_transport(url), _cloning=True)
1312
def initialize_on_transport(self, transport, _cloning=False):
1313
"""Format 5 dirs always have working tree, branch and repository.
1315
Except when they are being cloned.
1317
from bzrlib.branch import BzrBranchFormat4
1318
from bzrlib.repository import RepositoryFormat5
1319
from bzrlib.workingtree import WorkingTreeFormat2
1320
result = (super(BzrDirFormat5, self).initialize_on_transport(transport))
1321
RepositoryFormat5().initialize(result, _internal=True)
1323
branch = BzrBranchFormat4().initialize(result)
1325
WorkingTreeFormat2().initialize(result)
1326
except errors.NotLocalUrl:
1327
# Even though we can't access the working tree, we need to
1328
# create its control files.
1329
WorkingTreeFormat2().stub_initialize_remote(branch.control_files)
1332
def _open(self, transport):
1333
"""See BzrDirFormat._open."""
1334
return BzrDir5(transport, self)
1336
def __return_repository_format(self):
1337
"""Circular import protection."""
1338
from bzrlib.repository import RepositoryFormat5
1339
return RepositoryFormat5()
1340
repository_format = property(__return_repository_format)
1343
class BzrDirFormat6(BzrDirFormat):
1344
"""Bzr control format 6.
1346
This format is a combined format for working tree, branch and repository.
1348
- Format 2 working trees [always]
1349
- Format 4 branches [always]
1350
- Format 6 repositories [always]
1353
_lock_class = lockable_files.TransportLock
1355
def get_format_string(self):
1356
"""See BzrDirFormat.get_format_string()."""
1357
return "Bazaar-NG branch, format 6\n"
1359
def get_format_description(self):
1360
"""See BzrDirFormat.get_format_description()."""
1361
return "All-in-one format 6"
1363
def get_converter(self, format=None):
1364
"""See BzrDirFormat.get_converter()."""
1365
# there is one and only one upgrade path here.
1366
return ConvertBzrDir6ToMeta()
1368
def _initialize_for_clone(self, url):
1369
return self.initialize_on_transport(get_transport(url), _cloning=True)
1371
def initialize_on_transport(self, transport, _cloning=False):
1372
"""Format 6 dirs always have working tree, branch and repository.
1374
Except when they are being cloned.
1376
from bzrlib.branch import BzrBranchFormat4
1377
from bzrlib.repository import RepositoryFormat6
1378
from bzrlib.workingtree import WorkingTreeFormat2
1379
result = super(BzrDirFormat6, self).initialize_on_transport(transport)
1380
RepositoryFormat6().initialize(result, _internal=True)
1382
branch = BzrBranchFormat4().initialize(result)
1384
WorkingTreeFormat2().initialize(result)
1385
except errors.NotLocalUrl:
1386
# Even though we can't access the working tree, we need to
1387
# create its control files.
1388
WorkingTreeFormat2().stub_initialize_remote(branch.control_files)
1391
def _open(self, transport):
1392
"""See BzrDirFormat._open."""
1393
return BzrDir6(transport, self)
1395
def __return_repository_format(self):
1396
"""Circular import protection."""
1397
from bzrlib.repository import RepositoryFormat6
1398
return RepositoryFormat6()
1399
repository_format = property(__return_repository_format)
1402
class BzrDirMetaFormat1(BzrDirFormat):
1403
"""Bzr meta control format 1
1405
This is the first format with split out working tree, branch and repository
1408
- Format 3 working trees [optional]
1409
- Format 5 branches [optional]
1410
- Format 7 repositories [optional]
1413
_lock_class = lockdir.LockDir
1415
def get_converter(self, format=None):
1416
"""See BzrDirFormat.get_converter()."""
1418
format = BzrDirFormat.get_default_format()
1419
if not isinstance(self, format.__class__):
1420
# converting away from metadir is not implemented
1421
raise NotImplementedError(self.get_converter)
1422
return ConvertMetaToMeta(format)
1424
def get_format_string(self):
1425
"""See BzrDirFormat.get_format_string()."""
1426
return "Bazaar-NG meta directory, format 1\n"
1428
def get_format_description(self):
1429
"""See BzrDirFormat.get_format_description()."""
1430
return "Meta directory format 1"
1432
def _open(self, transport):
1433
"""See BzrDirFormat._open."""
1434
return BzrDirMeta1(transport, self)
1436
def __return_repository_format(self):
1437
"""Circular import protection."""
1438
if getattr(self, '_repository_format', None):
1439
return self._repository_format
1440
from bzrlib.repository import RepositoryFormat
1441
return RepositoryFormat.get_default_format()
1443
def __set_repository_format(self, value):
1444
"""Allow changint the repository format for metadir formats."""
1445
self._repository_format = value
1447
repository_format = property(__return_repository_format, __set_repository_format)
1450
BzrDirFormat.register_format(BzrDirFormat4())
1451
BzrDirFormat.register_format(BzrDirFormat5())
1452
BzrDirFormat.register_format(BzrDirFormat6())
1453
__default_format = BzrDirMetaFormat1()
1454
BzrDirFormat.register_format(__default_format)
1455
BzrDirFormat.set_default_format(__default_format)
1458
class BzrDirTestProviderAdapter(object):
1459
"""A tool to generate a suite testing multiple bzrdir formats at once.
1461
This is done by copying the test once for each transport and injecting
1462
the transport_server, transport_readonly_server, and bzrdir_format
1463
classes into each copy. Each copy is also given a new id() to make it
1467
def __init__(self, transport_server, transport_readonly_server, formats):
1468
self._transport_server = transport_server
1469
self._transport_readonly_server = transport_readonly_server
1470
self._formats = formats
1472
def adapt(self, test):
1473
result = unittest.TestSuite()
1474
for format in self._formats:
1475
new_test = deepcopy(test)
1476
new_test.transport_server = self._transport_server
1477
new_test.transport_readonly_server = self._transport_readonly_server
1478
new_test.bzrdir_format = format
1479
def make_new_test_id():
1480
new_id = "%s(%s)" % (new_test.id(), format.__class__.__name__)
1481
return lambda: new_id
1482
new_test.id = make_new_test_id()
1483
result.addTest(new_test)
1487
class Converter(object):
1488
"""Converts a disk format object from one format to another."""
1490
def convert(self, to_convert, pb):
1491
"""Perform the conversion of to_convert, giving feedback via pb.
1493
:param to_convert: The disk object to convert.
1494
:param pb: a progress bar to use for progress information.
1497
def step(self, message):
1498
"""Update the pb by a step."""
1500
self.pb.update(message, self.count, self.total)
1503
class ConvertBzrDir4To5(Converter):
1504
"""Converts format 4 bzr dirs to format 5."""
1507
super(ConvertBzrDir4To5, self).__init__()
1508
self.converted_revs = set()
1509
self.absent_revisions = set()
1513
def convert(self, to_convert, pb):
1514
"""See Converter.convert()."""
1515
self.bzrdir = to_convert
1517
self.pb.note('starting upgrade from format 4 to 5')
1518
if isinstance(self.bzrdir.transport, LocalTransport):
1519
self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
1520
self._convert_to_weaves()
1521
return BzrDir.open(self.bzrdir.root_transport.base)
1523
def _convert_to_weaves(self):
1524
self.pb.note('note: upgrade may be faster if all store files are ungzipped first')
1527
stat = self.bzrdir.transport.stat('weaves')
1528
if not S_ISDIR(stat.st_mode):
1529
self.bzrdir.transport.delete('weaves')
1530
self.bzrdir.transport.mkdir('weaves')
1531
except errors.NoSuchFile:
1532
self.bzrdir.transport.mkdir('weaves')
1533
# deliberately not a WeaveFile as we want to build it up slowly.
1534
self.inv_weave = Weave('inventory')
1535
# holds in-memory weaves for all files
1536
self.text_weaves = {}
1537
self.bzrdir.transport.delete('branch-format')
1538
self.branch = self.bzrdir.open_branch()
1539
self._convert_working_inv()
1540
rev_history = self.branch.revision_history()
1541
# to_read is a stack holding the revisions we still need to process;
1542
# appending to it adds new highest-priority revisions
1543
self.known_revisions = set(rev_history)
1544
self.to_read = rev_history[-1:]
1546
rev_id = self.to_read.pop()
1547
if (rev_id not in self.revisions
1548
and rev_id not in self.absent_revisions):
1549
self._load_one_rev(rev_id)
1551
to_import = self._make_order()
1552
for i, rev_id in enumerate(to_import):
1553
self.pb.update('converting revision', i, len(to_import))
1554
self._convert_one_rev(rev_id)
1556
self._write_all_weaves()
1557
self._write_all_revs()
1558
self.pb.note('upgraded to weaves:')
1559
self.pb.note(' %6d revisions and inventories', len(self.revisions))
1560
self.pb.note(' %6d revisions not present', len(self.absent_revisions))
1561
self.pb.note(' %6d texts', self.text_count)
1562
self._cleanup_spare_files_after_format4()
1563
self.branch.control_files.put_utf8('branch-format', BzrDirFormat5().get_format_string())
1565
def _cleanup_spare_files_after_format4(self):
1566
# FIXME working tree upgrade foo.
1567
for n in 'merged-patches', 'pending-merged-patches':
1569
## assert os.path.getsize(p) == 0
1570
self.bzrdir.transport.delete(n)
1571
except errors.NoSuchFile:
1573
self.bzrdir.transport.delete_tree('inventory-store')
1574
self.bzrdir.transport.delete_tree('text-store')
1576
def _convert_working_inv(self):
1577
inv = xml4.serializer_v4.read_inventory(
1578
self.branch.control_files.get('inventory'))
1579
new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
1580
# FIXME inventory is a working tree change.
1581
self.branch.control_files.put('inventory', StringIO(new_inv_xml))
1583
def _write_all_weaves(self):
1584
controlweaves = WeaveStore(self.bzrdir.transport, prefixed=False)
1585
weave_transport = self.bzrdir.transport.clone('weaves')
1586
weaves = WeaveStore(weave_transport, prefixed=False)
1587
transaction = WriteTransaction()
1591
for file_id, file_weave in self.text_weaves.items():
1592
self.pb.update('writing weave', i, len(self.text_weaves))
1593
weaves._put_weave(file_id, file_weave, transaction)
1595
self.pb.update('inventory', 0, 1)
1596
controlweaves._put_weave('inventory', self.inv_weave, transaction)
1597
self.pb.update('inventory', 1, 1)
1601
def _write_all_revs(self):
1602
"""Write all revisions out in new form."""
1603
self.bzrdir.transport.delete_tree('revision-store')
1604
self.bzrdir.transport.mkdir('revision-store')
1605
revision_transport = self.bzrdir.transport.clone('revision-store')
1607
_revision_store = TextRevisionStore(TextStore(revision_transport,
1611
transaction = WriteTransaction()
1612
for i, rev_id in enumerate(self.converted_revs):
1613
self.pb.update('write revision', i, len(self.converted_revs))
1614
_revision_store.add_revision(self.revisions[rev_id], transaction)
1618
def _load_one_rev(self, rev_id):
1619
"""Load a revision object into memory.
1621
Any parents not either loaded or abandoned get queued to be
1623
self.pb.update('loading revision',
1624
len(self.revisions),
1625
len(self.known_revisions))
1626
if not self.branch.repository.has_revision(rev_id):
1628
self.pb.note('revision {%s} not present in branch; '
1629
'will be converted as a ghost',
1631
self.absent_revisions.add(rev_id)
1633
rev = self.branch.repository._revision_store.get_revision(rev_id,
1634
self.branch.repository.get_transaction())
1635
for parent_id in rev.parent_ids:
1636
self.known_revisions.add(parent_id)
1637
self.to_read.append(parent_id)
1638
self.revisions[rev_id] = rev
1640
def _load_old_inventory(self, rev_id):
1641
assert rev_id not in self.converted_revs
1642
old_inv_xml = self.branch.repository.inventory_store.get(rev_id).read()
1643
inv = xml4.serializer_v4.read_inventory_from_string(old_inv_xml)
1644
inv.revision_id = rev_id
1645
rev = self.revisions[rev_id]
1646
if rev.inventory_sha1:
1647
assert rev.inventory_sha1 == sha_string(old_inv_xml), \
1648
'inventory sha mismatch for {%s}' % rev_id
1651
def _load_updated_inventory(self, rev_id):
1652
assert rev_id in self.converted_revs
1653
inv_xml = self.inv_weave.get_text(rev_id)
1654
inv = xml5.serializer_v5.read_inventory_from_string(inv_xml)
1657
def _convert_one_rev(self, rev_id):
1658
"""Convert revision and all referenced objects to new format."""
1659
rev = self.revisions[rev_id]
1660
inv = self._load_old_inventory(rev_id)
1661
present_parents = [p for p in rev.parent_ids
1662
if p not in self.absent_revisions]
1663
self._convert_revision_contents(rev, inv, present_parents)
1664
self._store_new_weave(rev, inv, present_parents)
1665
self.converted_revs.add(rev_id)
1667
def _store_new_weave(self, rev, inv, present_parents):
1668
# the XML is now updated with text versions
1670
entries = inv.iter_entries()
1672
for path, ie in entries:
1673
assert getattr(ie, 'revision', None) is not None, \
1674
'no revision on {%s} in {%s}' % \
1675
(file_id, rev.revision_id)
1676
new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
1677
new_inv_sha1 = sha_string(new_inv_xml)
1678
self.inv_weave.add_lines(rev.revision_id,
1680
new_inv_xml.splitlines(True))
1681
rev.inventory_sha1 = new_inv_sha1
1683
def _convert_revision_contents(self, rev, inv, present_parents):
1684
"""Convert all the files within a revision.
1686
Also upgrade the inventory to refer to the text revision ids."""
1687
rev_id = rev.revision_id
1688
mutter('converting texts of revision {%s}',
1690
parent_invs = map(self._load_updated_inventory, present_parents)
1691
entries = inv.iter_entries()
1693
for path, ie in entries:
1694
self._convert_file_version(rev, ie, parent_invs)
1696
def _convert_file_version(self, rev, ie, parent_invs):
1697
"""Convert one version of one file.
1699
The file needs to be added into the weave if it is a merge
1700
of >=2 parents or if it's changed from its parent.
1702
file_id = ie.file_id
1703
rev_id = rev.revision_id
1704
w = self.text_weaves.get(file_id)
1707
self.text_weaves[file_id] = w
1708
text_changed = False
1709
previous_entries = ie.find_previous_heads(parent_invs,
1713
for old_revision in previous_entries:
1714
# if this fails, its a ghost ?
1715
assert old_revision in self.converted_revs, \
1716
"Revision {%s} not in converted_revs" % old_revision
1717
self.snapshot_ie(previous_entries, ie, w, rev_id)
1719
assert getattr(ie, 'revision', None) is not None
1721
def snapshot_ie(self, previous_revisions, ie, w, rev_id):
1722
# TODO: convert this logic, which is ~= snapshot to
1723
# a call to:. This needs the path figured out. rather than a work_tree
1724
# a v4 revision_tree can be given, or something that looks enough like
1725
# one to give the file content to the entry if it needs it.
1726
# and we need something that looks like a weave store for snapshot to
1728
#ie.snapshot(rev, PATH, previous_revisions, REVISION_TREE, InMemoryWeaveStore(self.text_weaves))
1729
if len(previous_revisions) == 1:
1730
previous_ie = previous_revisions.values()[0]
1731
if ie._unchanged(previous_ie):
1732
ie.revision = previous_ie.revision
1735
text = self.branch.repository.text_store.get(ie.text_id)
1736
file_lines = text.readlines()
1737
assert sha_strings(file_lines) == ie.text_sha1
1738
assert sum(map(len, file_lines)) == ie.text_size
1739
w.add_lines(rev_id, previous_revisions, file_lines)
1740
self.text_count += 1
1742
w.add_lines(rev_id, previous_revisions, [])
1743
ie.revision = rev_id
1745
def _make_order(self):
1746
"""Return a suitable order for importing revisions.
1748
The order must be such that an revision is imported after all
1749
its (present) parents.
1751
todo = set(self.revisions.keys())
1752
done = self.absent_revisions.copy()
1755
# scan through looking for a revision whose parents
1757
for rev_id in sorted(list(todo)):
1758
rev = self.revisions[rev_id]
1759
parent_ids = set(rev.parent_ids)
1760
if parent_ids.issubset(done):
1761
# can take this one now
1762
order.append(rev_id)
1768
class ConvertBzrDir5To6(Converter):
1769
"""Converts format 5 bzr dirs to format 6."""
1771
def convert(self, to_convert, pb):
1772
"""See Converter.convert()."""
1773
self.bzrdir = to_convert
1775
self.pb.note('starting upgrade from format 5 to 6')
1776
self._convert_to_prefixed()
1777
return BzrDir.open(self.bzrdir.root_transport.base)
1779
def _convert_to_prefixed(self):
1780
from bzrlib.store import TransportStore
1781
self.bzrdir.transport.delete('branch-format')
1782
for store_name in ["weaves", "revision-store"]:
1783
self.pb.note("adding prefixes to %s" % store_name)
1784
store_transport = self.bzrdir.transport.clone(store_name)
1785
store = TransportStore(store_transport, prefixed=True)
1786
for urlfilename in store_transport.list_dir('.'):
1787
filename = urlutils.unescape(urlfilename)
1788
if (filename.endswith(".weave") or
1789
filename.endswith(".gz") or
1790
filename.endswith(".sig")):
1791
file_id = os.path.splitext(filename)[0]
1794
prefix_dir = store.hash_prefix(file_id)
1795
# FIXME keep track of the dirs made RBC 20060121
1797
store_transport.move(filename, prefix_dir + '/' + filename)
1798
except errors.NoSuchFile: # catches missing dirs strangely enough
1799
store_transport.mkdir(prefix_dir)
1800
store_transport.move(filename, prefix_dir + '/' + filename)
1801
self.bzrdir._control_files.put_utf8('branch-format', BzrDirFormat6().get_format_string())
1804
class ConvertBzrDir6ToMeta(Converter):
1805
"""Converts format 6 bzr dirs to metadirs."""
1807
def convert(self, to_convert, pb):
1808
"""See Converter.convert()."""
1809
from bzrlib.branch import BzrBranchFormat5
1810
self.bzrdir = to_convert
1813
self.total = 20 # the steps we know about
1814
self.garbage_inventories = []
1816
self.pb.note('starting upgrade from format 6 to metadir')
1817
self.bzrdir._control_files.put_utf8('branch-format', "Converting to format 6")
1818
# its faster to move specific files around than to open and use the apis...
1819
# first off, nuke ancestry.weave, it was never used.
1821
self.step('Removing ancestry.weave')
1822
self.bzrdir.transport.delete('ancestry.weave')
1823
except errors.NoSuchFile:
1825
# find out whats there
1826
self.step('Finding branch files')
1827
last_revision = self.bzrdir.open_branch().last_revision()
1828
bzrcontents = self.bzrdir.transport.list_dir('.')
1829
for name in bzrcontents:
1830
if name.startswith('basis-inventory.'):
1831
self.garbage_inventories.append(name)
1832
# create new directories for repository, working tree and branch
1833
self.dir_mode = self.bzrdir._control_files._dir_mode
1834
self.file_mode = self.bzrdir._control_files._file_mode
1835
repository_names = [('inventory.weave', True),
1836
('revision-store', True),
1838
self.step('Upgrading repository ')
1839
self.bzrdir.transport.mkdir('repository', mode=self.dir_mode)
1840
self.make_lock('repository')
1841
# we hard code the formats here because we are converting into
1842
# the meta format. The meta format upgrader can take this to a
1843
# future format within each component.
1844
self.put_format('repository', _mod_repository.RepositoryFormat7())
1845
for entry in repository_names:
1846
self.move_entry('repository', entry)
1848
self.step('Upgrading branch ')
1849
self.bzrdir.transport.mkdir('branch', mode=self.dir_mode)
1850
self.make_lock('branch')
1851
self.put_format('branch', BzrBranchFormat5())
1852
branch_files = [('revision-history', True),
1853
('branch-name', True),
1855
for entry in branch_files:
1856
self.move_entry('branch', entry)
1858
checkout_files = [('pending-merges', True),
1859
('inventory', True),
1860
('stat-cache', False)]
1861
# If a mandatory checkout file is not present, the branch does not have
1862
# a functional checkout. Do not create a checkout in the converted
1864
for name, mandatory in checkout_files:
1865
if mandatory and name not in bzrcontents:
1866
has_checkout = False
1870
if not has_checkout:
1871
self.pb.note('No working tree.')
1872
# If some checkout files are there, we may as well get rid of them.
1873
for name, mandatory in checkout_files:
1874
if name in bzrcontents:
1875
self.bzrdir.transport.delete(name)
1877
from bzrlib.workingtree import WorkingTreeFormat3
1878
self.step('Upgrading working tree')
1879
self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
1880
self.make_lock('checkout')
1882
'checkout', WorkingTreeFormat3())
1883
self.bzrdir.transport.delete_multi(
1884
self.garbage_inventories, self.pb)
1885
for entry in checkout_files:
1886
self.move_entry('checkout', entry)
1887
if last_revision is not None:
1888
self.bzrdir._control_files.put_utf8(
1889
'checkout/last-revision', last_revision)
1890
self.bzrdir._control_files.put_utf8(
1891
'branch-format', BzrDirMetaFormat1().get_format_string())
1892
return BzrDir.open(self.bzrdir.root_transport.base)
1894
def make_lock(self, name):
1895
"""Make a lock for the new control dir name."""
1896
self.step('Make %s lock' % name)
1897
ld = lockdir.LockDir(self.bzrdir.transport,
1899
file_modebits=self.file_mode,
1900
dir_modebits=self.dir_mode)
1903
def move_entry(self, new_dir, entry):
1904
"""Move then entry name into new_dir."""
1906
mandatory = entry[1]
1907
self.step('Moving %s' % name)
1909
self.bzrdir.transport.move(name, '%s/%s' % (new_dir, name))
1910
except errors.NoSuchFile:
1914
def put_format(self, dirname, format):
1915
self.bzrdir._control_files.put_utf8('%s/format' % dirname, format.get_format_string())
1918
class ConvertMetaToMeta(Converter):
1919
"""Converts the components of metadirs."""
1921
def __init__(self, target_format):
1922
"""Create a metadir to metadir converter.
1924
:param target_format: The final metadir format that is desired.
1926
self.target_format = target_format
1928
def convert(self, to_convert, pb):
1929
"""See Converter.convert()."""
1930
self.bzrdir = to_convert
1934
self.step('checking repository format')
1936
repo = self.bzrdir.open_repository()
1937
except errors.NoRepositoryPresent:
1940
if not isinstance(repo._format, self.target_format.repository_format.__class__):
1941
from bzrlib.repository import CopyConverter
1942
self.pb.note('starting repository conversion')
1943
converter = CopyConverter(self.target_format.repository_format)
1944
converter.convert(repo, pb)
1948
class BzrDirFormatInfo(object):
1950
def __init__(self, native, deprecated):
1951
self.deprecated = deprecated
1952
self.native = native
1955
class BzrDirFormatRegistry(registry.Registry):
1956
"""Registry of user-selectable BzrDir subformats.
1958
Differs from BzrDirFormat._control_formats in that it provides sub-formats,
1959
e.g. BzrDirMeta1 with weave repository. Also, it's more user-oriented.
1962
def register_metadir(self, key, repo, help, native=True, deprecated=False):
1963
"""Register a metadir subformat.
1965
repo is the repository format name as a string.
1967
# This should be expanded to support setting WorkingTree and Branch
1968
# formats, once BzrDirMetaFormat1 supports that.
1970
import bzrlib.repository
1971
repo_format = getattr(bzrlib.repository, repo)
1972
bd = BzrDirMetaFormat1()
1973
bd.repository_format = repo_format()
1975
self.register(key, helper, help, native, deprecated)
1977
def register(self, key, factory, help, native=True, deprecated=False):
1978
"""Register a BzrDirFormat factory.
1980
The factory must be a callable that takes one parameter: the key.
1981
It must produce an instance of the BzrDirFormat when called.
1983
This function mainly exists to prevent the info object from being
1986
registry.Registry.register(self, key, factory, help,
1987
BzrDirFormatInfo(native, deprecated))
1989
def register_lazy(self, key, module_name, member_name, help, native=True,
1991
registry.Registry.register_lazy(self, key, module_name, member_name,
1992
help, BzrDirFormatInfo(native, deprecated))
1994
def set_default(self, key):
1995
"""Set the 'default' key to be a clone of the supplied key.
1997
This method must be called once and only once.
1999
registry.Registry.register(self, 'default', self.get(key),
2000
self.get_help(key), info=self.get_info(key))
2002
def make_bzrdir(self, key):
2003
return self.get(key)()
2005
def help_topic(self, topic):
2006
output = textwrap.dedent("""\
2007
Bazaar directory formats
2008
------------------------
2010
These formats can be used for creating branches, working trees, and
2014
default_help = self.get_help('default')
2016
for key in self.keys():
2017
if key == 'default':
2019
help = self.get_help(key)
2020
if help == default_help:
2021
default_realkey = key
2023
help_pairs.append((key, help))
2025
def wrapped(key, help, info):
2027
help = '(native) ' + help
2028
return ' %s:\n%s\n\n' % (key,
2029
textwrap.fill(help, initial_indent=' ',
2030
subsequent_indent=' '))
2031
output += wrapped('%s/default' % default_realkey, default_help,
2032
self.get_info('default'))
2033
deprecated_pairs = []
2034
for key, help in help_pairs:
2035
info = self.get_info(key)
2037
deprecated_pairs.append((key, help))
2039
output += wrapped(key, help, info)
2040
if len(deprecated_pairs) > 0:
2041
output += "Deprecated formats\n------------------\n\n"
2042
for key, help in deprecated_pairs:
2043
info = self.get_info(key)
2044
output += wrapped(key, help, info)
2049
format_registry = BzrDirFormatRegistry()
2050
format_registry.register('weave', BzrDirFormat6,
2051
'Pre-0.8 format. Slower than knit and does not'
2052
' support checkouts or shared repositories.', deprecated=True)
2053
format_registry.register_metadir('knit', 'RepositoryFormatKnit1',
2054
'Format using knits. Recommended.')
2055
format_registry.set_default('knit')
2056
format_registry.register_metadir('metaweave', 'RepositoryFormat7',
2057
'Transitional format in 0.8. Slower than knit.',
2059
format_registry.register_metadir('experimental-knit2', 'RepositoryFormatKnit2',
2060
'Experimental successor to knit. Use at your own risk.')