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 cStringIO import StringIO
26
from bzrlib.lazy_import import lazy_import
27
lazy_import(globals(), """
28
from copy import deepcopy
29
from stat import S_ISDIR
37
revision as _mod_revision,
42
from bzrlib.osutils import (
47
from bzrlib.store.revision.text import TextRevisionStore
48
from bzrlib.store.text import TextStore
49
from bzrlib.store.versioned import WeaveStore
50
from bzrlib.transactions import WriteTransaction
51
from bzrlib.transport import get_transport
52
from bzrlib.weave import Weave
55
from bzrlib.trace import mutter
56
from bzrlib.transport.local import LocalTransport
60
"""A .bzr control diretory.
62
BzrDir instances let you create or open any of the things that can be
63
found within .bzr - checkouts, branches and repositories.
66
the transport which this bzr dir is rooted at (i.e. file:///.../.bzr/)
68
a transport connected to the directory this bzr was opened from.
72
"""Invoke break_lock on the first object in the bzrdir.
74
If there is a tree, the tree is opened and break_lock() called.
75
Otherwise, branch is tried, and finally repository.
78
thing_to_unlock = self.open_workingtree()
79
except (errors.NotLocalUrl, errors.NoWorkingTree):
81
thing_to_unlock = self.open_branch()
82
except errors.NotBranchError:
84
thing_to_unlock = self.open_repository()
85
except errors.NoRepositoryPresent:
87
thing_to_unlock.break_lock()
89
def can_convert_format(self):
90
"""Return true if this bzrdir is one whose format we can convert from."""
94
def _check_supported(format, allow_unsupported):
95
"""Check whether format is a supported format.
97
If allow_unsupported is True, this is a no-op.
99
if not allow_unsupported and not format.is_supported():
100
# see open_downlevel to open legacy branches.
101
raise errors.UnsupportedFormatError(format=format)
103
def clone(self, url, revision_id=None, basis=None, force_new_repo=False):
104
"""Clone this bzrdir and its contents to url verbatim.
106
If urls last component does not exist, it will be created.
108
if revision_id is not None, then the clone operation may tune
109
itself to download less data.
110
:param force_new_repo: Do not use a shared repository for the target
111
even if one is available.
114
basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
115
result = self._format.initialize(url)
117
local_repo = self.find_repository()
118
except errors.NoRepositoryPresent:
121
# may need to copy content in
123
result_repo = local_repo.clone(
125
revision_id=revision_id,
127
result_repo.set_make_working_trees(local_repo.make_working_trees())
130
result_repo = result.find_repository()
131
# fetch content this dir needs.
133
# XXX FIXME RBC 20060214 need tests for this when the basis
135
result_repo.fetch(basis_repo, revision_id=revision_id)
136
result_repo.fetch(local_repo, revision_id=revision_id)
137
except errors.NoRepositoryPresent:
138
# needed to make one anyway.
139
result_repo = local_repo.clone(
141
revision_id=revision_id,
143
result_repo.set_make_working_trees(local_repo.make_working_trees())
144
# 1 if there is a branch present
145
# make sure its content is available in the target repository
148
self.open_branch().clone(result, revision_id=revision_id)
149
except errors.NotBranchError:
152
self.open_workingtree().clone(result, basis=basis_tree)
153
except (errors.NoWorkingTree, errors.NotLocalUrl):
157
def _get_basis_components(self, basis):
158
"""Retrieve the basis components that are available at basis."""
160
return None, None, None
162
basis_tree = basis.open_workingtree()
163
basis_branch = basis_tree.branch
164
basis_repo = basis_branch.repository
165
except (errors.NoWorkingTree, errors.NotLocalUrl):
168
basis_branch = basis.open_branch()
169
basis_repo = basis_branch.repository
170
except errors.NotBranchError:
173
basis_repo = basis.open_repository()
174
except errors.NoRepositoryPresent:
176
return basis_repo, basis_branch, basis_tree
178
# TODO: This should be given a Transport, and should chdir up; otherwise
179
# this will open a new connection.
180
def _make_tail(self, url):
181
head, tail = urlutils.split(url)
182
if tail and tail != '.':
183
t = get_transport(head)
186
except errors.FileExists:
189
# TODO: Should take a Transport
191
def create(cls, base):
192
"""Create a new BzrDir at the url 'base'.
194
This will call the current default formats initialize with base
195
as the only parameter.
197
If you need a specific format, consider creating an instance
198
of that and calling initialize().
200
if cls is not BzrDir:
201
raise AssertionError("BzrDir.create always creates the default format, "
202
"not one of %r" % cls)
203
head, tail = urlutils.split(base)
204
if tail and tail != '.':
205
t = get_transport(head)
208
except errors.FileExists:
210
return BzrDirFormat.get_default_format().initialize(safe_unicode(base))
212
def create_branch(self):
213
"""Create a branch in this BzrDir.
215
The bzrdirs format will control what branch format is created.
216
For more control see BranchFormatXX.create(a_bzrdir).
218
raise NotImplementedError(self.create_branch)
221
def create_branch_and_repo(base, force_new_repo=False):
222
"""Create a new BzrDir, Branch and Repository at the url 'base'.
224
This will use the current default BzrDirFormat, and use whatever
225
repository format that that uses via bzrdir.create_branch and
226
create_repository. If a shared repository is available that is used
229
The created Branch object is returned.
231
:param base: The URL to create the branch at.
232
:param force_new_repo: If True a new repository is always created.
234
bzrdir = BzrDir.create(base)
235
bzrdir._find_or_create_repository(force_new_repo)
236
return bzrdir.create_branch()
238
def _find_or_create_repository(self, force_new_repo):
239
"""Create a new repository if needed, returning the repository."""
241
return self.create_repository()
243
return self.find_repository()
244
except errors.NoRepositoryPresent:
245
return self.create_repository()
248
def create_branch_convenience(base, force_new_repo=False,
249
force_new_tree=None, format=None):
250
"""Create a new BzrDir, Branch and Repository at the url 'base'.
252
This is a convenience function - it will use an existing repository
253
if possible, can be told explicitly whether to create a working tree or
256
This will use the current default BzrDirFormat, and use whatever
257
repository format that that uses via bzrdir.create_branch and
258
create_repository. If a shared repository is available that is used
259
preferentially. Whatever repository is used, its tree creation policy
262
The created Branch object is returned.
263
If a working tree cannot be made due to base not being a file:// url,
264
no error is raised unless force_new_tree is True, in which case no
265
data is created on disk and NotLocalUrl is raised.
267
:param base: The URL to create the branch at.
268
:param force_new_repo: If True a new repository is always created.
269
:param force_new_tree: If True or False force creation of a tree or
270
prevent such creation respectively.
271
:param format: Override for the for the bzrdir format to create
274
# check for non local urls
275
t = get_transport(safe_unicode(base))
276
if not isinstance(t, LocalTransport):
277
raise errors.NotLocalUrl(base)
279
bzrdir = BzrDir.create(base)
281
bzrdir = format.initialize(base)
282
repo = bzrdir._find_or_create_repository(force_new_repo)
283
result = bzrdir.create_branch()
284
if force_new_tree or (repo.make_working_trees() and
285
force_new_tree is None):
287
bzrdir.create_workingtree()
288
except errors.NotLocalUrl:
293
def create_repository(base, shared=False):
294
"""Create a new BzrDir and Repository at the url 'base'.
296
This will use the current default BzrDirFormat, and use whatever
297
repository format that that uses for bzrdirformat.create_repository.
299
;param shared: Create a shared repository rather than a standalone
301
The Repository object is returned.
303
This must be overridden as an instance method in child classes, where
304
it should take no parameters and construct whatever repository format
305
that child class desires.
307
bzrdir = BzrDir.create(base)
308
return bzrdir.create_repository(shared)
311
def create_standalone_workingtree(base):
312
"""Create a new BzrDir, WorkingTree, Branch and Repository at 'base'.
314
'base' must be a local path or a file:// url.
316
This will use the current default BzrDirFormat, and use whatever
317
repository format that that uses for bzrdirformat.create_workingtree,
318
create_branch and create_repository.
320
The WorkingTree object is returned.
322
t = get_transport(safe_unicode(base))
323
if not isinstance(t, LocalTransport):
324
raise errors.NotLocalUrl(base)
325
bzrdir = BzrDir.create_branch_and_repo(safe_unicode(base),
326
force_new_repo=True).bzrdir
327
return bzrdir.create_workingtree()
329
def create_workingtree(self, revision_id=None):
330
"""Create a working tree at this BzrDir.
332
revision_id: create it as of this revision id.
334
raise NotImplementedError(self.create_workingtree)
336
def find_repository(self):
337
"""Find the repository that should be used for a_bzrdir.
339
This does not require a branch as we use it to find the repo for
340
new branches as well as to hook existing branches up to their
344
return self.open_repository()
345
except errors.NoRepositoryPresent:
347
next_transport = self.root_transport.clone('..')
349
# find the next containing bzrdir
351
found_bzrdir = BzrDir.open_containing_from_transport(
353
except errors.NotBranchError:
355
raise errors.NoRepositoryPresent(self)
356
# does it have a repository ?
358
repository = found_bzrdir.open_repository()
359
except errors.NoRepositoryPresent:
360
next_transport = found_bzrdir.root_transport.clone('..')
361
if (found_bzrdir.root_transport.base == next_transport.base):
362
# top of the file system
366
if ((found_bzrdir.root_transport.base ==
367
self.root_transport.base) or repository.is_shared()):
370
raise errors.NoRepositoryPresent(self)
371
raise errors.NoRepositoryPresent(self)
373
def get_branch_transport(self, branch_format):
374
"""Get the transport for use by branch format in this BzrDir.
376
Note that bzr dirs that do not support format strings will raise
377
IncompatibleFormat if the branch format they are given has
378
a format string, and vice versa.
380
If branch_format is None, the transport is returned with no
381
checking. if it is not None, then the returned transport is
382
guaranteed to point to an existing directory ready for use.
384
raise NotImplementedError(self.get_branch_transport)
386
def get_repository_transport(self, repository_format):
387
"""Get the transport for use by repository format in this BzrDir.
389
Note that bzr dirs that do not support format strings will raise
390
IncompatibleFormat if the repository format they are given has
391
a format string, and vice versa.
393
If repository_format is None, the transport is returned with no
394
checking. if it is not None, then the returned transport is
395
guaranteed to point to an existing directory ready for use.
397
raise NotImplementedError(self.get_repository_transport)
399
def get_workingtree_transport(self, tree_format):
400
"""Get the transport for use by workingtree format in this BzrDir.
402
Note that bzr dirs that do not support format strings will raise
403
IncompatibleFormat if the workingtree format they are given has
404
a format string, and vice versa.
406
If workingtree_format is None, the transport is returned with no
407
checking. if it is not None, then the returned transport is
408
guaranteed to point to an existing directory ready for use.
410
raise NotImplementedError(self.get_workingtree_transport)
412
def __init__(self, _transport, _format):
413
"""Initialize a Bzr control dir object.
415
Only really common logic should reside here, concrete classes should be
416
made with varying behaviours.
418
:param _format: the format that is creating this BzrDir instance.
419
:param _transport: the transport this dir is based at.
421
self._format = _format
422
self.transport = _transport.clone('.bzr')
423
self.root_transport = _transport
425
def is_control_filename(self, filename):
426
"""True if filename is the name of a path which is reserved for bzrdir's.
428
:param filename: A filename within the root transport of this bzrdir.
430
This is true IF and ONLY IF the filename is part of the namespace reserved
431
for bzr control dirs. Currently this is the '.bzr' directory in the root
432
of the root_transport. it is expected that plugins will need to extend
433
this in the future - for instance to make bzr talk with svn working
436
# this might be better on the BzrDirFormat class because it refers to
437
# all the possible bzrdir disk formats.
438
# This method is tested via the workingtree is_control_filename tests-
439
# it was extracted from WorkingTree.is_control_filename. If the methods
440
# contract is extended beyond the current trivial implementation please
441
# add new tests for it to the appropriate place.
442
return filename == '.bzr' or filename.startswith('.bzr/')
444
def needs_format_conversion(self, format=None):
445
"""Return true if this bzrdir needs convert_format run on it.
447
For instance, if the repository format is out of date but the
448
branch and working tree are not, this should return True.
450
:param format: Optional parameter indicating a specific desired
451
format we plan to arrive at.
453
raise NotImplementedError(self.needs_format_conversion)
456
def open_unsupported(base):
457
"""Open a branch which is not supported."""
458
return BzrDir.open(base, _unsupported=True)
461
def open(base, _unsupported=False):
462
"""Open an existing bzrdir, rooted at 'base' (url)
464
_unsupported is a private parameter to the BzrDir class.
466
t = get_transport(base)
467
# mutter("trying to open %r with transport %r", base, t)
468
format = BzrDirFormat.find_format(t)
469
BzrDir._check_supported(format, _unsupported)
470
return format.open(t, _found=True)
472
def open_branch(self, unsupported=False):
473
"""Open the branch object at this BzrDir if one is present.
475
If unsupported is True, then no longer supported branch formats can
478
TODO: static convenience version of this?
480
raise NotImplementedError(self.open_branch)
483
def open_containing(url):
484
"""Open an existing branch which contains url.
486
:param url: url to search from.
487
See open_containing_from_transport for more detail.
489
return BzrDir.open_containing_from_transport(get_transport(url))
492
def open_containing_from_transport(a_transport):
493
"""Open an existing branch which contains a_transport.base
495
This probes for a branch at a_transport, and searches upwards from there.
497
Basically we keep looking up until we find the control directory or
498
run into the root. If there isn't one, raises NotBranchError.
499
If there is one and it is either an unrecognised format or an unsupported
500
format, UnknownFormatError or UnsupportedFormatError are raised.
501
If there is one, it is returned, along with the unused portion of url.
503
:return: The BzrDir that contains the path, and a Unicode path
504
for the rest of the URL.
506
# this gets the normalised url back. I.e. '.' -> the full path.
507
url = a_transport.base
510
format = BzrDirFormat.find_format(a_transport)
511
BzrDir._check_supported(format, False)
512
return format.open(a_transport), urlutils.unescape(a_transport.relpath(url))
513
except errors.NotBranchError, e:
514
## mutter('not a branch in: %r %s', a_transport.base, e)
516
new_t = a_transport.clone('..')
517
if new_t.base == a_transport.base:
518
# reached the root, whatever that may be
519
raise errors.NotBranchError(path=url)
522
def open_repository(self, _unsupported=False):
523
"""Open the repository object at this BzrDir if one is present.
525
This will not follow the Branch object pointer - its strictly a direct
526
open facility. Most client code should use open_branch().repository to
529
_unsupported is a private parameter, not part of the api.
530
TODO: static convenience version of this?
532
raise NotImplementedError(self.open_repository)
534
def open_workingtree(self, _unsupported=False):
535
"""Open the workingtree object at this BzrDir if one is present.
537
TODO: static convenience version of this?
539
raise NotImplementedError(self.open_workingtree)
541
def has_branch(self):
542
"""Tell if this bzrdir contains a branch.
544
Note: if you're going to open the branch, you should just go ahead
545
and try, and not ask permission first. (This method just opens the
546
branch and discards it, and that's somewhat expensive.)
551
except errors.NotBranchError:
554
def has_workingtree(self):
555
"""Tell if this bzrdir contains a working tree.
557
This will still raise an exception if the bzrdir has a workingtree that
558
is remote & inaccessible.
560
Note: if you're going to open the working tree, you should just go ahead
561
and try, and not ask permission first. (This method just opens the
562
workingtree and discards it, and that's somewhat expensive.)
565
self.open_workingtree()
567
except errors.NoWorkingTree:
570
def sprout(self, url, revision_id=None, basis=None, force_new_repo=False):
571
"""Create a copy of this bzrdir prepared for use as a new line of
574
If urls last component does not exist, it will be created.
576
Attributes related to the identity of the source branch like
577
branch nickname will be cleaned, a working tree is created
578
whether one existed before or not; and a local branch is always
581
if revision_id is not None, then the clone operation may tune
582
itself to download less data.
585
result = self._format.initialize(url)
586
basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
588
source_branch = self.open_branch()
589
source_repository = source_branch.repository
590
except errors.NotBranchError:
593
source_repository = self.open_repository()
594
except errors.NoRepositoryPresent:
595
# copy the entire basis one if there is one
596
# but there is no repository.
597
source_repository = basis_repo
602
result_repo = result.find_repository()
603
except errors.NoRepositoryPresent:
605
if source_repository is None and result_repo is not None:
607
elif source_repository is None and result_repo is None:
608
# no repo available, make a new one
609
result.create_repository()
610
elif source_repository is not None and result_repo is None:
611
# have source, and want to make a new target repo
612
# we don't clone the repo because that preserves attributes
613
# like is_shared(), and we have not yet implemented a
614
# repository sprout().
615
result_repo = result.create_repository()
616
if result_repo is not None:
617
# fetch needed content into target.
619
# XXX FIXME RBC 20060214 need tests for this when the basis
621
result_repo.fetch(basis_repo, revision_id=revision_id)
622
if source_repository is not None:
623
result_repo.fetch(source_repository, revision_id=revision_id)
624
if source_branch is not None:
625
source_branch.sprout(result, revision_id=revision_id)
627
result.create_branch()
628
# TODO: jam 20060426 we probably need a test in here in the
629
# case that the newly sprouted branch is a remote one
630
if result_repo is None or result_repo.make_working_trees():
631
result.create_workingtree()
635
class BzrDirPreSplitOut(BzrDir):
636
"""A common class for the all-in-one formats."""
638
def __init__(self, _transport, _format):
639
"""See BzrDir.__init__."""
640
super(BzrDirPreSplitOut, self).__init__(_transport, _format)
641
assert self._format._lock_class == lockable_files.TransportLock
642
assert self._format._lock_file_name == 'branch-lock'
643
self._control_files = lockable_files.LockableFiles(
644
self.get_branch_transport(None),
645
self._format._lock_file_name,
646
self._format._lock_class)
648
def break_lock(self):
649
"""Pre-splitout bzrdirs do not suffer from stale locks."""
650
raise NotImplementedError(self.break_lock)
652
def clone(self, url, revision_id=None, basis=None, force_new_repo=False):
653
"""See BzrDir.clone()."""
654
from bzrlib.workingtree import WorkingTreeFormat2
656
result = self._format._initialize_for_clone(url)
657
basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
658
self.open_repository().clone(result, revision_id=revision_id, basis=basis_repo)
659
from_branch = self.open_branch()
660
from_branch.clone(result, revision_id=revision_id)
662
self.open_workingtree().clone(result, basis=basis_tree)
663
except errors.NotLocalUrl:
664
# make a new one, this format always has to have one.
666
WorkingTreeFormat2().initialize(result)
667
except errors.NotLocalUrl:
668
# but we cannot do it for remote trees.
669
to_branch = result.open_branch()
670
WorkingTreeFormat2().stub_initialize_remote(to_branch.control_files)
673
def create_branch(self):
674
"""See BzrDir.create_branch."""
675
return self.open_branch()
677
def create_repository(self, shared=False):
678
"""See BzrDir.create_repository."""
680
raise errors.IncompatibleFormat('shared repository', self._format)
681
return self.open_repository()
683
def create_workingtree(self, revision_id=None):
684
"""See BzrDir.create_workingtree."""
685
# this looks buggy but is not -really-
686
# clone and sprout will have set the revision_id
687
# and that will have set it for us, its only
688
# specific uses of create_workingtree in isolation
689
# that can do wonky stuff here, and that only
690
# happens for creating checkouts, which cannot be
691
# done on this format anyway. So - acceptable wart.
692
result = self.open_workingtree()
693
if revision_id is not None:
694
if revision_id == _mod_revision.NULL_REVISION:
695
result.set_parent_ids([])
697
result.set_parent_ids([revision_id])
700
def get_branch_transport(self, branch_format):
701
"""See BzrDir.get_branch_transport()."""
702
if branch_format is None:
703
return self.transport
705
branch_format.get_format_string()
706
except NotImplementedError:
707
return self.transport
708
raise errors.IncompatibleFormat(branch_format, self._format)
710
def get_repository_transport(self, repository_format):
711
"""See BzrDir.get_repository_transport()."""
712
if repository_format is None:
713
return self.transport
715
repository_format.get_format_string()
716
except NotImplementedError:
717
return self.transport
718
raise errors.IncompatibleFormat(repository_format, self._format)
720
def get_workingtree_transport(self, workingtree_format):
721
"""See BzrDir.get_workingtree_transport()."""
722
if workingtree_format is None:
723
return self.transport
725
workingtree_format.get_format_string()
726
except NotImplementedError:
727
return self.transport
728
raise errors.IncompatibleFormat(workingtree_format, self._format)
730
def needs_format_conversion(self, format=None):
731
"""See BzrDir.needs_format_conversion()."""
732
# if the format is not the same as the system default,
733
# an upgrade is needed.
735
format = BzrDirFormat.get_default_format()
736
return not isinstance(self._format, format.__class__)
738
def open_branch(self, unsupported=False):
739
"""See BzrDir.open_branch."""
740
from bzrlib.branch import BzrBranchFormat4
741
format = BzrBranchFormat4()
742
self._check_supported(format, unsupported)
743
return format.open(self, _found=True)
745
def sprout(self, url, revision_id=None, basis=None, force_new_repo=False):
746
"""See BzrDir.sprout()."""
747
from bzrlib.workingtree import WorkingTreeFormat2
749
result = self._format._initialize_for_clone(url)
750
basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
752
self.open_repository().clone(result, revision_id=revision_id, basis=basis_repo)
753
except errors.NoRepositoryPresent:
756
self.open_branch().sprout(result, revision_id=revision_id)
757
except errors.NotBranchError:
759
# we always want a working tree
760
WorkingTreeFormat2().initialize(result)
764
class BzrDir4(BzrDirPreSplitOut):
765
"""A .bzr version 4 control object.
767
This is a deprecated format and may be removed after sept 2006.
770
def create_repository(self, shared=False):
771
"""See BzrDir.create_repository."""
772
return self._format.repository_format.initialize(self, shared)
774
def needs_format_conversion(self, format=None):
775
"""Format 4 dirs are always in need of conversion."""
778
def open_repository(self):
779
"""See BzrDir.open_repository."""
780
from bzrlib.repository import RepositoryFormat4
781
return RepositoryFormat4().open(self, _found=True)
784
class BzrDir5(BzrDirPreSplitOut):
785
"""A .bzr version 5 control object.
787
This is a deprecated format and may be removed after sept 2006.
790
def open_repository(self):
791
"""See BzrDir.open_repository."""
792
from bzrlib.repository import RepositoryFormat5
793
return RepositoryFormat5().open(self, _found=True)
795
def open_workingtree(self, _unsupported=False):
796
"""See BzrDir.create_workingtree."""
797
from bzrlib.workingtree import WorkingTreeFormat2
798
return WorkingTreeFormat2().open(self, _found=True)
801
class BzrDir6(BzrDirPreSplitOut):
802
"""A .bzr version 6 control object.
804
This is a deprecated format and may be removed after sept 2006.
807
def open_repository(self):
808
"""See BzrDir.open_repository."""
809
from bzrlib.repository import RepositoryFormat6
810
return RepositoryFormat6().open(self, _found=True)
812
def open_workingtree(self, _unsupported=False):
813
"""See BzrDir.create_workingtree."""
814
from bzrlib.workingtree import WorkingTreeFormat2
815
return WorkingTreeFormat2().open(self, _found=True)
818
class BzrDirMeta1(BzrDir):
819
"""A .bzr meta version 1 control object.
821
This is the first control object where the
822
individual aspects are really split out: there are separate repository,
823
workingtree and branch subdirectories and any subset of the three can be
824
present within a BzrDir.
827
def can_convert_format(self):
828
"""See BzrDir.can_convert_format()."""
831
def create_branch(self):
832
"""See BzrDir.create_branch."""
833
from bzrlib.branch import BranchFormat
834
return BranchFormat.get_default_format().initialize(self)
836
def create_repository(self, shared=False):
837
"""See BzrDir.create_repository."""
838
return self._format.repository_format.initialize(self, shared)
840
def create_workingtree(self, revision_id=None):
841
"""See BzrDir.create_workingtree."""
842
from bzrlib.workingtree import WorkingTreeFormat
843
return WorkingTreeFormat.get_default_format().initialize(self, revision_id)
845
def _get_mkdir_mode(self):
846
"""Figure out the mode to use when creating a bzrdir subdir."""
847
temp_control = lockable_files.LockableFiles(self.transport, '',
848
lockable_files.TransportLock)
849
return temp_control._dir_mode
851
def get_branch_transport(self, branch_format):
852
"""See BzrDir.get_branch_transport()."""
853
if branch_format is None:
854
return self.transport.clone('branch')
856
branch_format.get_format_string()
857
except NotImplementedError:
858
raise errors.IncompatibleFormat(branch_format, self._format)
860
self.transport.mkdir('branch', mode=self._get_mkdir_mode())
861
except errors.FileExists:
863
return self.transport.clone('branch')
865
def get_repository_transport(self, repository_format):
866
"""See BzrDir.get_repository_transport()."""
867
if repository_format is None:
868
return self.transport.clone('repository')
870
repository_format.get_format_string()
871
except NotImplementedError:
872
raise errors.IncompatibleFormat(repository_format, self._format)
874
self.transport.mkdir('repository', mode=self._get_mkdir_mode())
875
except errors.FileExists:
877
return self.transport.clone('repository')
879
def get_workingtree_transport(self, workingtree_format):
880
"""See BzrDir.get_workingtree_transport()."""
881
if workingtree_format is None:
882
return self.transport.clone('checkout')
884
workingtree_format.get_format_string()
885
except NotImplementedError:
886
raise errors.IncompatibleFormat(workingtree_format, self._format)
888
self.transport.mkdir('checkout', mode=self._get_mkdir_mode())
889
except errors.FileExists:
891
return self.transport.clone('checkout')
893
def needs_format_conversion(self, format=None):
894
"""See BzrDir.needs_format_conversion()."""
896
format = BzrDirFormat.get_default_format()
897
if not isinstance(self._format, format.__class__):
898
# it is not a meta dir format, conversion is needed.
900
# we might want to push this down to the repository?
902
if not isinstance(self.open_repository()._format,
903
format.repository_format.__class__):
904
# the repository needs an upgrade.
906
except errors.NoRepositoryPresent:
908
# currently there are no other possible conversions for meta1 formats.
911
def open_branch(self, unsupported=False):
912
"""See BzrDir.open_branch."""
913
from bzrlib.branch import BranchFormat
914
format = BranchFormat.find_format(self)
915
self._check_supported(format, unsupported)
916
return format.open(self, _found=True)
918
def open_repository(self, unsupported=False):
919
"""See BzrDir.open_repository."""
920
from bzrlib.repository import RepositoryFormat
921
format = RepositoryFormat.find_format(self)
922
self._check_supported(format, unsupported)
923
return format.open(self, _found=True)
925
def open_workingtree(self, unsupported=False):
926
"""See BzrDir.open_workingtree."""
927
from bzrlib.workingtree import WorkingTreeFormat
928
format = WorkingTreeFormat.find_format(self)
929
self._check_supported(format, unsupported)
930
return format.open(self, _found=True)
933
class BzrDirFormat(object):
934
"""An encapsulation of the initialization and open routines for a format.
936
Formats provide three things:
937
* An initialization routine,
941
Formats are placed in an dict by their format string for reference
942
during bzrdir opening. These should be subclasses of BzrDirFormat
945
Once a format is deprecated, just deprecate the initialize and open
946
methods on the format class. Do not deprecate the object, as the
947
object will be created every system load.
950
_default_format = None
951
"""The default format used for new .bzr dirs."""
954
"""The known formats."""
956
_control_formats = []
957
"""The registered control formats - .bzr, ....
959
This is a list of BzrDirFormat objects.
962
_lock_file_name = 'branch-lock'
964
# _lock_class must be set in subclasses to the lock type, typ.
965
# TransportLock or LockDir
968
def find_format(klass, transport):
969
"""Return the format present at transport."""
970
for format in klass._control_formats:
972
return format.probe_transport(transport)
973
except errors.NotBranchError:
974
# this format does not find a control dir here.
976
raise errors.NotBranchError(path=transport.base)
979
def probe_transport(klass, transport):
980
"""Return the .bzrdir style transport present at URL."""
982
format_string = transport.get(".bzr/branch-format").read()
983
except errors.NoSuchFile:
984
raise errors.NotBranchError(path=transport.base)
987
return klass._formats[format_string]
989
raise errors.UnknownFormatError(format=format_string)
992
def get_default_format(klass):
993
"""Return the current default format."""
994
return klass._default_format
996
def get_format_string(self):
997
"""Return the ASCII format string that identifies this format."""
998
raise NotImplementedError(self.get_format_string)
1000
def get_format_description(self):
1001
"""Return the short description for this format."""
1002
raise NotImplementedError(self.get_format_description)
1004
def get_converter(self, format=None):
1005
"""Return the converter to use to convert bzrdirs needing converts.
1007
This returns a bzrlib.bzrdir.Converter object.
1009
This should return the best upgrader to step this format towards the
1010
current default format. In the case of plugins we can/should provide
1011
some means for them to extend the range of returnable converters.
1013
:param format: Optional format to override the default format of the
1016
raise NotImplementedError(self.get_converter)
1018
def initialize(self, url):
1019
"""Create a bzr control dir at this url and return an opened copy.
1021
Subclasses should typically override initialize_on_transport
1022
instead of this method.
1024
return self.initialize_on_transport(get_transport(url))
1026
def initialize_on_transport(self, transport):
1027
"""Initialize a new bzrdir in the base directory of a Transport."""
1028
# Since we don't have a .bzr directory, inherit the
1029
# mode from the root directory
1030
temp_control = lockable_files.LockableFiles(transport,
1031
'', lockable_files.TransportLock)
1032
temp_control._transport.mkdir('.bzr',
1033
# FIXME: RBC 20060121 don't peek under
1035
mode=temp_control._dir_mode)
1036
file_mode = temp_control._file_mode
1038
mutter('created control directory in ' + transport.base)
1039
control = transport.clone('.bzr')
1040
utf8_files = [('README',
1041
"This is a Bazaar-NG control directory.\n"
1042
"Do not change any files in this directory.\n"),
1043
('branch-format', self.get_format_string()),
1045
# NB: no need to escape relative paths that are url safe.
1046
control_files = lockable_files.LockableFiles(control,
1047
self._lock_file_name, self._lock_class)
1048
control_files.create_lock()
1049
control_files.lock_write()
1051
for file, content in utf8_files:
1052
control_files.put_utf8(file, content)
1054
control_files.unlock()
1055
return self.open(transport, _found=True)
1057
def is_supported(self):
1058
"""Is this format supported?
1060
Supported formats must be initializable and openable.
1061
Unsupported formats may not support initialization or committing or
1062
some other features depending on the reason for not being supported.
1067
def known_formats(klass):
1068
"""Return all the known formats.
1070
Concrete formats should override _known_formats.
1072
# There is double indirection here to make sure that control
1073
# formats used by more than one dir format will only be probed
1074
# once. This can otherwise be quite expensive for remote connections.
1076
for format in klass._control_formats:
1077
result.update(format._known_formats())
1081
def _known_formats(klass):
1082
"""Return the known format instances for this control format."""
1083
return set(klass._formats.values())
1085
def open(self, transport, _found=False):
1086
"""Return an instance of this format for the dir transport points at.
1088
_found is a private parameter, do not use it.
1091
assert isinstance(BzrDirFormat.find_format(transport),
1093
return self._open(transport)
1095
def _open(self, transport):
1096
"""Template method helper for opening BzrDirectories.
1098
This performs the actual open and any additional logic or parameter
1101
raise NotImplementedError(self._open)
1104
def register_format(klass, format):
1105
klass._formats[format.get_format_string()] = format
1108
def register_control_format(klass, format):
1109
"""Register a format that does not use '.bzrdir' for its control dir.
1111
TODO: This should be pulled up into a 'ControlDirFormat' base class
1112
which BzrDirFormat can inherit from, and renamed to register_format
1113
there. It has been done without that for now for simplicity of
1116
klass._control_formats.append(format)
1119
def set_default_format(klass, format):
1120
klass._default_format = format
1123
return self.get_format_string()[:-1]
1126
def unregister_format(klass, format):
1127
assert klass._formats[format.get_format_string()] is format
1128
del klass._formats[format.get_format_string()]
1131
def unregister_control_format(klass, format):
1132
klass._control_formats.remove(format)
1135
# register BzrDirFormat as a control format
1136
BzrDirFormat.register_control_format(BzrDirFormat)
1139
class BzrDirFormat4(BzrDirFormat):
1140
"""Bzr dir format 4.
1142
This format is a combined format for working tree, branch and repository.
1144
- Format 1 working trees [always]
1145
- Format 4 branches [always]
1146
- Format 4 repositories [always]
1148
This format is deprecated: it indexes texts using a text it which is
1149
removed in format 5; write support for this format has been removed.
1152
_lock_class = lockable_files.TransportLock
1154
def get_format_string(self):
1155
"""See BzrDirFormat.get_format_string()."""
1156
return "Bazaar-NG branch, format 0.0.4\n"
1158
def get_format_description(self):
1159
"""See BzrDirFormat.get_format_description()."""
1160
return "All-in-one format 4"
1162
def get_converter(self, format=None):
1163
"""See BzrDirFormat.get_converter()."""
1164
# there is one and only one upgrade path here.
1165
return ConvertBzrDir4To5()
1167
def initialize_on_transport(self, transport):
1168
"""Format 4 branches cannot be created."""
1169
raise errors.UninitializableFormat(self)
1171
def is_supported(self):
1172
"""Format 4 is not supported.
1174
It is not supported because the model changed from 4 to 5 and the
1175
conversion logic is expensive - so doing it on the fly was not
1180
def _open(self, transport):
1181
"""See BzrDirFormat._open."""
1182
return BzrDir4(transport, self)
1184
def __return_repository_format(self):
1185
"""Circular import protection."""
1186
from bzrlib.repository import RepositoryFormat4
1187
return RepositoryFormat4(self)
1188
repository_format = property(__return_repository_format)
1191
class BzrDirFormat5(BzrDirFormat):
1192
"""Bzr control format 5.
1194
This format is a combined format for working tree, branch and repository.
1196
- Format 2 working trees [always]
1197
- Format 4 branches [always]
1198
- Format 5 repositories [always]
1199
Unhashed stores in the repository.
1202
_lock_class = lockable_files.TransportLock
1204
def get_format_string(self):
1205
"""See BzrDirFormat.get_format_string()."""
1206
return "Bazaar-NG branch, format 5\n"
1208
def get_format_description(self):
1209
"""See BzrDirFormat.get_format_description()."""
1210
return "All-in-one format 5"
1212
def get_converter(self, format=None):
1213
"""See BzrDirFormat.get_converter()."""
1214
# there is one and only one upgrade path here.
1215
return ConvertBzrDir5To6()
1217
def _initialize_for_clone(self, url):
1218
return self.initialize_on_transport(get_transport(url), _cloning=True)
1220
def initialize_on_transport(self, transport, _cloning=False):
1221
"""Format 5 dirs always have working tree, branch and repository.
1223
Except when they are being cloned.
1225
from bzrlib.branch import BzrBranchFormat4
1226
from bzrlib.repository import RepositoryFormat5
1227
from bzrlib.workingtree import WorkingTreeFormat2
1228
result = (super(BzrDirFormat5, self).initialize_on_transport(transport))
1229
RepositoryFormat5().initialize(result, _internal=True)
1231
branch = BzrBranchFormat4().initialize(result)
1233
WorkingTreeFormat2().initialize(result)
1234
except errors.NotLocalUrl:
1235
# Even though we can't access the working tree, we need to
1236
# create its control files.
1237
WorkingTreeFormat2().stub_initialize_remote(branch.control_files)
1240
def _open(self, transport):
1241
"""See BzrDirFormat._open."""
1242
return BzrDir5(transport, self)
1244
def __return_repository_format(self):
1245
"""Circular import protection."""
1246
from bzrlib.repository import RepositoryFormat5
1247
return RepositoryFormat5(self)
1248
repository_format = property(__return_repository_format)
1251
class BzrDirFormat6(BzrDirFormat):
1252
"""Bzr control format 6.
1254
This format is a combined format for working tree, branch and repository.
1256
- Format 2 working trees [always]
1257
- Format 4 branches [always]
1258
- Format 6 repositories [always]
1261
_lock_class = lockable_files.TransportLock
1263
def get_format_string(self):
1264
"""See BzrDirFormat.get_format_string()."""
1265
return "Bazaar-NG branch, format 6\n"
1267
def get_format_description(self):
1268
"""See BzrDirFormat.get_format_description()."""
1269
return "All-in-one format 6"
1271
def get_converter(self, format=None):
1272
"""See BzrDirFormat.get_converter()."""
1273
# there is one and only one upgrade path here.
1274
return ConvertBzrDir6ToMeta()
1276
def _initialize_for_clone(self, url):
1277
return self.initialize_on_transport(get_transport(url), _cloning=True)
1279
def initialize_on_transport(self, transport, _cloning=False):
1280
"""Format 6 dirs always have working tree, branch and repository.
1282
Except when they are being cloned.
1284
from bzrlib.branch import BzrBranchFormat4
1285
from bzrlib.repository import RepositoryFormat6
1286
from bzrlib.workingtree import WorkingTreeFormat2
1287
result = super(BzrDirFormat6, self).initialize_on_transport(transport)
1288
RepositoryFormat6().initialize(result, _internal=True)
1290
branch = BzrBranchFormat4().initialize(result)
1292
WorkingTreeFormat2().initialize(result)
1293
except errors.NotLocalUrl:
1294
# Even though we can't access the working tree, we need to
1295
# create its control files.
1296
WorkingTreeFormat2().stub_initialize_remote(branch.control_files)
1299
def _open(self, transport):
1300
"""See BzrDirFormat._open."""
1301
return BzrDir6(transport, self)
1303
def __return_repository_format(self):
1304
"""Circular import protection."""
1305
from bzrlib.repository import RepositoryFormat6
1306
return RepositoryFormat6(self)
1307
repository_format = property(__return_repository_format)
1310
class BzrDirMetaFormat1(BzrDirFormat):
1311
"""Bzr meta control format 1
1313
This is the first format with split out working tree, branch and repository
1316
- Format 3 working trees [optional]
1317
- Format 5 branches [optional]
1318
- Format 7 repositories [optional]
1321
_lock_class = lockdir.LockDir
1323
def get_converter(self, format=None):
1324
"""See BzrDirFormat.get_converter()."""
1326
format = BzrDirFormat.get_default_format()
1327
if not isinstance(self, format.__class__):
1328
# converting away from metadir is not implemented
1329
raise NotImplementedError(self.get_converter)
1330
return ConvertMetaToMeta(format)
1332
def get_format_string(self):
1333
"""See BzrDirFormat.get_format_string()."""
1334
return "Bazaar-NG meta directory, format 1\n"
1336
def get_format_description(self):
1337
"""See BzrDirFormat.get_format_description()."""
1338
return "Meta directory format 1"
1340
def _open(self, transport):
1341
"""See BzrDirFormat._open."""
1342
return BzrDirMeta1(transport, self)
1344
def __return_repository_format(self):
1345
"""Circular import protection."""
1346
if getattr(self, '_repository_format', None):
1347
return self._repository_format
1348
from bzrlib.repository import RepositoryFormat
1349
return RepositoryFormat.get_default_format()
1351
def __set_repository_format(self, value):
1352
"""Allow changint the repository format for metadir formats."""
1353
self._repository_format = value
1355
repository_format = property(__return_repository_format, __set_repository_format)
1358
BzrDirFormat.register_format(BzrDirFormat4())
1359
BzrDirFormat.register_format(BzrDirFormat5())
1360
BzrDirFormat.register_format(BzrDirFormat6())
1361
__default_format = BzrDirMetaFormat1()
1362
BzrDirFormat.register_format(__default_format)
1363
BzrDirFormat.set_default_format(__default_format)
1366
class BzrDirTestProviderAdapter(object):
1367
"""A tool to generate a suite testing multiple bzrdir formats at once.
1369
This is done by copying the test once for each transport and injecting
1370
the transport_server, transport_readonly_server, and bzrdir_format
1371
classes into each copy. Each copy is also given a new id() to make it
1375
def __init__(self, transport_server, transport_readonly_server, formats):
1376
self._transport_server = transport_server
1377
self._transport_readonly_server = transport_readonly_server
1378
self._formats = formats
1380
def adapt(self, test):
1381
result = unittest.TestSuite()
1382
for format in self._formats:
1383
new_test = deepcopy(test)
1384
new_test.transport_server = self._transport_server
1385
new_test.transport_readonly_server = self._transport_readonly_server
1386
new_test.bzrdir_format = format
1387
def make_new_test_id():
1388
new_id = "%s(%s)" % (new_test.id(), format.__class__.__name__)
1389
return lambda: new_id
1390
new_test.id = make_new_test_id()
1391
result.addTest(new_test)
1395
class Converter(object):
1396
"""Converts a disk format object from one format to another."""
1398
def convert(self, to_convert, pb):
1399
"""Perform the conversion of to_convert, giving feedback via pb.
1401
:param to_convert: The disk object to convert.
1402
:param pb: a progress bar to use for progress information.
1405
def step(self, message):
1406
"""Update the pb by a step."""
1408
self.pb.update(message, self.count, self.total)
1411
class ConvertBzrDir4To5(Converter):
1412
"""Converts format 4 bzr dirs to format 5."""
1415
super(ConvertBzrDir4To5, self).__init__()
1416
self.converted_revs = set()
1417
self.absent_revisions = set()
1421
def convert(self, to_convert, pb):
1422
"""See Converter.convert()."""
1423
self.bzrdir = to_convert
1425
self.pb.note('starting upgrade from format 4 to 5')
1426
if isinstance(self.bzrdir.transport, LocalTransport):
1427
self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
1428
self._convert_to_weaves()
1429
return BzrDir.open(self.bzrdir.root_transport.base)
1431
def _convert_to_weaves(self):
1432
self.pb.note('note: upgrade may be faster if all store files are ungzipped first')
1435
stat = self.bzrdir.transport.stat('weaves')
1436
if not S_ISDIR(stat.st_mode):
1437
self.bzrdir.transport.delete('weaves')
1438
self.bzrdir.transport.mkdir('weaves')
1439
except errors.NoSuchFile:
1440
self.bzrdir.transport.mkdir('weaves')
1441
# deliberately not a WeaveFile as we want to build it up slowly.
1442
self.inv_weave = Weave('inventory')
1443
# holds in-memory weaves for all files
1444
self.text_weaves = {}
1445
self.bzrdir.transport.delete('branch-format')
1446
self.branch = self.bzrdir.open_branch()
1447
self._convert_working_inv()
1448
rev_history = self.branch.revision_history()
1449
# to_read is a stack holding the revisions we still need to process;
1450
# appending to it adds new highest-priority revisions
1451
self.known_revisions = set(rev_history)
1452
self.to_read = rev_history[-1:]
1454
rev_id = self.to_read.pop()
1455
if (rev_id not in self.revisions
1456
and rev_id not in self.absent_revisions):
1457
self._load_one_rev(rev_id)
1459
to_import = self._make_order()
1460
for i, rev_id in enumerate(to_import):
1461
self.pb.update('converting revision', i, len(to_import))
1462
self._convert_one_rev(rev_id)
1464
self._write_all_weaves()
1465
self._write_all_revs()
1466
self.pb.note('upgraded to weaves:')
1467
self.pb.note(' %6d revisions and inventories', len(self.revisions))
1468
self.pb.note(' %6d revisions not present', len(self.absent_revisions))
1469
self.pb.note(' %6d texts', self.text_count)
1470
self._cleanup_spare_files_after_format4()
1471
self.branch.control_files.put_utf8('branch-format', BzrDirFormat5().get_format_string())
1473
def _cleanup_spare_files_after_format4(self):
1474
# FIXME working tree upgrade foo.
1475
for n in 'merged-patches', 'pending-merged-patches':
1477
## assert os.path.getsize(p) == 0
1478
self.bzrdir.transport.delete(n)
1479
except errors.NoSuchFile:
1481
self.bzrdir.transport.delete_tree('inventory-store')
1482
self.bzrdir.transport.delete_tree('text-store')
1484
def _convert_working_inv(self):
1485
inv = xml4.serializer_v4.read_inventory(
1486
self.branch.control_files.get('inventory'))
1487
new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
1488
# FIXME inventory is a working tree change.
1489
self.branch.control_files.put('inventory', StringIO(new_inv_xml))
1491
def _write_all_weaves(self):
1492
controlweaves = WeaveStore(self.bzrdir.transport, prefixed=False)
1493
weave_transport = self.bzrdir.transport.clone('weaves')
1494
weaves = WeaveStore(weave_transport, prefixed=False)
1495
transaction = WriteTransaction()
1499
for file_id, file_weave in self.text_weaves.items():
1500
self.pb.update('writing weave', i, len(self.text_weaves))
1501
weaves._put_weave(file_id, file_weave, transaction)
1503
self.pb.update('inventory', 0, 1)
1504
controlweaves._put_weave('inventory', self.inv_weave, transaction)
1505
self.pb.update('inventory', 1, 1)
1509
def _write_all_revs(self):
1510
"""Write all revisions out in new form."""
1511
self.bzrdir.transport.delete_tree('revision-store')
1512
self.bzrdir.transport.mkdir('revision-store')
1513
revision_transport = self.bzrdir.transport.clone('revision-store')
1515
_revision_store = TextRevisionStore(TextStore(revision_transport,
1519
transaction = WriteTransaction()
1520
for i, rev_id in enumerate(self.converted_revs):
1521
self.pb.update('write revision', i, len(self.converted_revs))
1522
_revision_store.add_revision(self.revisions[rev_id], transaction)
1526
def _load_one_rev(self, rev_id):
1527
"""Load a revision object into memory.
1529
Any parents not either loaded or abandoned get queued to be
1531
self.pb.update('loading revision',
1532
len(self.revisions),
1533
len(self.known_revisions))
1534
if not self.branch.repository.has_revision(rev_id):
1536
self.pb.note('revision {%s} not present in branch; '
1537
'will be converted as a ghost',
1539
self.absent_revisions.add(rev_id)
1541
rev = self.branch.repository._revision_store.get_revision(rev_id,
1542
self.branch.repository.get_transaction())
1543
for parent_id in rev.parent_ids:
1544
self.known_revisions.add(parent_id)
1545
self.to_read.append(parent_id)
1546
self.revisions[rev_id] = rev
1548
def _load_old_inventory(self, rev_id):
1549
assert rev_id not in self.converted_revs
1550
old_inv_xml = self.branch.repository.inventory_store.get(rev_id).read()
1551
inv = xml4.serializer_v4.read_inventory_from_string(old_inv_xml)
1552
rev = self.revisions[rev_id]
1553
if rev.inventory_sha1:
1554
assert rev.inventory_sha1 == sha_string(old_inv_xml), \
1555
'inventory sha mismatch for {%s}' % rev_id
1558
def _load_updated_inventory(self, rev_id):
1559
assert rev_id in self.converted_revs
1560
inv_xml = self.inv_weave.get_text(rev_id)
1561
inv = xml5.serializer_v5.read_inventory_from_string(inv_xml)
1564
def _convert_one_rev(self, rev_id):
1565
"""Convert revision and all referenced objects to new format."""
1566
rev = self.revisions[rev_id]
1567
inv = self._load_old_inventory(rev_id)
1568
present_parents = [p for p in rev.parent_ids
1569
if p not in self.absent_revisions]
1570
self._convert_revision_contents(rev, inv, present_parents)
1571
self._store_new_weave(rev, inv, present_parents)
1572
self.converted_revs.add(rev_id)
1574
def _store_new_weave(self, rev, inv, present_parents):
1575
# the XML is now updated with text versions
1577
entries = inv.iter_entries()
1579
for path, ie in entries:
1580
assert getattr(ie, 'revision', None) is not None, \
1581
'no revision on {%s} in {%s}' % \
1582
(file_id, rev.revision_id)
1583
new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
1584
new_inv_sha1 = sha_string(new_inv_xml)
1585
self.inv_weave.add_lines(rev.revision_id,
1587
new_inv_xml.splitlines(True))
1588
rev.inventory_sha1 = new_inv_sha1
1590
def _convert_revision_contents(self, rev, inv, present_parents):
1591
"""Convert all the files within a revision.
1593
Also upgrade the inventory to refer to the text revision ids."""
1594
rev_id = rev.revision_id
1595
mutter('converting texts of revision {%s}',
1597
parent_invs = map(self._load_updated_inventory, present_parents)
1598
entries = inv.iter_entries()
1600
for path, ie in entries:
1601
self._convert_file_version(rev, ie, parent_invs)
1603
def _convert_file_version(self, rev, ie, parent_invs):
1604
"""Convert one version of one file.
1606
The file needs to be added into the weave if it is a merge
1607
of >=2 parents or if it's changed from its parent.
1609
file_id = ie.file_id
1610
rev_id = rev.revision_id
1611
w = self.text_weaves.get(file_id)
1614
self.text_weaves[file_id] = w
1615
text_changed = False
1616
previous_entries = ie.find_previous_heads(parent_invs,
1620
for old_revision in previous_entries:
1621
# if this fails, its a ghost ?
1622
assert old_revision in self.converted_revs
1623
self.snapshot_ie(previous_entries, ie, w, rev_id)
1625
assert getattr(ie, 'revision', None) is not None
1627
def snapshot_ie(self, previous_revisions, ie, w, rev_id):
1628
# TODO: convert this logic, which is ~= snapshot to
1629
# a call to:. This needs the path figured out. rather than a work_tree
1630
# a v4 revision_tree can be given, or something that looks enough like
1631
# one to give the file content to the entry if it needs it.
1632
# and we need something that looks like a weave store for snapshot to
1634
#ie.snapshot(rev, PATH, previous_revisions, REVISION_TREE, InMemoryWeaveStore(self.text_weaves))
1635
if len(previous_revisions) == 1:
1636
previous_ie = previous_revisions.values()[0]
1637
if ie._unchanged(previous_ie):
1638
ie.revision = previous_ie.revision
1641
text = self.branch.repository.text_store.get(ie.text_id)
1642
file_lines = text.readlines()
1643
assert sha_strings(file_lines) == ie.text_sha1
1644
assert sum(map(len, file_lines)) == ie.text_size
1645
w.add_lines(rev_id, previous_revisions, file_lines)
1646
self.text_count += 1
1648
w.add_lines(rev_id, previous_revisions, [])
1649
ie.revision = rev_id
1651
def _make_order(self):
1652
"""Return a suitable order for importing revisions.
1654
The order must be such that an revision is imported after all
1655
its (present) parents.
1657
todo = set(self.revisions.keys())
1658
done = self.absent_revisions.copy()
1661
# scan through looking for a revision whose parents
1663
for rev_id in sorted(list(todo)):
1664
rev = self.revisions[rev_id]
1665
parent_ids = set(rev.parent_ids)
1666
if parent_ids.issubset(done):
1667
# can take this one now
1668
order.append(rev_id)
1674
class ConvertBzrDir5To6(Converter):
1675
"""Converts format 5 bzr dirs to format 6."""
1677
def convert(self, to_convert, pb):
1678
"""See Converter.convert()."""
1679
self.bzrdir = to_convert
1681
self.pb.note('starting upgrade from format 5 to 6')
1682
self._convert_to_prefixed()
1683
return BzrDir.open(self.bzrdir.root_transport.base)
1685
def _convert_to_prefixed(self):
1686
from bzrlib.store import TransportStore
1687
self.bzrdir.transport.delete('branch-format')
1688
for store_name in ["weaves", "revision-store"]:
1689
self.pb.note("adding prefixes to %s" % store_name)
1690
store_transport = self.bzrdir.transport.clone(store_name)
1691
store = TransportStore(store_transport, prefixed=True)
1692
for urlfilename in store_transport.list_dir('.'):
1693
filename = urlutils.unescape(urlfilename)
1694
if (filename.endswith(".weave") or
1695
filename.endswith(".gz") or
1696
filename.endswith(".sig")):
1697
file_id = os.path.splitext(filename)[0]
1700
prefix_dir = store.hash_prefix(file_id)
1701
# FIXME keep track of the dirs made RBC 20060121
1703
store_transport.move(filename, prefix_dir + '/' + filename)
1704
except errors.NoSuchFile: # catches missing dirs strangely enough
1705
store_transport.mkdir(prefix_dir)
1706
store_transport.move(filename, prefix_dir + '/' + filename)
1707
self.bzrdir._control_files.put_utf8('branch-format', BzrDirFormat6().get_format_string())
1710
class ConvertBzrDir6ToMeta(Converter):
1711
"""Converts format 6 bzr dirs to metadirs."""
1713
def convert(self, to_convert, pb):
1714
"""See Converter.convert()."""
1715
self.bzrdir = to_convert
1718
self.total = 20 # the steps we know about
1719
self.garbage_inventories = []
1721
self.pb.note('starting upgrade from format 6 to metadir')
1722
self.bzrdir._control_files.put_utf8('branch-format', "Converting to format 6")
1723
# its faster to move specific files around than to open and use the apis...
1724
# first off, nuke ancestry.weave, it was never used.
1726
self.step('Removing ancestry.weave')
1727
self.bzrdir.transport.delete('ancestry.weave')
1728
except errors.NoSuchFile:
1730
# find out whats there
1731
self.step('Finding branch files')
1732
last_revision = self.bzrdir.open_branch().last_revision()
1733
bzrcontents = self.bzrdir.transport.list_dir('.')
1734
for name in bzrcontents:
1735
if name.startswith('basis-inventory.'):
1736
self.garbage_inventories.append(name)
1737
# create new directories for repository, working tree and branch
1738
self.dir_mode = self.bzrdir._control_files._dir_mode
1739
self.file_mode = self.bzrdir._control_files._file_mode
1740
repository_names = [('inventory.weave', True),
1741
('revision-store', True),
1743
self.step('Upgrading repository ')
1744
self.bzrdir.transport.mkdir('repository', mode=self.dir_mode)
1745
self.make_lock('repository')
1746
# we hard code the formats here because we are converting into
1747
# the meta format. The meta format upgrader can take this to a
1748
# future format within each component.
1749
self.put_format('repository', bzrlib.repository.RepositoryFormat7())
1750
for entry in repository_names:
1751
self.move_entry('repository', entry)
1753
self.step('Upgrading branch ')
1754
self.bzrdir.transport.mkdir('branch', mode=self.dir_mode)
1755
self.make_lock('branch')
1756
self.put_format('branch', bzrlib.branch.BzrBranchFormat5())
1757
branch_files = [('revision-history', True),
1758
('branch-name', True),
1760
for entry in branch_files:
1761
self.move_entry('branch', entry)
1763
checkout_files = [('pending-merges', True),
1764
('inventory', True),
1765
('stat-cache', False)]
1766
# If a mandatory checkout file is not present, the branch does not have
1767
# a functional checkout. Do not create a checkout in the converted
1769
for name, mandatory in checkout_files:
1770
if mandatory and name not in bzrcontents:
1771
has_checkout = False
1775
if not has_checkout:
1776
self.pb.note('No working tree.')
1777
# If some checkout files are there, we may as well get rid of them.
1778
for name, mandatory in checkout_files:
1779
if name in bzrcontents:
1780
self.bzrdir.transport.delete(name)
1782
self.step('Upgrading working tree')
1783
self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
1784
self.make_lock('checkout')
1786
'checkout', bzrlib.workingtree.WorkingTreeFormat3())
1787
self.bzrdir.transport.delete_multi(
1788
self.garbage_inventories, self.pb)
1789
for entry in checkout_files:
1790
self.move_entry('checkout', entry)
1791
if last_revision is not None:
1792
self.bzrdir._control_files.put_utf8(
1793
'checkout/last-revision', last_revision)
1794
self.bzrdir._control_files.put_utf8(
1795
'branch-format', BzrDirMetaFormat1().get_format_string())
1796
return BzrDir.open(self.bzrdir.root_transport.base)
1798
def make_lock(self, name):
1799
"""Make a lock for the new control dir name."""
1800
self.step('Make %s lock' % name)
1801
ld = lockdir.LockDir(self.bzrdir.transport,
1803
file_modebits=self.file_mode,
1804
dir_modebits=self.dir_mode)
1807
def move_entry(self, new_dir, entry):
1808
"""Move then entry name into new_dir."""
1810
mandatory = entry[1]
1811
self.step('Moving %s' % name)
1813
self.bzrdir.transport.move(name, '%s/%s' % (new_dir, name))
1814
except errors.NoSuchFile:
1818
def put_format(self, dirname, format):
1819
self.bzrdir._control_files.put_utf8('%s/format' % dirname, format.get_format_string())
1822
class ConvertMetaToMeta(Converter):
1823
"""Converts the components of metadirs."""
1825
def __init__(self, target_format):
1826
"""Create a metadir to metadir converter.
1828
:param target_format: The final metadir format that is desired.
1830
self.target_format = target_format
1832
def convert(self, to_convert, pb):
1833
"""See Converter.convert()."""
1834
self.bzrdir = to_convert
1838
self.step('checking repository format')
1840
repo = self.bzrdir.open_repository()
1841
except errors.NoRepositoryPresent:
1844
if not isinstance(repo._format, self.target_format.repository_format.__class__):
1845
from bzrlib.repository import CopyConverter
1846
self.pb.note('starting repository conversion')
1847
converter = CopyConverter(self.target_format.repository_format)
1848
converter.convert(repo, pb)