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
47
from bzrlib.transport.local import LocalTransport
48
import bzrlib.urlutils as urlutils
49
from bzrlib.weave import Weave
50
from bzrlib.xml4 import serializer_v4
51
from bzrlib.xml5 import serializer_v5
55
"""A .bzr control diretory.
57
BzrDir instances let you create or open any of the things that can be
58
found within .bzr - checkouts, branches and repositories.
61
the transport which this bzr dir is rooted at (i.e. file:///.../.bzr/)
63
a transport connected to the directory this bzr was opened from.
66
def can_convert_format(self):
67
"""Return true if this bzrdir is one whose format we can convert from."""
71
def _check_supported(format, allow_unsupported):
72
"""Check whether format is a supported format.
74
If allow_unsupported is True, this is a no-op.
76
if not allow_unsupported and not format.is_supported():
77
# see open_downlevel to open legacy branches.
78
raise errors.UnsupportedFormatError(
79
'sorry, format %s not supported' % format,
80
['use a different bzr version',
81
'or remove the .bzr directory'
82
' and "bzr init" again'])
84
def clone(self, url, revision_id=None, basis=None, force_new_repo=False):
85
"""Clone this bzrdir and its contents to url verbatim.
87
If urls last component does not exist, it will be created.
89
if revision_id is not None, then the clone operation may tune
90
itself to download less data.
91
:param force_new_repo: Do not use a shared repository for the target
92
even if one is available.
95
basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
96
result = self._format.initialize(url)
98
local_repo = self.find_repository()
99
except errors.NoRepositoryPresent:
102
# may need to copy content in
104
local_repo.clone(result, revision_id=revision_id, basis=basis_repo)
107
result_repo = result.find_repository()
108
# fetch content this dir needs.
110
# XXX FIXME RBC 20060214 need tests for this when the basis
112
result_repo.fetch(basis_repo, revision_id=revision_id)
113
result_repo.fetch(local_repo, revision_id=revision_id)
114
except errors.NoRepositoryPresent:
115
# needed to make one anyway.
116
local_repo.clone(result, revision_id=revision_id, basis=basis_repo)
117
# 1 if there is a branch present
118
# make sure its content is available in the target repository
121
self.open_branch().clone(result, revision_id=revision_id)
122
except errors.NotBranchError:
125
self.open_workingtree().clone(result, basis=basis_tree)
126
except (errors.NoWorkingTree, errors.NotLocalUrl):
130
def _get_basis_components(self, basis):
131
"""Retrieve the basis components that are available at basis."""
133
return None, None, None
135
basis_tree = basis.open_workingtree()
136
basis_branch = basis_tree.branch
137
basis_repo = basis_branch.repository
138
except (errors.NoWorkingTree, errors.NotLocalUrl):
141
basis_branch = basis.open_branch()
142
basis_repo = basis_branch.repository
143
except errors.NotBranchError:
146
basis_repo = basis.open_repository()
147
except errors.NoRepositoryPresent:
149
return basis_repo, basis_branch, basis_tree
151
def _make_tail(self, url):
152
segments = url.split('/')
153
if segments and segments[-1] not in ('', '.'):
154
parent = '/'.join(segments[:-1])
155
print '_make_tail(%s) => parent: %s, segment: %s' % (
156
url, parent, segments[-1])
157
t = bzrlib.transport.get_transport(parent)
159
t.mkdir(segments[-1])
160
except errors.FileExists:
164
def create(cls, base):
165
"""Create a new BzrDir at the url 'base'.
167
This will call the current default formats initialize with base
168
as the only parameter.
170
If you need a specific format, consider creating an instance
171
of that and calling initialize().
173
if cls is not BzrDir:
174
raise AssertionError("BzrDir.create always creates the default format, "
175
"not one of %r" % cls)
176
segments = base.split('/')
177
if segments and segments[-1] not in ('', '.'):
178
parent = '/'.join(segments[:-1])
179
t = bzrlib.transport.get_transport(parent)
181
t.mkdir(segments[-1])
182
except errors.FileExists:
184
return BzrDirFormat.get_default_format().initialize(safe_unicode(base))
186
def create_branch(self):
187
"""Create a branch in this BzrDir.
189
The bzrdirs format will control what branch format is created.
190
For more control see BranchFormatXX.create(a_bzrdir).
192
raise NotImplementedError(self.create_branch)
195
def create_branch_and_repo(base, force_new_repo=False):
196
"""Create a new BzrDir, Branch and Repository at the url 'base'.
198
This will use the current default BzrDirFormat, and use whatever
199
repository format that that uses via bzrdir.create_branch and
200
create_repository. If a shared repository is available that is used
203
The created Branch object is returned.
205
:param base: The URL to create the branch at.
206
:param force_new_repo: If True a new repository is always created.
208
bzrdir = BzrDir.create(base)
209
bzrdir._find_or_create_repository(force_new_repo)
210
return bzrdir.create_branch()
212
def _find_or_create_repository(self, force_new_repo):
213
"""Create a new repository if needed, returning the repository."""
215
return self.create_repository()
217
return self.find_repository()
218
except errors.NoRepositoryPresent:
219
return self.create_repository()
222
def create_branch_convenience(base, force_new_repo=False,
223
force_new_tree=None, format=None):
224
"""Create a new BzrDir, Branch and Repository at the url 'base'.
226
This is a convenience function - it will use an existing repository
227
if possible, can be told explicitly whether to create a working tree or
230
This will use the current default BzrDirFormat, and use whatever
231
repository format that that uses via bzrdir.create_branch and
232
create_repository. If a shared repository is available that is used
233
preferentially. Whatever repository is used, its tree creation policy
236
The created Branch object is returned.
237
If a working tree cannot be made due to base not being a file:// url,
238
no error is raised unless force_new_tree is True, in which case no
239
data is created on disk and NotLocalUrl is raised.
241
:param base: The URL to create the branch at.
242
:param force_new_repo: If True a new repository is always created.
243
:param force_new_tree: If True or False force creation of a tree or
244
prevent such creation respectively.
245
:param format: Override for the for the bzrdir format to create
248
# check for non local urls
249
t = get_transport(safe_unicode(base))
250
if not isinstance(t, LocalTransport):
251
raise errors.NotLocalUrl(base)
253
bzrdir = BzrDir.create(base)
255
bzrdir = format.initialize(base)
256
repo = bzrdir._find_or_create_repository(force_new_repo)
257
result = bzrdir.create_branch()
258
if force_new_tree or (repo.make_working_trees() and
259
force_new_tree is None):
261
bzrdir.create_workingtree()
262
except errors.NotLocalUrl:
267
def create_repository(base, shared=False):
268
"""Create a new BzrDir and Repository at the url 'base'.
270
This will use the current default BzrDirFormat, and use whatever
271
repository format that that uses for bzrdirformat.create_repository.
273
;param shared: Create a shared repository rather than a standalone
275
The Repository object is returned.
277
This must be overridden as an instance method in child classes, where
278
it should take no parameters and construct whatever repository format
279
that child class desires.
281
bzrdir = BzrDir.create(base)
282
return bzrdir.create_repository()
285
def create_standalone_workingtree(base):
286
"""Create a new BzrDir, WorkingTree, Branch and Repository at 'base'.
288
'base' must be a local path or a file:// url.
290
This will use the current default BzrDirFormat, and use whatever
291
repository format that that uses for bzrdirformat.create_workingtree,
292
create_branch and create_repository.
294
The WorkingTree object is returned.
296
t = get_transport(safe_unicode(base))
297
if not isinstance(t, LocalTransport):
298
raise errors.NotLocalUrl(base)
299
bzrdir = BzrDir.create_branch_and_repo(safe_unicode(base),
300
force_new_repo=True).bzrdir
301
return bzrdir.create_workingtree()
303
def create_workingtree(self, revision_id=None):
304
"""Create a working tree at this BzrDir.
306
revision_id: create it as of this revision id.
308
raise NotImplementedError(self.create_workingtree)
310
def find_repository(self):
311
"""Find the repository that should be used for a_bzrdir.
313
This does not require a branch as we use it to find the repo for
314
new branches as well as to hook existing branches up to their
318
return self.open_repository()
319
except errors.NoRepositoryPresent:
321
next_transport = self.root_transport.clone('..')
324
found_bzrdir = BzrDir.open_containing_from_transport(
326
except errors.NotBranchError:
327
raise errors.NoRepositoryPresent(self)
329
repository = found_bzrdir.open_repository()
330
except errors.NoRepositoryPresent:
331
next_transport = found_bzrdir.root_transport.clone('..')
333
if ((found_bzrdir.root_transport.base ==
334
self.root_transport.base) or repository.is_shared()):
337
raise errors.NoRepositoryPresent(self)
338
raise errors.NoRepositoryPresent(self)
340
def get_branch_transport(self, branch_format):
341
"""Get the transport for use by branch format in this BzrDir.
343
Note that bzr dirs that do not support format strings will raise
344
IncompatibleFormat if the branch format they are given has
345
a format string, and vice verca.
347
If branch_format is None, the transport is returned with no
348
checking. if it is not None, then the returned transport is
349
guaranteed to point to an existing directory ready for use.
351
raise NotImplementedError(self.get_branch_transport)
353
def get_repository_transport(self, repository_format):
354
"""Get the transport for use by repository format in this BzrDir.
356
Note that bzr dirs that do not support format strings will raise
357
IncompatibleFormat if the repository format they are given has
358
a format string, and vice verca.
360
If repository_format is None, the transport is returned with no
361
checking. if it is not None, then the returned transport is
362
guaranteed to point to an existing directory ready for use.
364
raise NotImplementedError(self.get_repository_transport)
366
def get_workingtree_transport(self, tree_format):
367
"""Get the transport for use by workingtree format in this BzrDir.
369
Note that bzr dirs that do not support format strings will raise
370
IncompatibleFormat if the workingtree format they are given has
371
a format string, and vice verca.
373
If workingtree_format is None, the transport is returned with no
374
checking. if it is not None, then the returned transport is
375
guaranteed to point to an existing directory ready for use.
377
raise NotImplementedError(self.get_workingtree_transport)
379
def __init__(self, _transport, _format):
380
"""Initialize a Bzr control dir object.
382
Only really common logic should reside here, concrete classes should be
383
made with varying behaviours.
385
:param _format: the format that is creating this BzrDir instance.
386
:param _transport: the transport this dir is based at.
388
self._format = _format
389
self.transport = _transport.clone('.bzr')
390
self.root_transport = _transport
392
def needs_format_conversion(self, format=None):
393
"""Return true if this bzrdir needs convert_format run on it.
395
For instance, if the repository format is out of date but the
396
branch and working tree are not, this should return True.
398
:param format: Optional parameter indicating a specific desired
399
format we plan to arrive at.
401
raise NotImplementedError(self.needs_format_conversion)
404
def open_unsupported(base):
405
"""Open a branch which is not supported."""
406
return BzrDir.open(base, _unsupported=True)
409
def open(base, _unsupported=False):
410
"""Open an existing bzrdir, rooted at 'base' (url)
412
_unsupported is a private parameter to the BzrDir class.
414
t = get_transport(base)
415
mutter("trying to open %r with transport %r", base, t)
416
format = BzrDirFormat.find_format(t)
417
BzrDir._check_supported(format, _unsupported)
418
return format.open(t, _found=True)
420
def open_branch(self, unsupported=False):
421
"""Open the branch object at this BzrDir if one is present.
423
If unsupported is True, then no longer supported branch formats can
426
TODO: static convenience version of this?
428
raise NotImplementedError(self.open_branch)
431
def open_containing(url):
432
"""Open an existing branch which contains url.
434
:param url: url to search from.
435
See open_containing_from_transport for more detail.
437
return BzrDir.open_containing_from_transport(get_transport(url))
440
def open_containing_from_transport(a_transport):
441
"""Open an existing branch which contains a_transport.base
443
This probes for a branch at a_transport, and searches upwards from there.
445
Basically we keep looking up until we find the control directory or
446
run into the root. If there isn't one, raises NotBranchError.
447
If there is one and it is either an unrecognised format or an unsupported
448
format, UnknownFormatError or UnsupportedFormatError are raised.
449
If there is one, it is returned, along with the unused portion of url.
451
:return: The BzrDir that contains the path, and a Unicode path
452
for the rest of the URL.
454
# this gets the normalised url back. I.e. '.' -> the full path.
455
url = a_transport.base
458
format = BzrDirFormat.find_format(a_transport)
459
BzrDir._check_supported(format, False)
460
return format.open(a_transport), urlutils.unescape(a_transport.relpath(url))
461
except errors.NotBranchError, e:
462
mutter('not a branch in: %r %s', a_transport.base, e)
463
new_t = a_transport.clone('..')
464
if new_t.base == a_transport.base:
465
# reached the root, whatever that may be
466
raise errors.NotBranchError(path=url)
469
def open_repository(self, _unsupported=False):
470
"""Open the repository object at this BzrDir if one is present.
472
This will not follow the Branch object pointer - its strictly a direct
473
open facility. Most client code should use open_branch().repository to
476
_unsupported is a private parameter, not part of the api.
477
TODO: static convenience version of this?
479
raise NotImplementedError(self.open_repository)
481
def open_workingtree(self, _unsupported=False):
482
"""Open the workingtree object at this BzrDir if one is present.
484
TODO: static convenience version of this?
486
raise NotImplementedError(self.open_workingtree)
488
def has_branch(self):
489
"""Tell if this bzrdir contains a branch.
491
Note: if you're going to open the branch, you should just go ahead
492
and try, and not ask permission first. (This method just opens the
493
branch and discards it, and that's somewhat expensive.)
498
except errors.NotBranchError:
501
def has_workingtree(self):
502
"""Tell if this bzrdir contains a working tree.
504
This will still raise an exception if the bzrdir has a workingtree that
505
is remote & inaccessible.
507
Note: if you're going to open the working tree, you should just go ahead
508
and try, and not ask permission first. (This method just opens the
509
workingtree and discards it, and that's somewhat expensive.)
512
self.open_workingtree()
514
except errors.NoWorkingTree:
517
def sprout(self, url, revision_id=None, basis=None, force_new_repo=False):
518
"""Create a copy of this bzrdir prepared for use as a new line of
521
If urls last component does not exist, it will be created.
523
Attributes related to the identity of the source branch like
524
branch nickname will be cleaned, a working tree is created
525
whether one existed before or not; and a local branch is always
528
if revision_id is not None, then the clone operation may tune
529
itself to download less data.
532
result = self._format.initialize(url)
533
basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
535
source_branch = self.open_branch()
536
source_repository = source_branch.repository
537
except errors.NotBranchError:
540
source_repository = self.open_repository()
541
except errors.NoRepositoryPresent:
542
# copy the entire basis one if there is one
543
# but there is no repository.
544
source_repository = basis_repo
549
result_repo = result.find_repository()
550
except errors.NoRepositoryPresent:
552
if source_repository is None and result_repo is not None:
554
elif source_repository is None and result_repo is None:
555
# no repo available, make a new one
556
result.create_repository()
557
elif source_repository is not None and result_repo is None:
558
# have soure, and want to make a new target repo
559
source_repository.clone(result,
560
revision_id=revision_id,
563
# fetch needed content into target.
565
# XXX FIXME RBC 20060214 need tests for this when the basis
567
result_repo.fetch(basis_repo, revision_id=revision_id)
568
result_repo.fetch(source_repository, revision_id=revision_id)
569
if source_branch is not None:
570
source_branch.sprout(result, revision_id=revision_id)
572
result.create_branch()
573
# TODO: jam 20060426 we probably need a test in here in the
574
# case that the newly sprouted branch is a remote one
575
if result_repo is None or result_repo.make_working_trees():
576
result.create_workingtree()
580
class BzrDirPreSplitOut(BzrDir):
581
"""A common class for the all-in-one formats."""
583
def __init__(self, _transport, _format):
584
"""See BzrDir.__init__."""
585
super(BzrDirPreSplitOut, self).__init__(_transport, _format)
586
assert self._format._lock_class == TransportLock
587
assert self._format._lock_file_name == 'branch-lock'
588
self._control_files = LockableFiles(self.get_branch_transport(None),
589
self._format._lock_file_name,
590
self._format._lock_class)
592
def clone(self, url, revision_id=None, basis=None, force_new_repo=False):
593
"""See BzrDir.clone()."""
594
from bzrlib.workingtree import WorkingTreeFormat2
596
result = self._format._initialize_for_clone(url)
597
basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
598
self.open_repository().clone(result, revision_id=revision_id, basis=basis_repo)
599
self.open_branch().clone(result, revision_id=revision_id)
601
self.open_workingtree().clone(result, basis=basis_tree)
602
except errors.NotLocalUrl:
603
# make a new one, this format always has to have one.
605
WorkingTreeFormat2().initialize(result)
606
except errors.NotLocalUrl:
607
# but we canot do it for remote trees.
611
def create_branch(self):
612
"""See BzrDir.create_branch."""
613
return self.open_branch()
615
def create_repository(self, shared=False):
616
"""See BzrDir.create_repository."""
618
raise errors.IncompatibleFormat('shared repository', self._format)
619
return self.open_repository()
621
def create_workingtree(self, revision_id=None):
622
"""See BzrDir.create_workingtree."""
623
# this looks buggy but is not -really-
624
# clone and sprout will have set the revision_id
625
# and that will have set it for us, its only
626
# specific uses of create_workingtree in isolation
627
# that can do wonky stuff here, and that only
628
# happens for creating checkouts, which cannot be
629
# done on this format anyway. So - acceptable wart.
630
result = self.open_workingtree()
631
if revision_id is not None:
632
result.set_last_revision(revision_id)
635
def get_branch_transport(self, branch_format):
636
"""See BzrDir.get_branch_transport()."""
637
if branch_format is None:
638
return self.transport
640
branch_format.get_format_string()
641
except NotImplementedError:
642
return self.transport
643
raise errors.IncompatibleFormat(branch_format, self._format)
645
def get_repository_transport(self, repository_format):
646
"""See BzrDir.get_repository_transport()."""
647
if repository_format is None:
648
return self.transport
650
repository_format.get_format_string()
651
except NotImplementedError:
652
return self.transport
653
raise errors.IncompatibleFormat(repository_format, self._format)
655
def get_workingtree_transport(self, workingtree_format):
656
"""See BzrDir.get_workingtree_transport()."""
657
if workingtree_format is None:
658
return self.transport
660
workingtree_format.get_format_string()
661
except NotImplementedError:
662
return self.transport
663
raise errors.IncompatibleFormat(workingtree_format, self._format)
665
def needs_format_conversion(self, format=None):
666
"""See BzrDir.needs_format_conversion()."""
667
# if the format is not the same as the system default,
668
# an upgrade is needed.
670
format = BzrDirFormat.get_default_format()
671
return not isinstance(self._format, format.__class__)
673
def open_branch(self, unsupported=False):
674
"""See BzrDir.open_branch."""
675
from bzrlib.branch import BzrBranchFormat4
676
format = BzrBranchFormat4()
677
self._check_supported(format, unsupported)
678
return format.open(self, _found=True)
680
def sprout(self, url, revision_id=None, basis=None):
681
"""See BzrDir.sprout()."""
682
from bzrlib.workingtree import WorkingTreeFormat2
684
result = self._format._initialize_for_clone(url)
685
basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
687
self.open_repository().clone(result, revision_id=revision_id, basis=basis_repo)
688
except errors.NoRepositoryPresent:
691
self.open_branch().sprout(result, revision_id=revision_id)
692
except errors.NotBranchError:
694
# we always want a working tree
695
WorkingTreeFormat2().initialize(result)
699
class BzrDir4(BzrDirPreSplitOut):
700
"""A .bzr version 4 control object.
702
This is a deprecated format and may be removed after sept 2006.
705
def create_repository(self, shared=False):
706
"""See BzrDir.create_repository."""
707
return self._format.repository_format.initialize(self, shared)
709
def needs_format_conversion(self, format=None):
710
"""Format 4 dirs are always in need of conversion."""
713
def open_repository(self):
714
"""See BzrDir.open_repository."""
715
from bzrlib.repository import RepositoryFormat4
716
return RepositoryFormat4().open(self, _found=True)
719
class BzrDir5(BzrDirPreSplitOut):
720
"""A .bzr version 5 control object.
722
This is a deprecated format and may be removed after sept 2006.
725
def open_repository(self):
726
"""See BzrDir.open_repository."""
727
from bzrlib.repository import RepositoryFormat5
728
return RepositoryFormat5().open(self, _found=True)
730
def open_workingtree(self, _unsupported=False):
731
"""See BzrDir.create_workingtree."""
732
from bzrlib.workingtree import WorkingTreeFormat2
733
return WorkingTreeFormat2().open(self, _found=True)
736
class BzrDir6(BzrDirPreSplitOut):
737
"""A .bzr version 6 control object.
739
This is a deprecated format and may be removed after sept 2006.
742
def open_repository(self):
743
"""See BzrDir.open_repository."""
744
from bzrlib.repository import RepositoryFormat6
745
return RepositoryFormat6().open(self, _found=True)
747
def open_workingtree(self, _unsupported=False):
748
"""See BzrDir.create_workingtree."""
749
from bzrlib.workingtree import WorkingTreeFormat2
750
return WorkingTreeFormat2().open(self, _found=True)
753
class BzrDirMeta1(BzrDir):
754
"""A .bzr meta version 1 control object.
756
This is the first control object where the
757
individual aspects are really split out: there are separate repository,
758
workingtree and branch subdirectories and any subset of the three can be
759
present within a BzrDir.
762
def can_convert_format(self):
763
"""See BzrDir.can_convert_format()."""
766
def create_branch(self):
767
"""See BzrDir.create_branch."""
768
from bzrlib.branch import BranchFormat
769
return BranchFormat.get_default_format().initialize(self)
771
def create_repository(self, shared=False):
772
"""See BzrDir.create_repository."""
773
return self._format.repository_format.initialize(self, shared)
775
def create_workingtree(self, revision_id=None):
776
"""See BzrDir.create_workingtree."""
777
from bzrlib.workingtree import WorkingTreeFormat
778
return WorkingTreeFormat.get_default_format().initialize(self, revision_id)
780
def _get_mkdir_mode(self):
781
"""Figure out the mode to use when creating a bzrdir subdir."""
782
temp_control = LockableFiles(self.transport, '', TransportLock)
783
return temp_control._dir_mode
785
def get_branch_transport(self, branch_format):
786
"""See BzrDir.get_branch_transport()."""
787
if branch_format is None:
788
return self.transport.clone('branch')
790
branch_format.get_format_string()
791
except NotImplementedError:
792
raise errors.IncompatibleFormat(branch_format, self._format)
794
self.transport.mkdir('branch', mode=self._get_mkdir_mode())
795
except errors.FileExists:
797
return self.transport.clone('branch')
799
def get_repository_transport(self, repository_format):
800
"""See BzrDir.get_repository_transport()."""
801
if repository_format is None:
802
return self.transport.clone('repository')
804
repository_format.get_format_string()
805
except NotImplementedError:
806
raise errors.IncompatibleFormat(repository_format, self._format)
808
self.transport.mkdir('repository', mode=self._get_mkdir_mode())
809
except errors.FileExists:
811
return self.transport.clone('repository')
813
def get_workingtree_transport(self, workingtree_format):
814
"""See BzrDir.get_workingtree_transport()."""
815
if workingtree_format is None:
816
return self.transport.clone('checkout')
818
workingtree_format.get_format_string()
819
except NotImplementedError:
820
raise errors.IncompatibleFormat(workingtree_format, self._format)
822
self.transport.mkdir('checkout', mode=self._get_mkdir_mode())
823
except errors.FileExists:
825
return self.transport.clone('checkout')
827
def needs_format_conversion(self, format=None):
828
"""See BzrDir.needs_format_conversion()."""
830
format = BzrDirFormat.get_default_format()
831
if not isinstance(self._format, format.__class__):
832
# it is not a meta dir format, conversion is needed.
834
# we might want to push this down to the repository?
836
if not isinstance(self.open_repository()._format,
837
format.repository_format.__class__):
838
# the repository needs an upgrade.
840
except errors.NoRepositoryPresent:
842
# currently there are no other possible conversions for meta1 formats.
845
def open_branch(self, unsupported=False):
846
"""See BzrDir.open_branch."""
847
from bzrlib.branch import BranchFormat
848
format = BranchFormat.find_format(self)
849
self._check_supported(format, unsupported)
850
return format.open(self, _found=True)
852
def open_repository(self, unsupported=False):
853
"""See BzrDir.open_repository."""
854
from bzrlib.repository import RepositoryFormat
855
format = RepositoryFormat.find_format(self)
856
self._check_supported(format, unsupported)
857
return format.open(self, _found=True)
859
def open_workingtree(self, unsupported=False):
860
"""See BzrDir.open_workingtree."""
861
from bzrlib.workingtree import WorkingTreeFormat
862
format = WorkingTreeFormat.find_format(self)
863
self._check_supported(format, unsupported)
864
return format.open(self, _found=True)
867
class BzrDirFormat(object):
868
"""An encapsulation of the initialization and open routines for a format.
870
Formats provide three things:
871
* An initialization routine,
875
Formats are placed in an dict by their format string for reference
876
during bzrdir opening. These should be subclasses of BzrDirFormat
879
Once a format is deprecated, just deprecate the initialize and open
880
methods on the format class. Do not deprecate the object, as the
881
object will be created every system load.
884
_default_format = None
885
"""The default format used for new .bzr dirs."""
888
"""The known formats."""
890
_lock_file_name = 'branch-lock'
892
# _lock_class must be set in subclasses to the lock type, typ.
893
# TransportLock or LockDir
896
def find_format(klass, transport):
897
"""Return the format registered for URL."""
899
format_string = transport.get(".bzr/branch-format").read()
900
return klass._formats[format_string]
901
except errors.NoSuchFile:
902
raise errors.NotBranchError(path=transport.base)
904
raise errors.UnknownFormatError(format_string)
907
def get_default_format(klass):
908
"""Return the current default format."""
909
return klass._default_format
911
def get_format_string(self):
912
"""Return the ASCII format string that identifies this format."""
913
raise NotImplementedError(self.get_format_string)
915
def get_format_description(self):
916
"""Return the short description for this format."""
917
raise NotImplementedError(self.get_format_description)
919
def get_converter(self, format=None):
920
"""Return the converter to use to convert bzrdirs needing converts.
922
This returns a bzrlib.bzrdir.Converter object.
924
This should return the best upgrader to step this format towards the
925
current default format. In the case of plugins we can/shouold provide
926
some means for them to extend the range of returnable converters.
928
:param format: Optional format to override the default foramt of the
931
raise NotImplementedError(self.get_converter)
933
def initialize(self, url):
934
"""Create a bzr control dir at this url and return an opened copy.
936
Subclasses should typically override initialize_on_transport
937
instead of this method.
939
return self.initialize_on_transport(get_transport(url))
941
def initialize_on_transport(self, transport):
942
"""Initialize a new bzrdir in the base directory of a Transport."""
943
# Since we don'transport have a .bzr directory, inherit the
944
# mode from the root directory
945
temp_control = LockableFiles(transport, '', TransportLock)
946
temp_control._transport.mkdir('.bzr',
947
# FIXME: RBC 20060121 dont peek under
949
mode=temp_control._dir_mode)
950
file_mode = temp_control._file_mode
952
mutter('created control directory in ' + transport.base)
953
control = transport.clone('.bzr')
954
utf8_files = [('README',
955
"This is a Bazaar-NG control directory.\n"
956
"Do not change any files in this directory.\n"),
957
('branch-format', self.get_format_string()),
959
# NB: no need to escape relative paths that are url safe.
960
control_files = LockableFiles(control, self._lock_file_name,
962
control_files.create_lock()
963
control_files.lock_write()
965
for file, content in utf8_files:
966
control_files.put_utf8(file, content)
968
control_files.unlock()
969
return self.open(transport, _found=True)
971
def is_supported(self):
972
"""Is this format supported?
974
Supported formats must be initializable and openable.
975
Unsupported formats may not support initialization or committing or
976
some other features depending on the reason for not being supported.
980
def open(self, transport, _found=False):
981
"""Return an instance of this format for the dir transport points at.
983
_found is a private parameter, do not use it.
986
assert isinstance(BzrDirFormat.find_format(transport),
988
return self._open(transport)
990
def _open(self, transport):
991
"""Template method helper for opening BzrDirectories.
993
This performs the actual open and any additional logic or parameter
996
raise NotImplementedError(self._open)
999
def register_format(klass, format):
1000
klass._formats[format.get_format_string()] = format
1003
def set_default_format(klass, format):
1004
klass._default_format = format
1007
return self.get_format_string()[:-1]
1010
def unregister_format(klass, format):
1011
assert klass._formats[format.get_format_string()] is format
1012
del klass._formats[format.get_format_string()]
1015
class BzrDirFormat4(BzrDirFormat):
1016
"""Bzr dir format 4.
1018
This format is a combined format for working tree, branch and repository.
1020
- Format 1 working trees [always]
1021
- Format 4 branches [always]
1022
- Format 4 repositories [always]
1024
This format is deprecated: it indexes texts using a text it which is
1025
removed in format 5; write support for this format has been removed.
1028
_lock_class = TransportLock
1030
def get_format_string(self):
1031
"""See BzrDirFormat.get_format_string()."""
1032
return "Bazaar-NG branch, format 0.0.4\n"
1034
def get_format_description(self):
1035
"""See BzrDirFormat.get_format_description()."""
1036
return "All-in-one format 4"
1038
def get_converter(self, format=None):
1039
"""See BzrDirFormat.get_converter()."""
1040
# there is one and only one upgrade path here.
1041
return ConvertBzrDir4To5()
1043
def initialize_on_transport(self, transport):
1044
"""Format 4 branches cannot be created."""
1045
raise errors.UninitializableFormat(self)
1047
def is_supported(self):
1048
"""Format 4 is not supported.
1050
It is not supported because the model changed from 4 to 5 and the
1051
conversion logic is expensive - so doing it on the fly was not
1056
def _open(self, transport):
1057
"""See BzrDirFormat._open."""
1058
return BzrDir4(transport, self)
1060
def __return_repository_format(self):
1061
"""Circular import protection."""
1062
from bzrlib.repository import RepositoryFormat4
1063
return RepositoryFormat4(self)
1064
repository_format = property(__return_repository_format)
1067
class BzrDirFormat5(BzrDirFormat):
1068
"""Bzr control format 5.
1070
This format is a combined format for working tree, branch and repository.
1072
- Format 2 working trees [always]
1073
- Format 4 branches [always]
1074
- Format 5 repositories [always]
1075
Unhashed stores in the repository.
1078
_lock_class = TransportLock
1080
def get_format_string(self):
1081
"""See BzrDirFormat.get_format_string()."""
1082
return "Bazaar-NG branch, format 5\n"
1084
def get_format_description(self):
1085
"""See BzrDirFormat.get_format_description()."""
1086
return "All-in-one format 5"
1088
def get_converter(self, format=None):
1089
"""See BzrDirFormat.get_converter()."""
1090
# there is one and only one upgrade path here.
1091
return ConvertBzrDir5To6()
1093
def _initialize_for_clone(self, url):
1094
return self.initialize_on_transport(get_transport(url), _cloning=True)
1096
def initialize_on_transport(self, transport, _cloning=False):
1097
"""Format 5 dirs always have working tree, branch and repository.
1099
Except when they are being cloned.
1101
from bzrlib.branch import BzrBranchFormat4
1102
from bzrlib.repository import RepositoryFormat5
1103
from bzrlib.workingtree import WorkingTreeFormat2
1104
result = (super(BzrDirFormat5, self).initialize_on_transport(transport))
1105
RepositoryFormat5().initialize(result, _internal=True)
1107
BzrBranchFormat4().initialize(result)
1108
WorkingTreeFormat2().initialize(result)
1111
def _open(self, transport):
1112
"""See BzrDirFormat._open."""
1113
return BzrDir5(transport, self)
1115
def __return_repository_format(self):
1116
"""Circular import protection."""
1117
from bzrlib.repository import RepositoryFormat5
1118
return RepositoryFormat5(self)
1119
repository_format = property(__return_repository_format)
1122
class BzrDirFormat6(BzrDirFormat):
1123
"""Bzr control format 6.
1125
This format is a combined format for working tree, branch and repository.
1127
- Format 2 working trees [always]
1128
- Format 4 branches [always]
1129
- Format 6 repositories [always]
1132
_lock_class = TransportLock
1134
def get_format_string(self):
1135
"""See BzrDirFormat.get_format_string()."""
1136
return "Bazaar-NG branch, format 6\n"
1138
def get_format_description(self):
1139
"""See BzrDirFormat.get_format_description()."""
1140
return "All-in-one format 6"
1142
def get_converter(self, format=None):
1143
"""See BzrDirFormat.get_converter()."""
1144
# there is one and only one upgrade path here.
1145
return ConvertBzrDir6ToMeta()
1147
def _initialize_for_clone(self, url):
1148
return self.initialize_on_transport(get_transport(url), _cloning=True)
1150
def initialize_on_transport(self, transport, _cloning=False):
1151
"""Format 6 dirs always have working tree, branch and repository.
1153
Except when they are being cloned.
1155
from bzrlib.branch import BzrBranchFormat4
1156
from bzrlib.repository import RepositoryFormat6
1157
from bzrlib.workingtree import WorkingTreeFormat2
1158
result = super(BzrDirFormat6, self).initialize_on_transport(transport)
1159
RepositoryFormat6().initialize(result, _internal=True)
1161
BzrBranchFormat4().initialize(result)
1163
WorkingTreeFormat2().initialize(result)
1164
except errors.NotLocalUrl:
1165
# emulate pre-check behaviour for working tree and silently
1170
def _open(self, transport):
1171
"""See BzrDirFormat._open."""
1172
return BzrDir6(transport, self)
1174
def __return_repository_format(self):
1175
"""Circular import protection."""
1176
from bzrlib.repository import RepositoryFormat6
1177
return RepositoryFormat6(self)
1178
repository_format = property(__return_repository_format)
1181
class BzrDirMetaFormat1(BzrDirFormat):
1182
"""Bzr meta control format 1
1184
This is the first format with split out working tree, branch and repository
1187
- Format 3 working trees [optional]
1188
- Format 5 branches [optional]
1189
- Format 7 repositories [optional]
1192
_lock_class = LockDir
1194
def get_converter(self, format=None):
1195
"""See BzrDirFormat.get_converter()."""
1197
format = BzrDirFormat.get_default_format()
1198
if not isinstance(self, format.__class__):
1199
# converting away from metadir is not implemented
1200
raise NotImplementedError(self.get_converter)
1201
return ConvertMetaToMeta(format)
1203
def get_format_string(self):
1204
"""See BzrDirFormat.get_format_string()."""
1205
return "Bazaar-NG meta directory, format 1\n"
1207
def get_format_description(self):
1208
"""See BzrDirFormat.get_format_description()."""
1209
return "Meta directory format 1"
1211
def _open(self, transport):
1212
"""See BzrDirFormat._open."""
1213
return BzrDirMeta1(transport, self)
1215
def __return_repository_format(self):
1216
"""Circular import protection."""
1217
if getattr(self, '_repository_format', None):
1218
return self._repository_format
1219
from bzrlib.repository import RepositoryFormat
1220
return RepositoryFormat.get_default_format()
1222
def __set_repository_format(self, value):
1223
"""Allow changint the repository format for metadir formats."""
1224
self._repository_format = value
1226
repository_format = property(__return_repository_format, __set_repository_format)
1229
BzrDirFormat.register_format(BzrDirFormat4())
1230
BzrDirFormat.register_format(BzrDirFormat5())
1231
BzrDirFormat.register_format(BzrDirFormat6())
1232
__default_format = BzrDirMetaFormat1()
1233
BzrDirFormat.register_format(__default_format)
1234
BzrDirFormat.set_default_format(__default_format)
1237
class BzrDirTestProviderAdapter(object):
1238
"""A tool to generate a suite testing multiple bzrdir formats at once.
1240
This is done by copying the test once for each transport and injecting
1241
the transport_server, transport_readonly_server, and bzrdir_format
1242
classes into each copy. Each copy is also given a new id() to make it
1246
def __init__(self, transport_server, transport_readonly_server, formats):
1247
self._transport_server = transport_server
1248
self._transport_readonly_server = transport_readonly_server
1249
self._formats = formats
1251
def adapt(self, test):
1252
result = TestSuite()
1253
for format in self._formats:
1254
new_test = deepcopy(test)
1255
new_test.transport_server = self._transport_server
1256
new_test.transport_readonly_server = self._transport_readonly_server
1257
new_test.bzrdir_format = format
1258
def make_new_test_id():
1259
new_id = "%s(%s)" % (new_test.id(), format.__class__.__name__)
1260
return lambda: new_id
1261
new_test.id = make_new_test_id()
1262
result.addTest(new_test)
1266
class ScratchDir(BzrDir6):
1267
"""Special test class: a bzrdir that cleans up itself..
1269
>>> d = ScratchDir()
1270
>>> base = d.transport.base
1273
>>> b.transport.__del__()
1278
def __init__(self, files=[], dirs=[], transport=None):
1279
"""Make a test branch.
1281
This creates a temporary directory and runs init-tree in it.
1283
If any files are listed, they are created in the working copy.
1285
if transport is None:
1286
transport = bzrlib.transport.local.ScratchTransport()
1287
# local import for scope restriction
1288
BzrDirFormat6().initialize(transport.base)
1289
super(ScratchDir, self).__init__(transport, BzrDirFormat6())
1290
self.create_repository()
1291
self.create_branch()
1292
self.create_workingtree()
1294
super(ScratchDir, self).__init__(transport, BzrDirFormat6())
1296
# BzrBranch creates a clone to .bzr and then forgets about the
1297
# original transport. A ScratchTransport() deletes itself and
1298
# everything underneath it when it goes away, so we need to
1299
# grab a local copy to prevent that from happening
1300
self._transport = transport
1303
self._transport.mkdir(d)
1306
self._transport.put(f, 'content of %s' % f)
1310
>>> orig = ScratchDir(files=["file1", "file2"])
1311
>>> os.listdir(orig.base)
1312
[u'.bzr', u'file1', u'file2']
1313
>>> clone = orig.clone()
1314
>>> if os.name != 'nt':
1315
... os.path.samefile(orig.base, clone.base)
1317
... orig.base == clone.base
1320
>>> os.listdir(clone.base)
1321
[u'.bzr', u'file1', u'file2']
1323
from shutil import copytree
1324
from bzrlib.osutils import mkdtemp
1327
copytree(self.base, base, symlinks=True)
1329
transport=bzrlib.transport.local.ScratchTransport(base))
1332
class Converter(object):
1333
"""Converts a disk format object from one format to another."""
1335
def convert(self, to_convert, pb):
1336
"""Perform the conversion of to_convert, giving feedback via pb.
1338
:param to_convert: The disk object to convert.
1339
:param pb: a progress bar to use for progress information.
1342
def step(self, message):
1343
"""Update the pb by a step."""
1345
self.pb.update(message, self.count, self.total)
1348
class ConvertBzrDir4To5(Converter):
1349
"""Converts format 4 bzr dirs to format 5."""
1352
super(ConvertBzrDir4To5, self).__init__()
1353
self.converted_revs = set()
1354
self.absent_revisions = set()
1358
def convert(self, to_convert, pb):
1359
"""See Converter.convert()."""
1360
self.bzrdir = to_convert
1362
self.pb.note('starting upgrade from format 4 to 5')
1363
if isinstance(self.bzrdir.transport, LocalTransport):
1364
self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
1365
self._convert_to_weaves()
1366
return BzrDir.open(self.bzrdir.root_transport.base)
1368
def _convert_to_weaves(self):
1369
self.pb.note('note: upgrade may be faster if all store files are ungzipped first')
1372
stat = self.bzrdir.transport.stat('weaves')
1373
if not S_ISDIR(stat.st_mode):
1374
self.bzrdir.transport.delete('weaves')
1375
self.bzrdir.transport.mkdir('weaves')
1376
except errors.NoSuchFile:
1377
self.bzrdir.transport.mkdir('weaves')
1378
# deliberately not a WeaveFile as we want to build it up slowly.
1379
self.inv_weave = Weave('inventory')
1380
# holds in-memory weaves for all files
1381
self.text_weaves = {}
1382
self.bzrdir.transport.delete('branch-format')
1383
self.branch = self.bzrdir.open_branch()
1384
self._convert_working_inv()
1385
rev_history = self.branch.revision_history()
1386
# to_read is a stack holding the revisions we still need to process;
1387
# appending to it adds new highest-priority revisions
1388
self.known_revisions = set(rev_history)
1389
self.to_read = rev_history[-1:]
1391
rev_id = self.to_read.pop()
1392
if (rev_id not in self.revisions
1393
and rev_id not in self.absent_revisions):
1394
self._load_one_rev(rev_id)
1396
to_import = self._make_order()
1397
for i, rev_id in enumerate(to_import):
1398
self.pb.update('converting revision', i, len(to_import))
1399
self._convert_one_rev(rev_id)
1401
self._write_all_weaves()
1402
self._write_all_revs()
1403
self.pb.note('upgraded to weaves:')
1404
self.pb.note(' %6d revisions and inventories', len(self.revisions))
1405
self.pb.note(' %6d revisions not present', len(self.absent_revisions))
1406
self.pb.note(' %6d texts', self.text_count)
1407
self._cleanup_spare_files_after_format4()
1408
self.branch.control_files.put_utf8('branch-format', BzrDirFormat5().get_format_string())
1410
def _cleanup_spare_files_after_format4(self):
1411
# FIXME working tree upgrade foo.
1412
for n in 'merged-patches', 'pending-merged-patches':
1414
## assert os.path.getsize(p) == 0
1415
self.bzrdir.transport.delete(n)
1416
except errors.NoSuchFile:
1418
self.bzrdir.transport.delete_tree('inventory-store')
1419
self.bzrdir.transport.delete_tree('text-store')
1421
def _convert_working_inv(self):
1422
inv = serializer_v4.read_inventory(self.branch.control_files.get('inventory'))
1423
new_inv_xml = serializer_v5.write_inventory_to_string(inv)
1424
# FIXME inventory is a working tree change.
1425
self.branch.control_files.put('inventory', new_inv_xml)
1427
def _write_all_weaves(self):
1428
controlweaves = WeaveStore(self.bzrdir.transport, prefixed=False)
1429
weave_transport = self.bzrdir.transport.clone('weaves')
1430
weaves = WeaveStore(weave_transport, prefixed=False)
1431
transaction = WriteTransaction()
1435
for file_id, file_weave in self.text_weaves.items():
1436
self.pb.update('writing weave', i, len(self.text_weaves))
1437
weaves._put_weave(file_id, file_weave, transaction)
1439
self.pb.update('inventory', 0, 1)
1440
controlweaves._put_weave('inventory', self.inv_weave, transaction)
1441
self.pb.update('inventory', 1, 1)
1445
def _write_all_revs(self):
1446
"""Write all revisions out in new form."""
1447
self.bzrdir.transport.delete_tree('revision-store')
1448
self.bzrdir.transport.mkdir('revision-store')
1449
revision_transport = self.bzrdir.transport.clone('revision-store')
1451
_revision_store = TextRevisionStore(TextStore(revision_transport,
1455
transaction = bzrlib.transactions.WriteTransaction()
1456
for i, rev_id in enumerate(self.converted_revs):
1457
self.pb.update('write revision', i, len(self.converted_revs))
1458
_revision_store.add_revision(self.revisions[rev_id], transaction)
1462
def _load_one_rev(self, rev_id):
1463
"""Load a revision object into memory.
1465
Any parents not either loaded or abandoned get queued to be
1467
self.pb.update('loading revision',
1468
len(self.revisions),
1469
len(self.known_revisions))
1470
if not self.branch.repository.has_revision(rev_id):
1472
self.pb.note('revision {%s} not present in branch; '
1473
'will be converted as a ghost',
1475
self.absent_revisions.add(rev_id)
1477
rev = self.branch.repository._revision_store.get_revision(rev_id,
1478
self.branch.repository.get_transaction())
1479
for parent_id in rev.parent_ids:
1480
self.known_revisions.add(parent_id)
1481
self.to_read.append(parent_id)
1482
self.revisions[rev_id] = rev
1484
def _load_old_inventory(self, rev_id):
1485
assert rev_id not in self.converted_revs
1486
old_inv_xml = self.branch.repository.inventory_store.get(rev_id).read()
1487
inv = serializer_v4.read_inventory_from_string(old_inv_xml)
1488
rev = self.revisions[rev_id]
1489
if rev.inventory_sha1:
1490
assert rev.inventory_sha1 == sha_string(old_inv_xml), \
1491
'inventory sha mismatch for {%s}' % rev_id
1494
def _load_updated_inventory(self, rev_id):
1495
assert rev_id in self.converted_revs
1496
inv_xml = self.inv_weave.get_text(rev_id)
1497
inv = serializer_v5.read_inventory_from_string(inv_xml)
1500
def _convert_one_rev(self, rev_id):
1501
"""Convert revision and all referenced objects to new format."""
1502
rev = self.revisions[rev_id]
1503
inv = self._load_old_inventory(rev_id)
1504
present_parents = [p for p in rev.parent_ids
1505
if p not in self.absent_revisions]
1506
self._convert_revision_contents(rev, inv, present_parents)
1507
self._store_new_weave(rev, inv, present_parents)
1508
self.converted_revs.add(rev_id)
1510
def _store_new_weave(self, rev, inv, present_parents):
1511
# the XML is now updated with text versions
1515
if ie.kind == 'root_directory':
1517
assert hasattr(ie, 'revision'), \
1518
'no revision on {%s} in {%s}' % \
1519
(file_id, rev.revision_id)
1520
new_inv_xml = serializer_v5.write_inventory_to_string(inv)
1521
new_inv_sha1 = sha_string(new_inv_xml)
1522
self.inv_weave.add_lines(rev.revision_id,
1524
new_inv_xml.splitlines(True))
1525
rev.inventory_sha1 = new_inv_sha1
1527
def _convert_revision_contents(self, rev, inv, present_parents):
1528
"""Convert all the files within a revision.
1530
Also upgrade the inventory to refer to the text revision ids."""
1531
rev_id = rev.revision_id
1532
mutter('converting texts of revision {%s}',
1534
parent_invs = map(self._load_updated_inventory, present_parents)
1537
self._convert_file_version(rev, ie, parent_invs)
1539
def _convert_file_version(self, rev, ie, parent_invs):
1540
"""Convert one version of one file.
1542
The file needs to be added into the weave if it is a merge
1543
of >=2 parents or if it's changed from its parent.
1545
if ie.kind == 'root_directory':
1547
file_id = ie.file_id
1548
rev_id = rev.revision_id
1549
w = self.text_weaves.get(file_id)
1552
self.text_weaves[file_id] = w
1553
text_changed = False
1554
previous_entries = ie.find_previous_heads(parent_invs,
1558
for old_revision in previous_entries:
1559
# if this fails, its a ghost ?
1560
assert old_revision in self.converted_revs
1561
self.snapshot_ie(previous_entries, ie, w, rev_id)
1563
assert getattr(ie, 'revision', None) is not None
1565
def snapshot_ie(self, previous_revisions, ie, w, rev_id):
1566
# TODO: convert this logic, which is ~= snapshot to
1567
# a call to:. This needs the path figured out. rather than a work_tree
1568
# a v4 revision_tree can be given, or something that looks enough like
1569
# one to give the file content to the entry if it needs it.
1570
# and we need something that looks like a weave store for snapshot to
1572
#ie.snapshot(rev, PATH, previous_revisions, REVISION_TREE, InMemoryWeaveStore(self.text_weaves))
1573
if len(previous_revisions) == 1:
1574
previous_ie = previous_revisions.values()[0]
1575
if ie._unchanged(previous_ie):
1576
ie.revision = previous_ie.revision
1579
text = self.branch.repository.text_store.get(ie.text_id)
1580
file_lines = text.readlines()
1581
assert sha_strings(file_lines) == ie.text_sha1
1582
assert sum(map(len, file_lines)) == ie.text_size
1583
w.add_lines(rev_id, previous_revisions, file_lines)
1584
self.text_count += 1
1586
w.add_lines(rev_id, previous_revisions, [])
1587
ie.revision = rev_id
1589
def _make_order(self):
1590
"""Return a suitable order for importing revisions.
1592
The order must be such that an revision is imported after all
1593
its (present) parents.
1595
todo = set(self.revisions.keys())
1596
done = self.absent_revisions.copy()
1599
# scan through looking for a revision whose parents
1601
for rev_id in sorted(list(todo)):
1602
rev = self.revisions[rev_id]
1603
parent_ids = set(rev.parent_ids)
1604
if parent_ids.issubset(done):
1605
# can take this one now
1606
order.append(rev_id)
1612
class ConvertBzrDir5To6(Converter):
1613
"""Converts format 5 bzr dirs to format 6."""
1615
def convert(self, to_convert, pb):
1616
"""See Converter.convert()."""
1617
self.bzrdir = to_convert
1619
self.pb.note('starting upgrade from format 5 to 6')
1620
self._convert_to_prefixed()
1621
return BzrDir.open(self.bzrdir.root_transport.base)
1623
def _convert_to_prefixed(self):
1624
from bzrlib.store import TransportStore
1625
self.bzrdir.transport.delete('branch-format')
1626
for store_name in ["weaves", "revision-store"]:
1627
self.pb.note("adding prefixes to %s" % store_name)
1628
store_transport = self.bzrdir.transport.clone(store_name)
1629
store = TransportStore(store_transport, prefixed=True)
1630
for urlfilename in store_transport.list_dir('.'):
1631
filename = urlutils.unescape(urlfilename)
1632
if (filename.endswith(".weave") or
1633
filename.endswith(".gz") or
1634
filename.endswith(".sig")):
1635
file_id = os.path.splitext(filename)[0]
1638
prefix_dir = store.hash_prefix(file_id)
1639
# FIXME keep track of the dirs made RBC 20060121
1641
store_transport.move(filename, prefix_dir + '/' + filename)
1642
except errors.NoSuchFile: # catches missing dirs strangely enough
1643
store_transport.mkdir(prefix_dir)
1644
store_transport.move(filename, prefix_dir + '/' + filename)
1645
self.bzrdir._control_files.put_utf8('branch-format', BzrDirFormat6().get_format_string())
1648
class ConvertBzrDir6ToMeta(Converter):
1649
"""Converts format 6 bzr dirs to metadirs."""
1651
def convert(self, to_convert, pb):
1652
"""See Converter.convert()."""
1653
self.bzrdir = to_convert
1656
self.total = 20 # the steps we know about
1657
self.garbage_inventories = []
1659
self.pb.note('starting upgrade from format 6 to metadir')
1660
self.bzrdir._control_files.put_utf8('branch-format', "Converting to format 6")
1661
# its faster to move specific files around than to open and use the apis...
1662
# first off, nuke ancestry.weave, it was never used.
1664
self.step('Removing ancestry.weave')
1665
self.bzrdir.transport.delete('ancestry.weave')
1666
except errors.NoSuchFile:
1668
# find out whats there
1669
self.step('Finding branch files')
1670
last_revision = self.bzrdir.open_branch().last_revision()
1671
bzrcontents = self.bzrdir.transport.list_dir('.')
1672
for name in bzrcontents:
1673
if name.startswith('basis-inventory.'):
1674
self.garbage_inventories.append(name)
1675
# create new directories for repository, working tree and branch
1676
self.dir_mode = self.bzrdir._control_files._dir_mode
1677
self.file_mode = self.bzrdir._control_files._file_mode
1678
repository_names = [('inventory.weave', True),
1679
('revision-store', True),
1681
self.step('Upgrading repository ')
1682
self.bzrdir.transport.mkdir('repository', mode=self.dir_mode)
1683
self.make_lock('repository')
1684
# we hard code the formats here because we are converting into
1685
# the meta format. The meta format upgrader can take this to a
1686
# future format within each component.
1687
self.put_format('repository', bzrlib.repository.RepositoryFormat7())
1688
for entry in repository_names:
1689
self.move_entry('repository', entry)
1691
self.step('Upgrading branch ')
1692
self.bzrdir.transport.mkdir('branch', mode=self.dir_mode)
1693
self.make_lock('branch')
1694
self.put_format('branch', bzrlib.branch.BzrBranchFormat5())
1695
branch_files = [('revision-history', True),
1696
('branch-name', True),
1698
for entry in branch_files:
1699
self.move_entry('branch', entry)
1701
self.step('Upgrading working tree')
1702
self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
1703
self.make_lock('checkout')
1704
self.put_format('checkout', bzrlib.workingtree.WorkingTreeFormat3())
1705
self.bzrdir.transport.delete_multi(self.garbage_inventories, self.pb)
1706
checkout_files = [('pending-merges', True),
1707
('inventory', True),
1708
('stat-cache', False)]
1709
for entry in checkout_files:
1710
self.move_entry('checkout', entry)
1711
if last_revision is not None:
1712
self.bzrdir._control_files.put_utf8('checkout/last-revision',
1714
self.bzrdir._control_files.put_utf8('branch-format', BzrDirMetaFormat1().get_format_string())
1715
return BzrDir.open(self.bzrdir.root_transport.base)
1717
def make_lock(self, name):
1718
"""Make a lock for the new control dir name."""
1719
self.step('Make %s lock' % name)
1720
ld = LockDir(self.bzrdir.transport,
1722
file_modebits=self.file_mode,
1723
dir_modebits=self.dir_mode)
1726
def move_entry(self, new_dir, entry):
1727
"""Move then entry name into new_dir."""
1729
mandatory = entry[1]
1730
self.step('Moving %s' % name)
1732
self.bzrdir.transport.move(name, '%s/%s' % (new_dir, name))
1733
except errors.NoSuchFile:
1737
def put_format(self, dirname, format):
1738
self.bzrdir._control_files.put_utf8('%s/format' % dirname, format.get_format_string())
1741
class ConvertMetaToMeta(Converter):
1742
"""Converts the components of metadirs."""
1744
def __init__(self, target_format):
1745
"""Create a metadir to metadir converter.
1747
:param target_format: The final metadir format that is desired.
1749
self.target_format = target_format
1751
def convert(self, to_convert, pb):
1752
"""See Converter.convert()."""
1753
self.bzrdir = to_convert
1757
self.step('checking repository format')
1759
repo = self.bzrdir.open_repository()
1760
except errors.NoRepositoryPresent:
1763
if not isinstance(repo._format, self.target_format.repository_format.__class__):
1764
from bzrlib.repository import CopyConverter
1765
self.pb.note('starting repository conversion')
1766
converter = CopyConverter(self.target_format.repository_format)
1767
converter.convert(repo, pb)