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
from copy import deepcopy
25
from cStringIO import StringIO
26
from unittest import TestSuite
29
import bzrlib.errors as errors
30
from bzrlib.lockable_files import LockableFiles, TransportLock
31
from bzrlib.lockdir import LockDir
32
from bzrlib.osutils import safe_unicode
33
from bzrlib.osutils import (
40
from bzrlib.store.revision.text import TextRevisionStore
41
from bzrlib.store.text import TextStore
42
from bzrlib.store.versioned import WeaveStore
43
from bzrlib.symbol_versioning import *
44
from bzrlib.trace import mutter
45
from bzrlib.transactions import WriteTransaction
46
from bzrlib.transport import get_transport, urlunescape
47
from bzrlib.transport.local import LocalTransport
48
from bzrlib.weave import Weave
49
from bzrlib.xml4 import serializer_v4
54
"""A .bzr control diretory.
56
BzrDir instances let you create or open any of the things that can be
57
found within .bzr - checkouts, branches and repositories.
60
the transport which this bzr dir is rooted at (i.e. file:///.../.bzr/)
62
a transport connected to the directory this bzr was opened from.
66
"""Invoke break_lock on the first object in the bzrdir.
68
If there is a tree, the tree is opened and break_lock() called.
69
Otherwise, branch is tried, and finally repository.
72
thing_to_unlock = self.open_workingtree()
73
except (errors.NotLocalUrl, errors.NoWorkingTree):
75
thing_to_unlock = self.open_branch()
76
except errors.NotBranchError:
78
thing_to_unlock = self.open_repository()
79
except errors.NoRepositoryPresent:
81
thing_to_unlock.break_lock()
83
def can_convert_format(self):
84
"""Return true if this bzrdir is one whose format we can convert from."""
88
def _check_supported(format, allow_unsupported):
89
"""Check whether format is a supported format.
91
If allow_unsupported is True, this is a no-op.
93
if not allow_unsupported and not format.is_supported():
94
# see open_downlevel to open legacy branches.
95
raise errors.UnsupportedFormatError(
96
'sorry, format %s not supported' % format,
97
['use a different bzr version',
98
'or remove the .bzr directory'
99
' and "bzr init" again'])
101
def clone(self, url, revision_id=None, basis=None, force_new_repo=False):
102
"""Clone this bzrdir and its contents to url verbatim.
104
If urls last component does not exist, it will be created.
106
if revision_id is not None, then the clone operation may tune
107
itself to download less data.
108
:param force_new_repo: Do not use a shared repository for the target
109
even if one is available.
112
basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
113
result = self._format.initialize(url)
115
local_repo = self.find_repository()
116
except errors.NoRepositoryPresent:
119
# may need to copy content in
121
result_repo = local_repo.clone(
123
revision_id=revision_id,
125
result_repo.set_make_working_trees(local_repo.make_working_trees())
128
result_repo = result.find_repository()
129
# fetch content this dir needs.
131
# XXX FIXME RBC 20060214 need tests for this when the basis
133
result_repo.fetch(basis_repo, revision_id=revision_id)
134
result_repo.fetch(local_repo, revision_id=revision_id)
135
except errors.NoRepositoryPresent:
136
# needed to make one anyway.
137
result_repo = local_repo.clone(
139
revision_id=revision_id,
141
result_repo.set_make_working_trees(local_repo.make_working_trees())
142
# 1 if there is a branch present
143
# make sure its content is available in the target repository
146
self.open_branch().clone(result, revision_id=revision_id)
147
except errors.NotBranchError:
150
self.open_workingtree().clone(result, basis=basis_tree)
151
except (errors.NoWorkingTree, errors.NotLocalUrl):
155
def _get_basis_components(self, basis):
156
"""Retrieve the basis components that are available at basis."""
158
return None, None, None
160
basis_tree = basis.open_workingtree()
161
basis_branch = basis_tree.branch
162
basis_repo = basis_branch.repository
163
except (errors.NoWorkingTree, errors.NotLocalUrl):
166
basis_branch = basis.open_branch()
167
basis_repo = basis_branch.repository
168
except errors.NotBranchError:
171
basis_repo = basis.open_repository()
172
except errors.NoRepositoryPresent:
174
return basis_repo, basis_branch, basis_tree
176
def _make_tail(self, url):
177
segments = url.split('/')
178
if segments and segments[-1] not in ('', '.'):
179
parent = '/'.join(segments[:-1])
180
t = bzrlib.transport.get_transport(parent)
182
t.mkdir(segments[-1])
183
except errors.FileExists:
187
def create(cls, base):
188
"""Create a new BzrDir at the url 'base'.
190
This will call the current default formats initialize with base
191
as the only parameter.
193
If you need a specific format, consider creating an instance
194
of that and calling initialize().
196
if cls is not BzrDir:
197
raise AssertionError("BzrDir.create always creates the default format, "
198
"not one of %r" % cls)
199
segments = base.split('/')
200
if segments and segments[-1] not in ('', '.'):
201
parent = '/'.join(segments[:-1])
202
t = bzrlib.transport.get_transport(parent)
204
t.mkdir(segments[-1])
205
except errors.FileExists:
207
return BzrDirFormat.get_default_format().initialize(safe_unicode(base))
209
def create_branch(self):
210
"""Create a branch in this BzrDir.
212
The bzrdirs format will control what branch format is created.
213
For more control see BranchFormatXX.create(a_bzrdir).
215
raise NotImplementedError(self.create_branch)
218
def create_branch_and_repo(base, force_new_repo=False):
219
"""Create a new BzrDir, Branch and Repository at the url 'base'.
221
This will use the current default BzrDirFormat, and use whatever
222
repository format that that uses via bzrdir.create_branch and
223
create_repository. If a shared repository is available that is used
226
The created Branch object is returned.
228
:param base: The URL to create the branch at.
229
:param force_new_repo: If True a new repository is always created.
231
bzrdir = BzrDir.create(base)
232
bzrdir._find_or_create_repository(force_new_repo)
233
return bzrdir.create_branch()
235
def _find_or_create_repository(self, force_new_repo):
236
"""Create a new repository if needed, returning the repository."""
238
return self.create_repository()
240
return self.find_repository()
241
except errors.NoRepositoryPresent:
242
return self.create_repository()
245
def create_branch_convenience(base, force_new_repo=False,
246
force_new_tree=None, format=None):
247
"""Create a new BzrDir, Branch and Repository at the url 'base'.
249
This is a convenience function - it will use an existing repository
250
if possible, can be told explicitly whether to create a working tree or
253
This will use the current default BzrDirFormat, and use whatever
254
repository format that that uses via bzrdir.create_branch and
255
create_repository. If a shared repository is available that is used
256
preferentially. Whatever repository is used, its tree creation policy
259
The created Branch object is returned.
260
If a working tree cannot be made due to base not being a file:// url,
261
no error is raised unless force_new_tree is True, in which case no
262
data is created on disk and NotLocalUrl is raised.
264
:param base: The URL to create the branch at.
265
:param force_new_repo: If True a new repository is always created.
266
:param force_new_tree: If True or False force creation of a tree or
267
prevent such creation respectively.
268
:param format: Override for the for the bzrdir format to create
271
# check for non local urls
272
t = get_transport(safe_unicode(base))
273
if not isinstance(t, LocalTransport):
274
raise errors.NotLocalUrl(base)
276
bzrdir = BzrDir.create(base)
278
bzrdir = format.initialize(base)
279
repo = bzrdir._find_or_create_repository(force_new_repo)
280
result = bzrdir.create_branch()
281
if force_new_tree or (repo.make_working_trees() and
282
force_new_tree is None):
284
bzrdir.create_workingtree()
285
except errors.NotLocalUrl:
290
def create_repository(base, shared=False):
291
"""Create a new BzrDir and Repository at the url 'base'.
293
This will use the current default BzrDirFormat, and use whatever
294
repository format that that uses for bzrdirformat.create_repository.
296
;param shared: Create a shared repository rather than a standalone
298
The Repository object is returned.
300
This must be overridden as an instance method in child classes, where
301
it should take no parameters and construct whatever repository format
302
that child class desires.
304
bzrdir = BzrDir.create(base)
305
return bzrdir.create_repository()
308
def create_standalone_workingtree(base):
309
"""Create a new BzrDir, WorkingTree, Branch and Repository at 'base'.
311
'base' must be a local path or a file:// url.
313
This will use the current default BzrDirFormat, and use whatever
314
repository format that that uses for bzrdirformat.create_workingtree,
315
create_branch and create_repository.
317
The WorkingTree object is returned.
319
t = get_transport(safe_unicode(base))
320
if not isinstance(t, LocalTransport):
321
raise errors.NotLocalUrl(base)
322
bzrdir = BzrDir.create_branch_and_repo(safe_unicode(base),
323
force_new_repo=True).bzrdir
324
return bzrdir.create_workingtree()
326
def create_workingtree(self, revision_id=None):
327
"""Create a working tree at this BzrDir.
329
revision_id: create it as of this revision id.
331
raise NotImplementedError(self.create_workingtree)
333
def find_repository(self):
334
"""Find the repository that should be used for a_bzrdir.
336
This does not require a branch as we use it to find the repo for
337
new branches as well as to hook existing branches up to their
341
return self.open_repository()
342
except errors.NoRepositoryPresent:
344
next_transport = self.root_transport.clone('..')
347
found_bzrdir = BzrDir.open_containing_from_transport(
349
except errors.NotBranchError:
350
raise errors.NoRepositoryPresent(self)
352
repository = found_bzrdir.open_repository()
353
except errors.NoRepositoryPresent:
354
next_transport = found_bzrdir.root_transport.clone('..')
356
if ((found_bzrdir.root_transport.base ==
357
self.root_transport.base) or repository.is_shared()):
360
raise errors.NoRepositoryPresent(self)
361
raise errors.NoRepositoryPresent(self)
363
def get_branch_transport(self, branch_format):
364
"""Get the transport for use by branch format in this BzrDir.
366
Note that bzr dirs that do not support format strings will raise
367
IncompatibleFormat if the branch format they are given has
368
a format string, and vice verca.
370
If branch_format is None, the transport is returned with no
371
checking. if it is not None, then the returned transport is
372
guaranteed to point to an existing directory ready for use.
374
raise NotImplementedError(self.get_branch_transport)
376
def get_repository_transport(self, repository_format):
377
"""Get the transport for use by repository format in this BzrDir.
379
Note that bzr dirs that do not support format strings will raise
380
IncompatibleFormat if the repository format they are given has
381
a format string, and vice verca.
383
If repository_format is None, the transport is returned with no
384
checking. if it is not None, then the returned transport is
385
guaranteed to point to an existing directory ready for use.
387
raise NotImplementedError(self.get_repository_transport)
389
def get_workingtree_transport(self, tree_format):
390
"""Get the transport for use by workingtree format in this BzrDir.
392
Note that bzr dirs that do not support format strings will raise
393
IncompatibleFormat if the workingtree format they are given has
394
a format string, and vice verca.
396
If workingtree_format is None, the transport is returned with no
397
checking. if it is not None, then the returned transport is
398
guaranteed to point to an existing directory ready for use.
400
raise NotImplementedError(self.get_workingtree_transport)
402
def __init__(self, _transport, _format):
403
"""Initialize a Bzr control dir object.
405
Only really common logic should reside here, concrete classes should be
406
made with varying behaviours.
408
:param _format: the format that is creating this BzrDir instance.
409
:param _transport: the transport this dir is based at.
411
self._format = _format
412
self.transport = _transport.clone('.bzr')
413
self.root_transport = _transport
415
def is_control_filename(self, filename):
416
"""True if filename is the name of a path which is reserved for bzrdir's.
418
:param filename: A filename within the root transport of this bzrdir.
420
This is true IF and ONLY IF the filename is part of the namespace reserved
421
for bzr control dirs. Currently this is the '.bzr' directory in the root
422
of the root_transport. it is expected that plugins will need to extend
423
this in the future - for instance to make bzr talk with svn working
426
# this might be better on the BzrDirFormat class because it refers to
427
# all the possible bzrdir disk formats.
428
# This method is tested via the workingtree is_control_filename tests-
429
# it was extractd from WorkingTree.is_control_filename. If the methods
430
# contract is extended beyond the current trivial implementation please
431
# add new tests for it to the appropriate place.
432
return filename == '.bzr' or filename.startswith('.bzr/')
434
def needs_format_conversion(self, format=None):
435
"""Return true if this bzrdir needs convert_format run on it.
437
For instance, if the repository format is out of date but the
438
branch and working tree are not, this should return True.
440
:param format: Optional parameter indicating a specific desired
441
format we plan to arrive at.
443
raise NotImplementedError(self.needs_format_conversion)
446
def open_unsupported(base):
447
"""Open a branch which is not supported."""
448
return BzrDir.open(base, _unsupported=True)
451
def open(base, _unsupported=False):
452
"""Open an existing bzrdir, rooted at 'base' (url)
454
_unsupported is a private parameter to the BzrDir class.
456
t = get_transport(base)
457
mutter("trying to open %r with transport %r", base, t)
458
format = BzrDirFormat.find_format(t)
459
BzrDir._check_supported(format, _unsupported)
460
return format.open(t, _found=True)
462
def open_branch(self, unsupported=False):
463
"""Open the branch object at this BzrDir if one is present.
465
If unsupported is True, then no longer supported branch formats can
468
TODO: static convenience version of this?
470
raise NotImplementedError(self.open_branch)
473
def open_containing(url):
474
"""Open an existing branch which contains url.
476
:param url: url to search from.
477
See open_containing_from_transport for more detail.
479
return BzrDir.open_containing_from_transport(get_transport(url))
482
def open_containing_from_transport(a_transport):
483
"""Open an existing branch which contains a_transport.base
485
This probes for a branch at a_transport, and searches upwards from there.
487
Basically we keep looking up until we find the control directory or
488
run into the root. If there isn't one, raises NotBranchError.
489
If there is one and it is either an unrecognised format or an unsupported
490
format, UnknownFormatError or UnsupportedFormatError are raised.
491
If there is one, it is returned, along with the unused portion of url.
493
# this gets the normalised url back. I.e. '.' -> the full path.
494
url = a_transport.base
497
format = BzrDirFormat.find_format(a_transport)
498
BzrDir._check_supported(format, False)
499
return format.open(a_transport), a_transport.relpath(url)
500
except errors.NotBranchError, e:
501
mutter('not a branch in: %r %s', a_transport.base, e)
502
new_t = a_transport.clone('..')
503
if new_t.base == a_transport.base:
504
# reached the root, whatever that may be
505
raise errors.NotBranchError(path=url)
508
def open_repository(self, _unsupported=False):
509
"""Open the repository object at this BzrDir if one is present.
511
This will not follow the Branch object pointer - its strictly a direct
512
open facility. Most client code should use open_branch().repository to
515
_unsupported is a private parameter, not part of the api.
516
TODO: static convenience version of this?
518
raise NotImplementedError(self.open_repository)
520
def open_workingtree(self, _unsupported=False):
521
"""Open the workingtree object at this BzrDir if one is present.
523
TODO: static convenience version of this?
525
raise NotImplementedError(self.open_workingtree)
527
def has_branch(self):
528
"""Tell if this bzrdir contains a branch.
530
Note: if you're going to open the branch, you should just go ahead
531
and try, and not ask permission first. (This method just opens the
532
branch and discards it, and that's somewhat expensive.)
537
except errors.NotBranchError:
540
def has_workingtree(self):
541
"""Tell if this bzrdir contains a working tree.
543
This will still raise an exception if the bzrdir has a workingtree that
544
is remote & inaccessible.
546
Note: if you're going to open the working tree, you should just go ahead
547
and try, and not ask permission first. (This method just opens the
548
workingtree and discards it, and that's somewhat expensive.)
551
self.open_workingtree()
553
except errors.NoWorkingTree:
556
def sprout(self, url, revision_id=None, basis=None, force_new_repo=False):
557
"""Create a copy of this bzrdir prepared for use as a new line of
560
If urls last component does not exist, it will be created.
562
Attributes related to the identity of the source branch like
563
branch nickname will be cleaned, a working tree is created
564
whether one existed before or not; and a local branch is always
567
if revision_id is not None, then the clone operation may tune
568
itself to download less data.
571
result = self._format.initialize(url)
572
basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
574
source_branch = self.open_branch()
575
source_repository = source_branch.repository
576
except errors.NotBranchError:
579
source_repository = self.open_repository()
580
except errors.NoRepositoryPresent:
581
# copy the entire basis one if there is one
582
# but there is no repository.
583
source_repository = basis_repo
588
result_repo = result.find_repository()
589
except errors.NoRepositoryPresent:
591
if source_repository is None and result_repo is not None:
593
elif source_repository is None and result_repo is None:
594
# no repo available, make a new one
595
result.create_repository()
596
elif source_repository is not None and result_repo is None:
597
# have source, and want to make a new target repo
598
# we dont clone the repo because that preserves attributes
599
# like is_shared(), and we have not yet implemented a
600
# repository sprout().
601
result_repo = result.create_repository()
602
if result_repo is not None:
603
# fetch needed content into target.
605
# XXX FIXME RBC 20060214 need tests for this when the basis
607
result_repo.fetch(basis_repo, revision_id=revision_id)
608
result_repo.fetch(source_repository, revision_id=revision_id)
609
if source_branch is not None:
610
source_branch.sprout(result, revision_id=revision_id)
612
result.create_branch()
613
if result_repo is None or result_repo.make_working_trees():
614
result.create_workingtree()
618
class BzrDirPreSplitOut(BzrDir):
619
"""A common class for the all-in-one formats."""
621
def __init__(self, _transport, _format):
622
"""See BzrDir.__init__."""
623
super(BzrDirPreSplitOut, self).__init__(_transport, _format)
624
assert self._format._lock_class == TransportLock
625
assert self._format._lock_file_name == 'branch-lock'
626
self._control_files = LockableFiles(self.get_branch_transport(None),
627
self._format._lock_file_name,
628
self._format._lock_class)
630
def break_lock(self):
631
"""Pre-splitout bzrdirs do not suffer from stale locks."""
632
raise NotImplementedError(self.break_lock)
634
def clone(self, url, revision_id=None, basis=None, force_new_repo=False):
635
"""See BzrDir.clone()."""
636
from bzrlib.workingtree import WorkingTreeFormat2
638
result = self._format._initialize_for_clone(url)
639
basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
640
self.open_repository().clone(result, revision_id=revision_id, basis=basis_repo)
641
from_branch = self.open_branch()
642
from_branch.clone(result, revision_id=revision_id)
644
self.open_workingtree().clone(result, basis=basis_tree)
645
except errors.NotLocalUrl:
646
# make a new one, this format always has to have one.
648
WorkingTreeFormat2().initialize(result)
649
except errors.NotLocalUrl:
650
# but we cannot do it for remote trees.
651
to_branch = result.open_branch()
652
WorkingTreeFormat2().stub_initialize_remote(to_branch.control_files)
655
def create_branch(self):
656
"""See BzrDir.create_branch."""
657
return self.open_branch()
659
def create_repository(self, shared=False):
660
"""See BzrDir.create_repository."""
662
raise errors.IncompatibleFormat('shared repository', self._format)
663
return self.open_repository()
665
def create_workingtree(self, revision_id=None):
666
"""See BzrDir.create_workingtree."""
667
# this looks buggy but is not -really-
668
# clone and sprout will have set the revision_id
669
# and that will have set it for us, its only
670
# specific uses of create_workingtree in isolation
671
# that can do wonky stuff here, and that only
672
# happens for creating checkouts, which cannot be
673
# done on this format anyway. So - acceptable wart.
674
result = self.open_workingtree()
675
if revision_id is not None:
676
result.set_last_revision(revision_id)
679
def get_branch_transport(self, branch_format):
680
"""See BzrDir.get_branch_transport()."""
681
if branch_format is None:
682
return self.transport
684
branch_format.get_format_string()
685
except NotImplementedError:
686
return self.transport
687
raise errors.IncompatibleFormat(branch_format, self._format)
689
def get_repository_transport(self, repository_format):
690
"""See BzrDir.get_repository_transport()."""
691
if repository_format is None:
692
return self.transport
694
repository_format.get_format_string()
695
except NotImplementedError:
696
return self.transport
697
raise errors.IncompatibleFormat(repository_format, self._format)
699
def get_workingtree_transport(self, workingtree_format):
700
"""See BzrDir.get_workingtree_transport()."""
701
if workingtree_format is None:
702
return self.transport
704
workingtree_format.get_format_string()
705
except NotImplementedError:
706
return self.transport
707
raise errors.IncompatibleFormat(workingtree_format, self._format)
709
def needs_format_conversion(self, format=None):
710
"""See BzrDir.needs_format_conversion()."""
711
# if the format is not the same as the system default,
712
# an upgrade is needed.
714
format = BzrDirFormat.get_default_format()
715
return not isinstance(self._format, format.__class__)
717
def open_branch(self, unsupported=False):
718
"""See BzrDir.open_branch."""
719
from bzrlib.branch import BzrBranchFormat4
720
format = BzrBranchFormat4()
721
self._check_supported(format, unsupported)
722
return format.open(self, _found=True)
724
def sprout(self, url, revision_id=None, basis=None):
725
"""See BzrDir.sprout()."""
726
from bzrlib.workingtree import WorkingTreeFormat2
728
result = self._format._initialize_for_clone(url)
729
basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
731
self.open_repository().clone(result, revision_id=revision_id, basis=basis_repo)
732
except errors.NoRepositoryPresent:
735
self.open_branch().sprout(result, revision_id=revision_id)
736
except errors.NotBranchError:
738
# we always want a working tree
739
WorkingTreeFormat2().initialize(result)
743
class BzrDir4(BzrDirPreSplitOut):
744
"""A .bzr version 4 control object.
746
This is a deprecated format and may be removed after sept 2006.
749
def create_repository(self, shared=False):
750
"""See BzrDir.create_repository."""
751
return self._format.repository_format.initialize(self, shared)
753
def needs_format_conversion(self, format=None):
754
"""Format 4 dirs are always in need of conversion."""
757
def open_repository(self):
758
"""See BzrDir.open_repository."""
759
from bzrlib.repository import RepositoryFormat4
760
return RepositoryFormat4().open(self, _found=True)
763
class BzrDir5(BzrDirPreSplitOut):
764
"""A .bzr version 5 control object.
766
This is a deprecated format and may be removed after sept 2006.
769
def open_repository(self):
770
"""See BzrDir.open_repository."""
771
from bzrlib.repository import RepositoryFormat5
772
return RepositoryFormat5().open(self, _found=True)
774
def open_workingtree(self, _unsupported=False):
775
"""See BzrDir.create_workingtree."""
776
from bzrlib.workingtree import WorkingTreeFormat2
777
return WorkingTreeFormat2().open(self, _found=True)
780
class BzrDir6(BzrDirPreSplitOut):
781
"""A .bzr version 6 control object.
783
This is a deprecated format and may be removed after sept 2006.
786
def open_repository(self):
787
"""See BzrDir.open_repository."""
788
from bzrlib.repository import RepositoryFormat6
789
return RepositoryFormat6().open(self, _found=True)
791
def open_workingtree(self, _unsupported=False):
792
"""See BzrDir.create_workingtree."""
793
from bzrlib.workingtree import WorkingTreeFormat2
794
return WorkingTreeFormat2().open(self, _found=True)
797
class BzrDirMeta1(BzrDir):
798
"""A .bzr meta version 1 control object.
800
This is the first control object where the
801
individual aspects are really split out: there are separate repository,
802
workingtree and branch subdirectories and any subset of the three can be
803
present within a BzrDir.
806
def can_convert_format(self):
807
"""See BzrDir.can_convert_format()."""
810
def create_branch(self):
811
"""See BzrDir.create_branch."""
812
from bzrlib.branch import BranchFormat
813
return BranchFormat.get_default_format().initialize(self)
815
def create_repository(self, shared=False):
816
"""See BzrDir.create_repository."""
817
return self._format.repository_format.initialize(self, shared)
819
def create_workingtree(self, revision_id=None):
820
"""See BzrDir.create_workingtree."""
821
from bzrlib.workingtree import WorkingTreeFormat
822
return WorkingTreeFormat.get_default_format().initialize(self, revision_id)
824
def _get_mkdir_mode(self):
825
"""Figure out the mode to use when creating a bzrdir subdir."""
826
temp_control = LockableFiles(self.transport, '', TransportLock)
827
return temp_control._dir_mode
829
def get_branch_transport(self, branch_format):
830
"""See BzrDir.get_branch_transport()."""
831
if branch_format is None:
832
return self.transport.clone('branch')
834
branch_format.get_format_string()
835
except NotImplementedError:
836
raise errors.IncompatibleFormat(branch_format, self._format)
838
self.transport.mkdir('branch', mode=self._get_mkdir_mode())
839
except errors.FileExists:
841
return self.transport.clone('branch')
843
def get_repository_transport(self, repository_format):
844
"""See BzrDir.get_repository_transport()."""
845
if repository_format is None:
846
return self.transport.clone('repository')
848
repository_format.get_format_string()
849
except NotImplementedError:
850
raise errors.IncompatibleFormat(repository_format, self._format)
852
self.transport.mkdir('repository', mode=self._get_mkdir_mode())
853
except errors.FileExists:
855
return self.transport.clone('repository')
857
def get_workingtree_transport(self, workingtree_format):
858
"""See BzrDir.get_workingtree_transport()."""
859
if workingtree_format is None:
860
return self.transport.clone('checkout')
862
workingtree_format.get_format_string()
863
except NotImplementedError:
864
raise errors.IncompatibleFormat(workingtree_format, self._format)
866
self.transport.mkdir('checkout', mode=self._get_mkdir_mode())
867
except errors.FileExists:
869
return self.transport.clone('checkout')
871
def needs_format_conversion(self, format=None):
872
"""See BzrDir.needs_format_conversion()."""
874
format = BzrDirFormat.get_default_format()
875
if not isinstance(self._format, format.__class__):
876
# it is not a meta dir format, conversion is needed.
878
# we might want to push this down to the repository?
880
if not isinstance(self.open_repository()._format,
881
format.repository_format.__class__):
882
# the repository needs an upgrade.
884
except errors.NoRepositoryPresent:
886
# currently there are no other possible conversions for meta1 formats.
889
def open_branch(self, unsupported=False):
890
"""See BzrDir.open_branch."""
891
from bzrlib.branch import BranchFormat
892
format = BranchFormat.find_format(self)
893
self._check_supported(format, unsupported)
894
return format.open(self, _found=True)
896
def open_repository(self, unsupported=False):
897
"""See BzrDir.open_repository."""
898
from bzrlib.repository import RepositoryFormat
899
format = RepositoryFormat.find_format(self)
900
self._check_supported(format, unsupported)
901
return format.open(self, _found=True)
903
def open_workingtree(self, unsupported=False):
904
"""See BzrDir.open_workingtree."""
905
from bzrlib.workingtree import WorkingTreeFormat
906
format = WorkingTreeFormat.find_format(self)
907
self._check_supported(format, unsupported)
908
return format.open(self, _found=True)
911
class BzrDirFormat(object):
912
"""An encapsulation of the initialization and open routines for a format.
914
Formats provide three things:
915
* An initialization routine,
919
Formats are placed in an dict by their format string for reference
920
during bzrdir opening. These should be subclasses of BzrDirFormat
923
Once a format is deprecated, just deprecate the initialize and open
924
methods on the format class. Do not deprecate the object, as the
925
object will be created every system load.
928
_default_format = None
929
"""The default format used for new .bzr dirs."""
932
"""The known formats."""
934
_lock_file_name = 'branch-lock'
936
# _lock_class must be set in subclasses to the lock type, typ.
937
# TransportLock or LockDir
940
def find_format(klass, transport):
941
"""Return the format registered for URL."""
943
format_string = transport.get(".bzr/branch-format").read()
944
return klass._formats[format_string]
945
except errors.NoSuchFile:
946
raise errors.NotBranchError(path=transport.base)
948
raise errors.UnknownFormatError(format_string)
951
def get_default_format(klass):
952
"""Return the current default format."""
953
return klass._default_format
955
def get_format_string(self):
956
"""Return the ASCII format string that identifies this format."""
957
raise NotImplementedError(self.get_format_string)
959
def get_format_description(self):
960
"""Return the short description for this format."""
961
raise NotImplementedError(self.get_format_description)
963
def get_converter(self, format=None):
964
"""Return the converter to use to convert bzrdirs needing converts.
966
This returns a bzrlib.bzrdir.Converter object.
968
This should return the best upgrader to step this format towards the
969
current default format. In the case of plugins we can/shouold provide
970
some means for them to extend the range of returnable converters.
972
:param format: Optional format to override the default foramt of the
975
raise NotImplementedError(self.get_converter)
977
def initialize(self, url):
978
"""Create a bzr control dir at this url and return an opened copy.
980
Subclasses should typically override initialize_on_transport
981
instead of this method.
983
return self.initialize_on_transport(get_transport(url))
985
def initialize_on_transport(self, transport):
986
"""Initialize a new bzrdir in the base directory of a Transport."""
987
# Since we don'transport have a .bzr directory, inherit the
988
# mode from the root directory
989
temp_control = LockableFiles(transport, '', TransportLock)
990
temp_control._transport.mkdir('.bzr',
991
# FIXME: RBC 20060121 dont peek under
993
mode=temp_control._dir_mode)
994
file_mode = temp_control._file_mode
996
mutter('created control directory in ' + transport.base)
997
control = transport.clone('.bzr')
998
utf8_files = [('README',
999
"This is a Bazaar-NG control directory.\n"
1000
"Do not change any files in this directory.\n"),
1001
('branch-format', self.get_format_string()),
1003
# NB: no need to escape relative paths that are url safe.
1004
control_files = LockableFiles(control, self._lock_file_name,
1006
control_files.create_lock()
1007
control_files.lock_write()
1009
for file, content in utf8_files:
1010
control_files.put_utf8(file, content)
1012
control_files.unlock()
1013
return self.open(transport, _found=True)
1015
def is_supported(self):
1016
"""Is this format supported?
1018
Supported formats must be initializable and openable.
1019
Unsupported formats may not support initialization or committing or
1020
some other features depending on the reason for not being supported.
1024
def open(self, transport, _found=False):
1025
"""Return an instance of this format for the dir transport points at.
1027
_found is a private parameter, do not use it.
1030
assert isinstance(BzrDirFormat.find_format(transport),
1032
return self._open(transport)
1034
def _open(self, transport):
1035
"""Template method helper for opening BzrDirectories.
1037
This performs the actual open and any additional logic or parameter
1040
raise NotImplementedError(self._open)
1043
def register_format(klass, format):
1044
klass._formats[format.get_format_string()] = format
1047
def set_default_format(klass, format):
1048
klass._default_format = format
1051
return self.get_format_string()[:-1]
1054
def unregister_format(klass, format):
1055
assert klass._formats[format.get_format_string()] is format
1056
del klass._formats[format.get_format_string()]
1059
class BzrDirFormat4(BzrDirFormat):
1060
"""Bzr dir format 4.
1062
This format is a combined format for working tree, branch and repository.
1064
- Format 1 working trees [always]
1065
- Format 4 branches [always]
1066
- Format 4 repositories [always]
1068
This format is deprecated: it indexes texts using a text it which is
1069
removed in format 5; write support for this format has been removed.
1072
_lock_class = TransportLock
1074
def get_format_string(self):
1075
"""See BzrDirFormat.get_format_string()."""
1076
return "Bazaar-NG branch, format 0.0.4\n"
1078
def get_format_description(self):
1079
"""See BzrDirFormat.get_format_description()."""
1080
return "All-in-one format 4"
1082
def get_converter(self, format=None):
1083
"""See BzrDirFormat.get_converter()."""
1084
# there is one and only one upgrade path here.
1085
return ConvertBzrDir4To5()
1087
def initialize_on_transport(self, transport):
1088
"""Format 4 branches cannot be created."""
1089
raise errors.UninitializableFormat(self)
1091
def is_supported(self):
1092
"""Format 4 is not supported.
1094
It is not supported because the model changed from 4 to 5 and the
1095
conversion logic is expensive - so doing it on the fly was not
1100
def _open(self, transport):
1101
"""See BzrDirFormat._open."""
1102
return BzrDir4(transport, self)
1104
def __return_repository_format(self):
1105
"""Circular import protection."""
1106
from bzrlib.repository import RepositoryFormat4
1107
return RepositoryFormat4(self)
1108
repository_format = property(__return_repository_format)
1111
class BzrDirFormat5(BzrDirFormat):
1112
"""Bzr control format 5.
1114
This format is a combined format for working tree, branch and repository.
1116
- Format 2 working trees [always]
1117
- Format 4 branches [always]
1118
- Format 5 repositories [always]
1119
Unhashed stores in the repository.
1122
_lock_class = TransportLock
1124
def get_format_string(self):
1125
"""See BzrDirFormat.get_format_string()."""
1126
return "Bazaar-NG branch, format 5\n"
1128
def get_format_description(self):
1129
"""See BzrDirFormat.get_format_description()."""
1130
return "All-in-one format 5"
1132
def get_converter(self, format=None):
1133
"""See BzrDirFormat.get_converter()."""
1134
# there is one and only one upgrade path here.
1135
return ConvertBzrDir5To6()
1137
def _initialize_for_clone(self, url):
1138
return self.initialize_on_transport(get_transport(url), _cloning=True)
1140
def initialize_on_transport(self, transport, _cloning=False):
1141
"""Format 5 dirs always have working tree, branch and repository.
1143
Except when they are being cloned.
1145
from bzrlib.branch import BzrBranchFormat4
1146
from bzrlib.repository import RepositoryFormat5
1147
from bzrlib.workingtree import WorkingTreeFormat2
1148
result = (super(BzrDirFormat5, self).initialize_on_transport(transport))
1149
RepositoryFormat5().initialize(result, _internal=True)
1151
BzrBranchFormat4().initialize(result)
1152
WorkingTreeFormat2().initialize(result)
1155
def _open(self, transport):
1156
"""See BzrDirFormat._open."""
1157
return BzrDir5(transport, self)
1159
def __return_repository_format(self):
1160
"""Circular import protection."""
1161
from bzrlib.repository import RepositoryFormat5
1162
return RepositoryFormat5(self)
1163
repository_format = property(__return_repository_format)
1166
class BzrDirFormat6(BzrDirFormat):
1167
"""Bzr control format 6.
1169
This format is a combined format for working tree, branch and repository.
1171
- Format 2 working trees [always]
1172
- Format 4 branches [always]
1173
- Format 6 repositories [always]
1176
_lock_class = TransportLock
1178
def get_format_string(self):
1179
"""See BzrDirFormat.get_format_string()."""
1180
return "Bazaar-NG branch, format 6\n"
1182
def get_format_description(self):
1183
"""See BzrDirFormat.get_format_description()."""
1184
return "All-in-one format 6"
1186
def get_converter(self, format=None):
1187
"""See BzrDirFormat.get_converter()."""
1188
# there is one and only one upgrade path here.
1189
return ConvertBzrDir6ToMeta()
1191
def _initialize_for_clone(self, url):
1192
return self.initialize_on_transport(get_transport(url), _cloning=True)
1194
def initialize_on_transport(self, transport, _cloning=False):
1195
"""Format 6 dirs always have working tree, branch and repository.
1197
Except when they are being cloned.
1199
from bzrlib.branch import BzrBranchFormat4
1200
from bzrlib.repository import RepositoryFormat6
1201
from bzrlib.workingtree import WorkingTreeFormat2
1202
result = super(BzrDirFormat6, self).initialize_on_transport(transport)
1203
RepositoryFormat6().initialize(result, _internal=True)
1205
BzrBranchFormat4().initialize(result)
1207
WorkingTreeFormat2().initialize(result)
1208
except errors.NotLocalUrl:
1209
# emulate pre-check behaviour for working tree and silently
1214
def _open(self, transport):
1215
"""See BzrDirFormat._open."""
1216
return BzrDir6(transport, self)
1218
def __return_repository_format(self):
1219
"""Circular import protection."""
1220
from bzrlib.repository import RepositoryFormat6
1221
return RepositoryFormat6(self)
1222
repository_format = property(__return_repository_format)
1225
class BzrDirMetaFormat1(BzrDirFormat):
1226
"""Bzr meta control format 1
1228
This is the first format with split out working tree, branch and repository
1231
- Format 3 working trees [optional]
1232
- Format 5 branches [optional]
1233
- Format 7 repositories [optional]
1236
_lock_class = LockDir
1238
def get_converter(self, format=None):
1239
"""See BzrDirFormat.get_converter()."""
1241
format = BzrDirFormat.get_default_format()
1242
if not isinstance(self, format.__class__):
1243
# converting away from metadir is not implemented
1244
raise NotImplementedError(self.get_converter)
1245
return ConvertMetaToMeta(format)
1247
def get_format_string(self):
1248
"""See BzrDirFormat.get_format_string()."""
1249
return "Bazaar-NG meta directory, format 1\n"
1251
def get_format_description(self):
1252
"""See BzrDirFormat.get_format_description()."""
1253
return "Meta directory format 1"
1255
def _open(self, transport):
1256
"""See BzrDirFormat._open."""
1257
return BzrDirMeta1(transport, self)
1259
def __return_repository_format(self):
1260
"""Circular import protection."""
1261
if getattr(self, '_repository_format', None):
1262
return self._repository_format
1263
from bzrlib.repository import RepositoryFormat
1264
return RepositoryFormat.get_default_format()
1266
def __set_repository_format(self, value):
1267
"""Allow changint the repository format for metadir formats."""
1268
self._repository_format = value
1270
repository_format = property(__return_repository_format, __set_repository_format)
1273
BzrDirFormat.register_format(BzrDirFormat4())
1274
BzrDirFormat.register_format(BzrDirFormat5())
1275
BzrDirFormat.register_format(BzrDirFormat6())
1276
__default_format = BzrDirMetaFormat1()
1277
BzrDirFormat.register_format(__default_format)
1278
BzrDirFormat.set_default_format(__default_format)
1281
class BzrDirTestProviderAdapter(object):
1282
"""A tool to generate a suite testing multiple bzrdir formats at once.
1284
This is done by copying the test once for each transport and injecting
1285
the transport_server, transport_readonly_server, and bzrdir_format
1286
classes into each copy. Each copy is also given a new id() to make it
1290
def __init__(self, transport_server, transport_readonly_server, formats):
1291
self._transport_server = transport_server
1292
self._transport_readonly_server = transport_readonly_server
1293
self._formats = formats
1295
def adapt(self, test):
1296
result = TestSuite()
1297
for format in self._formats:
1298
new_test = deepcopy(test)
1299
new_test.transport_server = self._transport_server
1300
new_test.transport_readonly_server = self._transport_readonly_server
1301
new_test.bzrdir_format = format
1302
def make_new_test_id():
1303
new_id = "%s(%s)" % (new_test.id(), format.__class__.__name__)
1304
return lambda: new_id
1305
new_test.id = make_new_test_id()
1306
result.addTest(new_test)
1310
class Converter(object):
1311
"""Converts a disk format object from one format to another."""
1313
def convert(self, to_convert, pb):
1314
"""Perform the conversion of to_convert, giving feedback via pb.
1316
:param to_convert: The disk object to convert.
1317
:param pb: a progress bar to use for progress information.
1320
def step(self, message):
1321
"""Update the pb by a step."""
1323
self.pb.update(message, self.count, self.total)
1326
class ConvertBzrDir4To5(Converter):
1327
"""Converts format 4 bzr dirs to format 5."""
1330
super(ConvertBzrDir4To5, self).__init__()
1331
self.converted_revs = set()
1332
self.absent_revisions = set()
1336
def convert(self, to_convert, pb):
1337
"""See Converter.convert()."""
1338
self.bzrdir = to_convert
1340
self.pb.note('starting upgrade from format 4 to 5')
1341
if isinstance(self.bzrdir.transport, LocalTransport):
1342
self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
1343
self._convert_to_weaves()
1344
return BzrDir.open(self.bzrdir.root_transport.base)
1346
def _convert_to_weaves(self):
1347
self.pb.note('note: upgrade may be faster if all store files are ungzipped first')
1350
stat = self.bzrdir.transport.stat('weaves')
1351
if not S_ISDIR(stat.st_mode):
1352
self.bzrdir.transport.delete('weaves')
1353
self.bzrdir.transport.mkdir('weaves')
1354
except errors.NoSuchFile:
1355
self.bzrdir.transport.mkdir('weaves')
1356
# deliberately not a WeaveFile as we want to build it up slowly.
1357
self.inv_weave = Weave('inventory')
1358
# holds in-memory weaves for all files
1359
self.text_weaves = {}
1360
self.bzrdir.transport.delete('branch-format')
1361
self.branch = self.bzrdir.open_branch()
1362
self._convert_working_inv()
1363
rev_history = self.branch.revision_history()
1364
# to_read is a stack holding the revisions we still need to process;
1365
# appending to it adds new highest-priority revisions
1366
self.known_revisions = set(rev_history)
1367
self.to_read = rev_history[-1:]
1369
rev_id = self.to_read.pop()
1370
if (rev_id not in self.revisions
1371
and rev_id not in self.absent_revisions):
1372
self._load_one_rev(rev_id)
1374
to_import = self._make_order()
1375
for i, rev_id in enumerate(to_import):
1376
self.pb.update('converting revision', i, len(to_import))
1377
self._convert_one_rev(rev_id)
1379
self._write_all_weaves()
1380
self._write_all_revs()
1381
self.pb.note('upgraded to weaves:')
1382
self.pb.note(' %6d revisions and inventories', len(self.revisions))
1383
self.pb.note(' %6d revisions not present', len(self.absent_revisions))
1384
self.pb.note(' %6d texts', self.text_count)
1385
self._cleanup_spare_files_after_format4()
1386
self.branch.control_files.put_utf8('branch-format', BzrDirFormat5().get_format_string())
1388
def _cleanup_spare_files_after_format4(self):
1389
# FIXME working tree upgrade foo.
1390
for n in 'merged-patches', 'pending-merged-patches':
1392
## assert os.path.getsize(p) == 0
1393
self.bzrdir.transport.delete(n)
1394
except errors.NoSuchFile:
1396
self.bzrdir.transport.delete_tree('inventory-store')
1397
self.bzrdir.transport.delete_tree('text-store')
1399
def _convert_working_inv(self):
1400
inv = serializer_v4.read_inventory(self.branch.control_files.get('inventory'))
1401
new_inv_xml = bzrlib.xml5.serializer_v5.write_inventory_to_string(inv)
1402
# FIXME inventory is a working tree change.
1403
self.branch.control_files.put('inventory', new_inv_xml)
1405
def _write_all_weaves(self):
1406
controlweaves = WeaveStore(self.bzrdir.transport, prefixed=False)
1407
weave_transport = self.bzrdir.transport.clone('weaves')
1408
weaves = WeaveStore(weave_transport, prefixed=False)
1409
transaction = WriteTransaction()
1413
for file_id, file_weave in self.text_weaves.items():
1414
self.pb.update('writing weave', i, len(self.text_weaves))
1415
weaves._put_weave(file_id, file_weave, transaction)
1417
self.pb.update('inventory', 0, 1)
1418
controlweaves._put_weave('inventory', self.inv_weave, transaction)
1419
self.pb.update('inventory', 1, 1)
1423
def _write_all_revs(self):
1424
"""Write all revisions out in new form."""
1425
self.bzrdir.transport.delete_tree('revision-store')
1426
self.bzrdir.transport.mkdir('revision-store')
1427
revision_transport = self.bzrdir.transport.clone('revision-store')
1429
_revision_store = TextRevisionStore(TextStore(revision_transport,
1433
transaction = bzrlib.transactions.WriteTransaction()
1434
for i, rev_id in enumerate(self.converted_revs):
1435
self.pb.update('write revision', i, len(self.converted_revs))
1436
_revision_store.add_revision(self.revisions[rev_id], transaction)
1440
def _load_one_rev(self, rev_id):
1441
"""Load a revision object into memory.
1443
Any parents not either loaded or abandoned get queued to be
1445
self.pb.update('loading revision',
1446
len(self.revisions),
1447
len(self.known_revisions))
1448
if not self.branch.repository.has_revision(rev_id):
1450
self.pb.note('revision {%s} not present in branch; '
1451
'will be converted as a ghost',
1453
self.absent_revisions.add(rev_id)
1455
rev = self.branch.repository._revision_store.get_revision(rev_id,
1456
self.branch.repository.get_transaction())
1457
for parent_id in rev.parent_ids:
1458
self.known_revisions.add(parent_id)
1459
self.to_read.append(parent_id)
1460
self.revisions[rev_id] = rev
1462
def _load_old_inventory(self, rev_id):
1463
assert rev_id not in self.converted_revs
1464
old_inv_xml = self.branch.repository.inventory_store.get(rev_id).read()
1465
inv = serializer_v4.read_inventory_from_string(old_inv_xml)
1466
rev = self.revisions[rev_id]
1467
if rev.inventory_sha1:
1468
assert rev.inventory_sha1 == sha_string(old_inv_xml), \
1469
'inventory sha mismatch for {%s}' % rev_id
1472
def _load_updated_inventory(self, rev_id):
1473
assert rev_id in self.converted_revs
1474
inv_xml = self.inv_weave.get_text(rev_id)
1475
inv = bzrlib.xml5.serializer_v5.read_inventory_from_string(inv_xml)
1478
def _convert_one_rev(self, rev_id):
1479
"""Convert revision and all referenced objects to new format."""
1480
rev = self.revisions[rev_id]
1481
inv = self._load_old_inventory(rev_id)
1482
present_parents = [p for p in rev.parent_ids
1483
if p not in self.absent_revisions]
1484
self._convert_revision_contents(rev, inv, present_parents)
1485
self._store_new_weave(rev, inv, present_parents)
1486
self.converted_revs.add(rev_id)
1488
def _store_new_weave(self, rev, inv, present_parents):
1489
# the XML is now updated with text versions
1493
if ie.kind == 'root_directory':
1495
assert hasattr(ie, 'revision'), \
1496
'no revision on {%s} in {%s}' % \
1497
(file_id, rev.revision_id)
1498
new_inv_xml = bzrlib.xml5.serializer_v5.write_inventory_to_string(inv)
1499
new_inv_sha1 = sha_string(new_inv_xml)
1500
self.inv_weave.add_lines(rev.revision_id,
1502
new_inv_xml.splitlines(True))
1503
rev.inventory_sha1 = new_inv_sha1
1505
def _convert_revision_contents(self, rev, inv, present_parents):
1506
"""Convert all the files within a revision.
1508
Also upgrade the inventory to refer to the text revision ids."""
1509
rev_id = rev.revision_id
1510
mutter('converting texts of revision {%s}',
1512
parent_invs = map(self._load_updated_inventory, present_parents)
1515
self._convert_file_version(rev, ie, parent_invs)
1517
def _convert_file_version(self, rev, ie, parent_invs):
1518
"""Convert one version of one file.
1520
The file needs to be added into the weave if it is a merge
1521
of >=2 parents or if it's changed from its parent.
1523
if ie.kind == 'root_directory':
1525
file_id = ie.file_id
1526
rev_id = rev.revision_id
1527
w = self.text_weaves.get(file_id)
1530
self.text_weaves[file_id] = w
1531
text_changed = False
1532
previous_entries = ie.find_previous_heads(parent_invs,
1536
for old_revision in previous_entries:
1537
# if this fails, its a ghost ?
1538
assert old_revision in self.converted_revs
1539
self.snapshot_ie(previous_entries, ie, w, rev_id)
1541
assert getattr(ie, 'revision', None) is not None
1543
def snapshot_ie(self, previous_revisions, ie, w, rev_id):
1544
# TODO: convert this logic, which is ~= snapshot to
1545
# a call to:. This needs the path figured out. rather than a work_tree
1546
# a v4 revision_tree can be given, or something that looks enough like
1547
# one to give the file content to the entry if it needs it.
1548
# and we need something that looks like a weave store for snapshot to
1550
#ie.snapshot(rev, PATH, previous_revisions, REVISION_TREE, InMemoryWeaveStore(self.text_weaves))
1551
if len(previous_revisions) == 1:
1552
previous_ie = previous_revisions.values()[0]
1553
if ie._unchanged(previous_ie):
1554
ie.revision = previous_ie.revision
1557
text = self.branch.repository.text_store.get(ie.text_id)
1558
file_lines = text.readlines()
1559
assert sha_strings(file_lines) == ie.text_sha1
1560
assert sum(map(len, file_lines)) == ie.text_size
1561
w.add_lines(rev_id, previous_revisions, file_lines)
1562
self.text_count += 1
1564
w.add_lines(rev_id, previous_revisions, [])
1565
ie.revision = rev_id
1567
def _make_order(self):
1568
"""Return a suitable order for importing revisions.
1570
The order must be such that an revision is imported after all
1571
its (present) parents.
1573
todo = set(self.revisions.keys())
1574
done = self.absent_revisions.copy()
1577
# scan through looking for a revision whose parents
1579
for rev_id in sorted(list(todo)):
1580
rev = self.revisions[rev_id]
1581
parent_ids = set(rev.parent_ids)
1582
if parent_ids.issubset(done):
1583
# can take this one now
1584
order.append(rev_id)
1590
class ConvertBzrDir5To6(Converter):
1591
"""Converts format 5 bzr dirs to format 6."""
1593
def convert(self, to_convert, pb):
1594
"""See Converter.convert()."""
1595
self.bzrdir = to_convert
1597
self.pb.note('starting upgrade from format 5 to 6')
1598
self._convert_to_prefixed()
1599
return BzrDir.open(self.bzrdir.root_transport.base)
1601
def _convert_to_prefixed(self):
1602
from bzrlib.store import TransportStore
1603
self.bzrdir.transport.delete('branch-format')
1604
for store_name in ["weaves", "revision-store"]:
1605
self.pb.note("adding prefixes to %s" % store_name)
1606
store_transport = self.bzrdir.transport.clone(store_name)
1607
store = TransportStore(store_transport, prefixed=True)
1608
for urlfilename in store_transport.list_dir('.'):
1609
filename = urlunescape(urlfilename)
1610
if (filename.endswith(".weave") or
1611
filename.endswith(".gz") or
1612
filename.endswith(".sig")):
1613
file_id = os.path.splitext(filename)[0]
1616
prefix_dir = store.hash_prefix(file_id)
1617
# FIXME keep track of the dirs made RBC 20060121
1619
store_transport.move(filename, prefix_dir + '/' + filename)
1620
except errors.NoSuchFile: # catches missing dirs strangely enough
1621
store_transport.mkdir(prefix_dir)
1622
store_transport.move(filename, prefix_dir + '/' + filename)
1623
self.bzrdir._control_files.put_utf8('branch-format', BzrDirFormat6().get_format_string())
1626
class ConvertBzrDir6ToMeta(Converter):
1627
"""Converts format 6 bzr dirs to metadirs."""
1629
def convert(self, to_convert, pb):
1630
"""See Converter.convert()."""
1631
self.bzrdir = to_convert
1634
self.total = 20 # the steps we know about
1635
self.garbage_inventories = []
1637
self.pb.note('starting upgrade from format 6 to metadir')
1638
self.bzrdir._control_files.put_utf8('branch-format', "Converting to format 6")
1639
# its faster to move specific files around than to open and use the apis...
1640
# first off, nuke ancestry.weave, it was never used.
1642
self.step('Removing ancestry.weave')
1643
self.bzrdir.transport.delete('ancestry.weave')
1644
except errors.NoSuchFile:
1646
# find out whats there
1647
self.step('Finding branch files')
1648
last_revision = self.bzrdir.open_branch().last_revision()
1649
bzrcontents = self.bzrdir.transport.list_dir('.')
1650
for name in bzrcontents:
1651
if name.startswith('basis-inventory.'):
1652
self.garbage_inventories.append(name)
1653
# create new directories for repository, working tree and branch
1654
self.dir_mode = self.bzrdir._control_files._dir_mode
1655
self.file_mode = self.bzrdir._control_files._file_mode
1656
repository_names = [('inventory.weave', True),
1657
('revision-store', True),
1659
self.step('Upgrading repository ')
1660
self.bzrdir.transport.mkdir('repository', mode=self.dir_mode)
1661
self.make_lock('repository')
1662
# we hard code the formats here because we are converting into
1663
# the meta format. The meta format upgrader can take this to a
1664
# future format within each component.
1665
self.put_format('repository', bzrlib.repository.RepositoryFormat7())
1666
for entry in repository_names:
1667
self.move_entry('repository', entry)
1669
self.step('Upgrading branch ')
1670
self.bzrdir.transport.mkdir('branch', mode=self.dir_mode)
1671
self.make_lock('branch')
1672
self.put_format('branch', bzrlib.branch.BzrBranchFormat5())
1673
branch_files = [('revision-history', True),
1674
('branch-name', True),
1676
for entry in branch_files:
1677
self.move_entry('branch', entry)
1679
self.step('Upgrading working tree')
1680
self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
1681
self.make_lock('checkout')
1682
self.put_format('checkout', bzrlib.workingtree.WorkingTreeFormat3())
1683
self.bzrdir.transport.delete_multi(self.garbage_inventories, self.pb)
1684
checkout_files = [('pending-merges', True),
1685
('inventory', True),
1686
('stat-cache', False)]
1687
for entry in checkout_files:
1688
self.move_entry('checkout', entry)
1689
if last_revision is not None:
1690
self.bzrdir._control_files.put_utf8('checkout/last-revision',
1692
self.bzrdir._control_files.put_utf8('branch-format', BzrDirMetaFormat1().get_format_string())
1693
return BzrDir.open(self.bzrdir.root_transport.base)
1695
def make_lock(self, name):
1696
"""Make a lock for the new control dir name."""
1697
self.step('Make %s lock' % name)
1698
ld = LockDir(self.bzrdir.transport,
1700
file_modebits=self.file_mode,
1701
dir_modebits=self.dir_mode)
1704
def move_entry(self, new_dir, entry):
1705
"""Move then entry name into new_dir."""
1707
mandatory = entry[1]
1708
self.step('Moving %s' % name)
1710
self.bzrdir.transport.move(name, '%s/%s' % (new_dir, name))
1711
except errors.NoSuchFile:
1715
def put_format(self, dirname, format):
1716
self.bzrdir._control_files.put_utf8('%s/format' % dirname, format.get_format_string())
1719
class ConvertMetaToMeta(Converter):
1720
"""Converts the components of metadirs."""
1722
def __init__(self, target_format):
1723
"""Create a metadir to metadir converter.
1725
:param target_format: The final metadir format that is desired.
1727
self.target_format = target_format
1729
def convert(self, to_convert, pb):
1730
"""See Converter.convert()."""
1731
self.bzrdir = to_convert
1735
self.step('checking repository format')
1737
repo = self.bzrdir.open_repository()
1738
except errors.NoRepositoryPresent:
1741
if not isinstance(repo._format, self.target_format.repository_format.__class__):
1742
from bzrlib.repository import CopyConverter
1743
self.pb.note('starting repository conversion')
1744
converter = CopyConverter(self.target_format.repository_format)
1745
converter.convert(repo, pb)