1
# Copyright (C) 2005, 2006 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
"""BzrDir logic. The BzrDir is the basic control directory used by bzr.
19
At format 7 this was split out into Branch, Repository and Checkout control
23
from copy import deepcopy
25
from cStringIO import StringIO
26
from unittest import TestSuite
29
import bzrlib.errors as errors
30
from bzrlib.lockable_files import LockableFiles, TransportLock
31
from bzrlib.lockdir import LockDir
32
from bzrlib.osutils import safe_unicode
33
from bzrlib.osutils import (
40
from bzrlib.store.revision.text import TextRevisionStore
41
from bzrlib.store.text import TextStore
42
from bzrlib.store.versioned import WeaveStore
43
from bzrlib.symbol_versioning import *
44
from bzrlib.trace import mutter
45
from bzrlib.transactions import WriteTransaction
46
from bzrlib.transport import get_transport, urlunescape
47
from bzrlib.transport.local import LocalTransport
48
from bzrlib.weave import Weave
49
from bzrlib.xml4 import serializer_v4
50
from bzrlib.xml5 import serializer_v5
54
"""A .bzr control diretory.
56
BzrDir instances let you create or open any of the things that can be
57
found within .bzr - checkouts, branches and repositories.
60
the transport which this bzr dir is rooted at (i.e. file:///.../.bzr/)
62
a transport connected to the directory this bzr was opened from.
66
"""Invoke break_lock on the first object in the bzrdir.
68
If there is a tree, the tree is opened and break_lock() called.
69
Otherwise, branch is tried, and finally repository.
72
thing_to_unlock = self.open_workingtree()
73
except (errors.NotLocalUrl, errors.NoWorkingTree):
75
thing_to_unlock = self.open_branch()
76
except errors.NotBranchError:
78
thing_to_unlock = self.open_repository()
79
except errors.NoRepositoryPresent:
81
thing_to_unlock.break_lock()
83
def can_convert_format(self):
84
"""Return true if this bzrdir is one whose format we can convert from."""
88
def _check_supported(format, allow_unsupported):
89
"""Check whether format is a supported format.
91
If allow_unsupported is True, this is a no-op.
93
if not allow_unsupported and not format.is_supported():
94
# see open_downlevel to open legacy branches.
95
raise errors.UnsupportedFormatError(
96
'sorry, format %s not supported' % format,
97
['use a different bzr version',
98
'or remove the .bzr directory'
99
' and "bzr init" again'])
101
def clone(self, url, revision_id=None, basis=None, force_new_repo=False):
102
"""Clone this bzrdir and its contents to url verbatim.
104
If urls last component does not exist, it will be created.
106
if revision_id is not None, then the clone operation may tune
107
itself to download less data.
108
:param force_new_repo: Do not use a shared repository for the target
109
even if one is available.
112
basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
113
result = self._format.initialize(url)
115
local_repo = self.find_repository()
116
except errors.NoRepositoryPresent:
119
# may need to copy content in
121
local_repo.clone(result, revision_id=revision_id, basis=basis_repo)
124
result_repo = result.find_repository()
125
# fetch content this dir needs.
127
# XXX FIXME RBC 20060214 need tests for this when the basis
129
result_repo.fetch(basis_repo, revision_id=revision_id)
130
result_repo.fetch(local_repo, revision_id=revision_id)
131
except errors.NoRepositoryPresent:
132
# needed to make one anyway.
133
local_repo.clone(result, revision_id=revision_id, basis=basis_repo)
134
# 1 if there is a branch present
135
# make sure its content is available in the target repository
138
self.open_branch().clone(result, revision_id=revision_id)
139
except errors.NotBranchError:
142
self.open_workingtree().clone(result, basis=basis_tree)
143
except (errors.NoWorkingTree, errors.NotLocalUrl):
147
def _get_basis_components(self, basis):
148
"""Retrieve the basis components that are available at basis."""
150
return None, None, None
152
basis_tree = basis.open_workingtree()
153
basis_branch = basis_tree.branch
154
basis_repo = basis_branch.repository
155
except (errors.NoWorkingTree, errors.NotLocalUrl):
158
basis_branch = basis.open_branch()
159
basis_repo = basis_branch.repository
160
except errors.NotBranchError:
163
basis_repo = basis.open_repository()
164
except errors.NoRepositoryPresent:
166
return basis_repo, basis_branch, basis_tree
168
def _make_tail(self, url):
169
segments = url.split('/')
170
if segments and segments[-1] not in ('', '.'):
171
parent = '/'.join(segments[:-1])
172
t = bzrlib.transport.get_transport(parent)
174
t.mkdir(segments[-1])
175
except errors.FileExists:
179
def create(cls, base):
180
"""Create a new BzrDir at the url 'base'.
182
This will call the current default formats initialize with base
183
as the only parameter.
185
If you need a specific format, consider creating an instance
186
of that and calling initialize().
188
if cls is not BzrDir:
189
raise AssertionError("BzrDir.create always creates the default format, "
190
"not one of %r" % cls)
191
segments = base.split('/')
192
if segments and segments[-1] not in ('', '.'):
193
parent = '/'.join(segments[:-1])
194
t = bzrlib.transport.get_transport(parent)
196
t.mkdir(segments[-1])
197
except errors.FileExists:
199
return BzrDirFormat.get_default_format().initialize(safe_unicode(base))
201
def create_branch(self):
202
"""Create a branch in this BzrDir.
204
The bzrdirs format will control what branch format is created.
205
For more control see BranchFormatXX.create(a_bzrdir).
207
raise NotImplementedError(self.create_branch)
210
def create_branch_and_repo(base, force_new_repo=False):
211
"""Create a new BzrDir, Branch and Repository at the url 'base'.
213
This will use the current default BzrDirFormat, and use whatever
214
repository format that that uses via bzrdir.create_branch and
215
create_repository. If a shared repository is available that is used
218
The created Branch object is returned.
220
:param base: The URL to create the branch at.
221
:param force_new_repo: If True a new repository is always created.
223
bzrdir = BzrDir.create(base)
224
bzrdir._find_or_create_repository(force_new_repo)
225
return bzrdir.create_branch()
227
def _find_or_create_repository(self, force_new_repo):
228
"""Create a new repository if needed, returning the repository."""
230
return self.create_repository()
232
return self.find_repository()
233
except errors.NoRepositoryPresent:
234
return self.create_repository()
237
def create_branch_convenience(base, force_new_repo=False,
238
force_new_tree=None, format=None):
239
"""Create a new BzrDir, Branch and Repository at the url 'base'.
241
This is a convenience function - it will use an existing repository
242
if possible, can be told explicitly whether to create a working tree or
245
This will use the current default BzrDirFormat, and use whatever
246
repository format that that uses via bzrdir.create_branch and
247
create_repository. If a shared repository is available that is used
248
preferentially. Whatever repository is used, its tree creation policy
251
The created Branch object is returned.
252
If a working tree cannot be made due to base not being a file:// url,
253
no error is raised unless force_new_tree is True, in which case no
254
data is created on disk and NotLocalUrl is raised.
256
:param base: The URL to create the branch at.
257
:param force_new_repo: If True a new repository is always created.
258
:param force_new_tree: If True or False force creation of a tree or
259
prevent such creation respectively.
260
:param format: Override for the for the bzrdir format to create
263
# check for non local urls
264
t = get_transport(safe_unicode(base))
265
if not isinstance(t, LocalTransport):
266
raise errors.NotLocalUrl(base)
268
bzrdir = BzrDir.create(base)
270
bzrdir = format.initialize(base)
271
repo = bzrdir._find_or_create_repository(force_new_repo)
272
result = bzrdir.create_branch()
273
if force_new_tree or (repo.make_working_trees() and
274
force_new_tree is None):
276
bzrdir.create_workingtree()
277
except errors.NotLocalUrl:
282
def create_repository(base, shared=False):
283
"""Create a new BzrDir and Repository at the url 'base'.
285
This will use the current default BzrDirFormat, and use whatever
286
repository format that that uses for bzrdirformat.create_repository.
288
;param shared: Create a shared repository rather than a standalone
290
The Repository object is returned.
292
This must be overridden as an instance method in child classes, where
293
it should take no parameters and construct whatever repository format
294
that child class desires.
296
bzrdir = BzrDir.create(base)
297
return bzrdir.create_repository()
300
def create_standalone_workingtree(base):
301
"""Create a new BzrDir, WorkingTree, Branch and Repository at 'base'.
303
'base' must be a local path or a file:// url.
305
This will use the current default BzrDirFormat, and use whatever
306
repository format that that uses for bzrdirformat.create_workingtree,
307
create_branch and create_repository.
309
The WorkingTree object is returned.
311
t = get_transport(safe_unicode(base))
312
if not isinstance(t, LocalTransport):
313
raise errors.NotLocalUrl(base)
314
bzrdir = BzrDir.create_branch_and_repo(safe_unicode(base),
315
force_new_repo=True).bzrdir
316
return bzrdir.create_workingtree()
318
def create_workingtree(self, revision_id=None):
319
"""Create a working tree at this BzrDir.
321
revision_id: create it as of this revision id.
323
raise NotImplementedError(self.create_workingtree)
325
def find_repository(self):
326
"""Find the repository that should be used for a_bzrdir.
328
This does not require a branch as we use it to find the repo for
329
new branches as well as to hook existing branches up to their
333
return self.open_repository()
334
except errors.NoRepositoryPresent:
336
next_transport = self.root_transport.clone('..')
339
found_bzrdir = BzrDir.open_containing_from_transport(
341
except errors.NotBranchError:
342
raise errors.NoRepositoryPresent(self)
344
repository = found_bzrdir.open_repository()
345
except errors.NoRepositoryPresent:
346
next_transport = found_bzrdir.root_transport.clone('..')
348
if ((found_bzrdir.root_transport.base ==
349
self.root_transport.base) or repository.is_shared()):
352
raise errors.NoRepositoryPresent(self)
353
raise errors.NoRepositoryPresent(self)
355
def get_branch_transport(self, branch_format):
356
"""Get the transport for use by branch format in this BzrDir.
358
Note that bzr dirs that do not support format strings will raise
359
IncompatibleFormat if the branch format they are given has
360
a format string, and vice verca.
362
If branch_format is None, the transport is returned with no
363
checking. if it is not None, then the returned transport is
364
guaranteed to point to an existing directory ready for use.
366
raise NotImplementedError(self.get_branch_transport)
368
def get_repository_transport(self, repository_format):
369
"""Get the transport for use by repository format in this BzrDir.
371
Note that bzr dirs that do not support format strings will raise
372
IncompatibleFormat if the repository format they are given has
373
a format string, and vice verca.
375
If repository_format is None, the transport is returned with no
376
checking. if it is not None, then the returned transport is
377
guaranteed to point to an existing directory ready for use.
379
raise NotImplementedError(self.get_repository_transport)
381
def get_workingtree_transport(self, tree_format):
382
"""Get the transport for use by workingtree format in this BzrDir.
384
Note that bzr dirs that do not support format strings will raise
385
IncompatibleFormat if the workingtree format they are given has
386
a format string, and vice verca.
388
If workingtree_format is None, the transport is returned with no
389
checking. if it is not None, then the returned transport is
390
guaranteed to point to an existing directory ready for use.
392
raise NotImplementedError(self.get_workingtree_transport)
394
def __init__(self, _transport, _format):
395
"""Initialize a Bzr control dir object.
397
Only really common logic should reside here, concrete classes should be
398
made with varying behaviours.
400
:param _format: the format that is creating this BzrDir instance.
401
:param _transport: the transport this dir is based at.
403
self._format = _format
404
self.transport = _transport.clone('.bzr')
405
self.root_transport = _transport
407
def needs_format_conversion(self, format=None):
408
"""Return true if this bzrdir needs convert_format run on it.
410
For instance, if the repository format is out of date but the
411
branch and working tree are not, this should return True.
413
:param format: Optional parameter indicating a specific desired
414
format we plan to arrive at.
416
raise NotImplementedError(self.needs_format_conversion)
419
def open_unsupported(base):
420
"""Open a branch which is not supported."""
421
return BzrDir.open(base, _unsupported=True)
424
def open(base, _unsupported=False):
425
"""Open an existing bzrdir, rooted at 'base' (url)
427
_unsupported is a private parameter to the BzrDir class.
429
t = get_transport(base)
430
mutter("trying to open %r with transport %r", base, t)
431
format = BzrDirFormat.find_format(t)
432
BzrDir._check_supported(format, _unsupported)
433
return format.open(t, _found=True)
435
def open_branch(self, unsupported=False):
436
"""Open the branch object at this BzrDir if one is present.
438
If unsupported is True, then no longer supported branch formats can
441
TODO: static convenience version of this?
443
raise NotImplementedError(self.open_branch)
446
def open_containing(url):
447
"""Open an existing branch which contains url.
449
:param url: url to search from.
450
See open_containing_from_transport for more detail.
452
return BzrDir.open_containing_from_transport(get_transport(url))
455
def open_containing_from_transport(a_transport):
456
"""Open an existing branch which contains a_transport.base
458
This probes for a branch at a_transport, and searches upwards from there.
460
Basically we keep looking up until we find the control directory or
461
run into the root. If there isn't one, raises NotBranchError.
462
If there is one and it is either an unrecognised format or an unsupported
463
format, UnknownFormatError or UnsupportedFormatError are raised.
464
If there is one, it is returned, along with the unused portion of url.
466
# this gets the normalised url back. I.e. '.' -> the full path.
467
url = a_transport.base
470
format = BzrDirFormat.find_format(a_transport)
471
BzrDir._check_supported(format, False)
472
return format.open(a_transport), a_transport.relpath(url)
473
except errors.NotBranchError, e:
474
mutter('not a branch in: %r %s', a_transport.base, e)
475
new_t = a_transport.clone('..')
476
if new_t.base == a_transport.base:
477
# reached the root, whatever that may be
478
raise errors.NotBranchError(path=url)
481
def open_repository(self, _unsupported=False):
482
"""Open the repository object at this BzrDir if one is present.
484
This will not follow the Branch object pointer - its strictly a direct
485
open facility. Most client code should use open_branch().repository to
488
_unsupported is a private parameter, not part of the api.
489
TODO: static convenience version of this?
491
raise NotImplementedError(self.open_repository)
493
def open_workingtree(self, _unsupported=False):
494
"""Open the workingtree object at this BzrDir if one is present.
496
TODO: static convenience version of this?
498
raise NotImplementedError(self.open_workingtree)
500
def has_branch(self):
501
"""Tell if this bzrdir contains a branch.
503
Note: if you're going to open the branch, you should just go ahead
504
and try, and not ask permission first. (This method just opens the
505
branch and discards it, and that's somewhat expensive.)
510
except errors.NotBranchError:
513
def has_workingtree(self):
514
"""Tell if this bzrdir contains a working tree.
516
This will still raise an exception if the bzrdir has a workingtree that
517
is remote & inaccessible.
519
Note: if you're going to open the working tree, you should just go ahead
520
and try, and not ask permission first. (This method just opens the
521
workingtree and discards it, and that's somewhat expensive.)
524
self.open_workingtree()
526
except errors.NoWorkingTree:
529
def sprout(self, url, revision_id=None, basis=None, force_new_repo=False):
530
"""Create a copy of this bzrdir prepared for use as a new line of
533
If urls last component does not exist, it will be created.
535
Attributes related to the identity of the source branch like
536
branch nickname will be cleaned, a working tree is created
537
whether one existed before or not; and a local branch is always
540
if revision_id is not None, then the clone operation may tune
541
itself to download less data.
544
result = self._format.initialize(url)
545
basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
547
source_branch = self.open_branch()
548
source_repository = source_branch.repository
549
except errors.NotBranchError:
552
source_repository = self.open_repository()
553
except errors.NoRepositoryPresent:
554
# copy the entire basis one if there is one
555
# but there is no repository.
556
source_repository = basis_repo
561
result_repo = result.find_repository()
562
except errors.NoRepositoryPresent:
564
if source_repository is None and result_repo is not None:
566
elif source_repository is None and result_repo is None:
567
# no repo available, make a new one
568
result.create_repository()
569
elif source_repository is not None and result_repo is None:
570
# have soure, and want to make a new target repo
571
source_repository.clone(result,
572
revision_id=revision_id,
575
# fetch needed content into target.
577
# XXX FIXME RBC 20060214 need tests for this when the basis
579
result_repo.fetch(basis_repo, revision_id=revision_id)
580
result_repo.fetch(source_repository, revision_id=revision_id)
581
if source_branch is not None:
582
source_branch.sprout(result, revision_id=revision_id)
584
result.create_branch()
585
if result_repo is None or result_repo.make_working_trees():
586
result.create_workingtree()
590
class BzrDirPreSplitOut(BzrDir):
591
"""A common class for the all-in-one formats."""
593
def __init__(self, _transport, _format):
594
"""See BzrDir.__init__."""
595
super(BzrDirPreSplitOut, self).__init__(_transport, _format)
596
assert self._format._lock_class == TransportLock
597
assert self._format._lock_file_name == 'branch-lock'
598
self._control_files = LockableFiles(self.get_branch_transport(None),
599
self._format._lock_file_name,
600
self._format._lock_class)
602
def break_lock(self):
603
"""Pre-splitout bzrdirs do not suffer from stale locks."""
604
raise NotImplementedError(self.break_lock)
606
def clone(self, url, revision_id=None, basis=None, force_new_repo=False):
607
"""See BzrDir.clone()."""
608
from bzrlib.workingtree import WorkingTreeFormat2
610
result = self._format._initialize_for_clone(url)
611
basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
612
self.open_repository().clone(result, revision_id=revision_id, basis=basis_repo)
613
self.open_branch().clone(result, revision_id=revision_id)
615
self.open_workingtree().clone(result, basis=basis_tree)
616
except errors.NotLocalUrl:
617
# make a new one, this format always has to have one.
619
WorkingTreeFormat2().initialize(result)
620
except errors.NotLocalUrl:
621
# but we canot do it for remote trees.
625
def create_branch(self):
626
"""See BzrDir.create_branch."""
627
return self.open_branch()
629
def create_repository(self, shared=False):
630
"""See BzrDir.create_repository."""
632
raise errors.IncompatibleFormat('shared repository', self._format)
633
return self.open_repository()
635
def create_workingtree(self, revision_id=None):
636
"""See BzrDir.create_workingtree."""
637
# this looks buggy but is not -really-
638
# clone and sprout will have set the revision_id
639
# and that will have set it for us, its only
640
# specific uses of create_workingtree in isolation
641
# that can do wonky stuff here, and that only
642
# happens for creating checkouts, which cannot be
643
# done on this format anyway. So - acceptable wart.
644
result = self.open_workingtree()
645
if revision_id is not None:
646
result.set_last_revision(revision_id)
649
def get_branch_transport(self, branch_format):
650
"""See BzrDir.get_branch_transport()."""
651
if branch_format is None:
652
return self.transport
654
branch_format.get_format_string()
655
except NotImplementedError:
656
return self.transport
657
raise errors.IncompatibleFormat(branch_format, self._format)
659
def get_repository_transport(self, repository_format):
660
"""See BzrDir.get_repository_transport()."""
661
if repository_format is None:
662
return self.transport
664
repository_format.get_format_string()
665
except NotImplementedError:
666
return self.transport
667
raise errors.IncompatibleFormat(repository_format, self._format)
669
def get_workingtree_transport(self, workingtree_format):
670
"""See BzrDir.get_workingtree_transport()."""
671
if workingtree_format is None:
672
return self.transport
674
workingtree_format.get_format_string()
675
except NotImplementedError:
676
return self.transport
677
raise errors.IncompatibleFormat(workingtree_format, self._format)
679
def needs_format_conversion(self, format=None):
680
"""See BzrDir.needs_format_conversion()."""
681
# if the format is not the same as the system default,
682
# an upgrade is needed.
684
format = BzrDirFormat.get_default_format()
685
return not isinstance(self._format, format.__class__)
687
def open_branch(self, unsupported=False):
688
"""See BzrDir.open_branch."""
689
from bzrlib.branch import BzrBranchFormat4
690
format = BzrBranchFormat4()
691
self._check_supported(format, unsupported)
692
return format.open(self, _found=True)
694
def sprout(self, url, revision_id=None, basis=None):
695
"""See BzrDir.sprout()."""
696
from bzrlib.workingtree import WorkingTreeFormat2
698
result = self._format._initialize_for_clone(url)
699
basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
701
self.open_repository().clone(result, revision_id=revision_id, basis=basis_repo)
702
except errors.NoRepositoryPresent:
705
self.open_branch().sprout(result, revision_id=revision_id)
706
except errors.NotBranchError:
708
# we always want a working tree
709
WorkingTreeFormat2().initialize(result)
713
class BzrDir4(BzrDirPreSplitOut):
714
"""A .bzr version 4 control object.
716
This is a deprecated format and may be removed after sept 2006.
719
def create_repository(self, shared=False):
720
"""See BzrDir.create_repository."""
721
return self._format.repository_format.initialize(self, shared)
723
def needs_format_conversion(self, format=None):
724
"""Format 4 dirs are always in need of conversion."""
727
def open_repository(self):
728
"""See BzrDir.open_repository."""
729
from bzrlib.repository import RepositoryFormat4
730
return RepositoryFormat4().open(self, _found=True)
733
class BzrDir5(BzrDirPreSplitOut):
734
"""A .bzr version 5 control object.
736
This is a deprecated format and may be removed after sept 2006.
739
def open_repository(self):
740
"""See BzrDir.open_repository."""
741
from bzrlib.repository import RepositoryFormat5
742
return RepositoryFormat5().open(self, _found=True)
744
def open_workingtree(self, _unsupported=False):
745
"""See BzrDir.create_workingtree."""
746
from bzrlib.workingtree import WorkingTreeFormat2
747
return WorkingTreeFormat2().open(self, _found=True)
750
class BzrDir6(BzrDirPreSplitOut):
751
"""A .bzr version 6 control object.
753
This is a deprecated format and may be removed after sept 2006.
756
def open_repository(self):
757
"""See BzrDir.open_repository."""
758
from bzrlib.repository import RepositoryFormat6
759
return RepositoryFormat6().open(self, _found=True)
761
def open_workingtree(self, _unsupported=False):
762
"""See BzrDir.create_workingtree."""
763
from bzrlib.workingtree import WorkingTreeFormat2
764
return WorkingTreeFormat2().open(self, _found=True)
767
class BzrDirMeta1(BzrDir):
768
"""A .bzr meta version 1 control object.
770
This is the first control object where the
771
individual aspects are really split out: there are separate repository,
772
workingtree and branch subdirectories and any subset of the three can be
773
present within a BzrDir.
776
def can_convert_format(self):
777
"""See BzrDir.can_convert_format()."""
780
def create_branch(self):
781
"""See BzrDir.create_branch."""
782
from bzrlib.branch import BranchFormat
783
return BranchFormat.get_default_format().initialize(self)
785
def create_repository(self, shared=False):
786
"""See BzrDir.create_repository."""
787
return self._format.repository_format.initialize(self, shared)
789
def create_workingtree(self, revision_id=None):
790
"""See BzrDir.create_workingtree."""
791
from bzrlib.workingtree import WorkingTreeFormat
792
return WorkingTreeFormat.get_default_format().initialize(self, revision_id)
794
def _get_mkdir_mode(self):
795
"""Figure out the mode to use when creating a bzrdir subdir."""
796
temp_control = LockableFiles(self.transport, '', TransportLock)
797
return temp_control._dir_mode
799
def get_branch_transport(self, branch_format):
800
"""See BzrDir.get_branch_transport()."""
801
if branch_format is None:
802
return self.transport.clone('branch')
804
branch_format.get_format_string()
805
except NotImplementedError:
806
raise errors.IncompatibleFormat(branch_format, self._format)
808
self.transport.mkdir('branch', mode=self._get_mkdir_mode())
809
except errors.FileExists:
811
return self.transport.clone('branch')
813
def get_repository_transport(self, repository_format):
814
"""See BzrDir.get_repository_transport()."""
815
if repository_format is None:
816
return self.transport.clone('repository')
818
repository_format.get_format_string()
819
except NotImplementedError:
820
raise errors.IncompatibleFormat(repository_format, self._format)
822
self.transport.mkdir('repository', mode=self._get_mkdir_mode())
823
except errors.FileExists:
825
return self.transport.clone('repository')
827
def get_workingtree_transport(self, workingtree_format):
828
"""See BzrDir.get_workingtree_transport()."""
829
if workingtree_format is None:
830
return self.transport.clone('checkout')
832
workingtree_format.get_format_string()
833
except NotImplementedError:
834
raise errors.IncompatibleFormat(workingtree_format, self._format)
836
self.transport.mkdir('checkout', mode=self._get_mkdir_mode())
837
except errors.FileExists:
839
return self.transport.clone('checkout')
841
def needs_format_conversion(self, format=None):
842
"""See BzrDir.needs_format_conversion()."""
844
format = BzrDirFormat.get_default_format()
845
if not isinstance(self._format, format.__class__):
846
# it is not a meta dir format, conversion is needed.
848
# we might want to push this down to the repository?
850
if not isinstance(self.open_repository()._format,
851
format.repository_format.__class__):
852
# the repository needs an upgrade.
854
except errors.NoRepositoryPresent:
856
# currently there are no other possible conversions for meta1 formats.
859
def open_branch(self, unsupported=False):
860
"""See BzrDir.open_branch."""
861
from bzrlib.branch import BranchFormat
862
format = BranchFormat.find_format(self)
863
self._check_supported(format, unsupported)
864
return format.open(self, _found=True)
866
def open_repository(self, unsupported=False):
867
"""See BzrDir.open_repository."""
868
from bzrlib.repository import RepositoryFormat
869
format = RepositoryFormat.find_format(self)
870
self._check_supported(format, unsupported)
871
return format.open(self, _found=True)
873
def open_workingtree(self, unsupported=False):
874
"""See BzrDir.open_workingtree."""
875
from bzrlib.workingtree import WorkingTreeFormat
876
format = WorkingTreeFormat.find_format(self)
877
self._check_supported(format, unsupported)
878
return format.open(self, _found=True)
881
class BzrDirFormat(object):
882
"""An encapsulation of the initialization and open routines for a format.
884
Formats provide three things:
885
* An initialization routine,
889
Formats are placed in an dict by their format string for reference
890
during bzrdir opening. These should be subclasses of BzrDirFormat
893
Once a format is deprecated, just deprecate the initialize and open
894
methods on the format class. Do not deprecate the object, as the
895
object will be created every system load.
898
_default_format = None
899
"""The default format used for new .bzr dirs."""
902
"""The known formats."""
904
_lock_file_name = 'branch-lock'
906
# _lock_class must be set in subclasses to the lock type, typ.
907
# TransportLock or LockDir
910
def find_format(klass, transport):
911
"""Return the format registered for URL."""
913
format_string = transport.get(".bzr/branch-format").read()
914
return klass._formats[format_string]
915
except errors.NoSuchFile:
916
raise errors.NotBranchError(path=transport.base)
918
raise errors.UnknownFormatError(format_string)
921
def get_default_format(klass):
922
"""Return the current default format."""
923
return klass._default_format
925
def get_format_string(self):
926
"""Return the ASCII format string that identifies this format."""
927
raise NotImplementedError(self.get_format_string)
929
def get_format_description(self):
930
"""Return the short description for this format."""
931
raise NotImplementedError(self.get_format_description)
933
def get_converter(self, format=None):
934
"""Return the converter to use to convert bzrdirs needing converts.
936
This returns a bzrlib.bzrdir.Converter object.
938
This should return the best upgrader to step this format towards the
939
current default format. In the case of plugins we can/shouold provide
940
some means for them to extend the range of returnable converters.
942
:param format: Optional format to override the default foramt of the
945
raise NotImplementedError(self.get_converter)
947
def initialize(self, url):
948
"""Create a bzr control dir at this url and return an opened copy.
950
Subclasses should typically override initialize_on_transport
951
instead of this method.
953
return self.initialize_on_transport(get_transport(url))
955
def initialize_on_transport(self, transport):
956
"""Initialize a new bzrdir in the base directory of a Transport."""
957
# Since we don'transport have a .bzr directory, inherit the
958
# mode from the root directory
959
temp_control = LockableFiles(transport, '', TransportLock)
960
temp_control._transport.mkdir('.bzr',
961
# FIXME: RBC 20060121 dont peek under
963
mode=temp_control._dir_mode)
964
file_mode = temp_control._file_mode
966
mutter('created control directory in ' + transport.base)
967
control = transport.clone('.bzr')
968
utf8_files = [('README',
969
"This is a Bazaar-NG control directory.\n"
970
"Do not change any files in this directory.\n"),
971
('branch-format', self.get_format_string()),
973
# NB: no need to escape relative paths that are url safe.
974
control_files = LockableFiles(control, self._lock_file_name,
976
control_files.create_lock()
977
control_files.lock_write()
979
for file, content in utf8_files:
980
control_files.put_utf8(file, content)
982
control_files.unlock()
983
return self.open(transport, _found=True)
985
def is_supported(self):
986
"""Is this format supported?
988
Supported formats must be initializable and openable.
989
Unsupported formats may not support initialization or committing or
990
some other features depending on the reason for not being supported.
994
def open(self, transport, _found=False):
995
"""Return an instance of this format for the dir transport points at.
997
_found is a private parameter, do not use it.
1000
assert isinstance(BzrDirFormat.find_format(transport),
1002
return self._open(transport)
1004
def _open(self, transport):
1005
"""Template method helper for opening BzrDirectories.
1007
This performs the actual open and any additional logic or parameter
1010
raise NotImplementedError(self._open)
1013
def register_format(klass, format):
1014
klass._formats[format.get_format_string()] = format
1017
def set_default_format(klass, format):
1018
klass._default_format = format
1021
return self.get_format_string()[:-1]
1024
def unregister_format(klass, format):
1025
assert klass._formats[format.get_format_string()] is format
1026
del klass._formats[format.get_format_string()]
1029
class BzrDirFormat4(BzrDirFormat):
1030
"""Bzr dir format 4.
1032
This format is a combined format for working tree, branch and repository.
1034
- Format 1 working trees [always]
1035
- Format 4 branches [always]
1036
- Format 4 repositories [always]
1038
This format is deprecated: it indexes texts using a text it which is
1039
removed in format 5; write support for this format has been removed.
1042
_lock_class = TransportLock
1044
def get_format_string(self):
1045
"""See BzrDirFormat.get_format_string()."""
1046
return "Bazaar-NG branch, format 0.0.4\n"
1048
def get_format_description(self):
1049
"""See BzrDirFormat.get_format_description()."""
1050
return "All-in-one format 4"
1052
def get_converter(self, format=None):
1053
"""See BzrDirFormat.get_converter()."""
1054
# there is one and only one upgrade path here.
1055
return ConvertBzrDir4To5()
1057
def initialize_on_transport(self, transport):
1058
"""Format 4 branches cannot be created."""
1059
raise errors.UninitializableFormat(self)
1061
def is_supported(self):
1062
"""Format 4 is not supported.
1064
It is not supported because the model changed from 4 to 5 and the
1065
conversion logic is expensive - so doing it on the fly was not
1070
def _open(self, transport):
1071
"""See BzrDirFormat._open."""
1072
return BzrDir4(transport, self)
1074
def __return_repository_format(self):
1075
"""Circular import protection."""
1076
from bzrlib.repository import RepositoryFormat4
1077
return RepositoryFormat4(self)
1078
repository_format = property(__return_repository_format)
1081
class BzrDirFormat5(BzrDirFormat):
1082
"""Bzr control format 5.
1084
This format is a combined format for working tree, branch and repository.
1086
- Format 2 working trees [always]
1087
- Format 4 branches [always]
1088
- Format 5 repositories [always]
1089
Unhashed stores in the repository.
1092
_lock_class = TransportLock
1094
def get_format_string(self):
1095
"""See BzrDirFormat.get_format_string()."""
1096
return "Bazaar-NG branch, format 5\n"
1098
def get_format_description(self):
1099
"""See BzrDirFormat.get_format_description()."""
1100
return "All-in-one format 5"
1102
def get_converter(self, format=None):
1103
"""See BzrDirFormat.get_converter()."""
1104
# there is one and only one upgrade path here.
1105
return ConvertBzrDir5To6()
1107
def _initialize_for_clone(self, url):
1108
return self.initialize_on_transport(get_transport(url), _cloning=True)
1110
def initialize_on_transport(self, transport, _cloning=False):
1111
"""Format 5 dirs always have working tree, branch and repository.
1113
Except when they are being cloned.
1115
from bzrlib.branch import BzrBranchFormat4
1116
from bzrlib.repository import RepositoryFormat5
1117
from bzrlib.workingtree import WorkingTreeFormat2
1118
result = (super(BzrDirFormat5, self).initialize_on_transport(transport))
1119
RepositoryFormat5().initialize(result, _internal=True)
1121
BzrBranchFormat4().initialize(result)
1122
WorkingTreeFormat2().initialize(result)
1125
def _open(self, transport):
1126
"""See BzrDirFormat._open."""
1127
return BzrDir5(transport, self)
1129
def __return_repository_format(self):
1130
"""Circular import protection."""
1131
from bzrlib.repository import RepositoryFormat5
1132
return RepositoryFormat5(self)
1133
repository_format = property(__return_repository_format)
1136
class BzrDirFormat6(BzrDirFormat):
1137
"""Bzr control format 6.
1139
This format is a combined format for working tree, branch and repository.
1141
- Format 2 working trees [always]
1142
- Format 4 branches [always]
1143
- Format 6 repositories [always]
1146
_lock_class = TransportLock
1148
def get_format_string(self):
1149
"""See BzrDirFormat.get_format_string()."""
1150
return "Bazaar-NG branch, format 6\n"
1152
def get_format_description(self):
1153
"""See BzrDirFormat.get_format_description()."""
1154
return "All-in-one format 6"
1156
def get_converter(self, format=None):
1157
"""See BzrDirFormat.get_converter()."""
1158
# there is one and only one upgrade path here.
1159
return ConvertBzrDir6ToMeta()
1161
def _initialize_for_clone(self, url):
1162
return self.initialize_on_transport(get_transport(url), _cloning=True)
1164
def initialize_on_transport(self, transport, _cloning=False):
1165
"""Format 6 dirs always have working tree, branch and repository.
1167
Except when they are being cloned.
1169
from bzrlib.branch import BzrBranchFormat4
1170
from bzrlib.repository import RepositoryFormat6
1171
from bzrlib.workingtree import WorkingTreeFormat2
1172
result = super(BzrDirFormat6, self).initialize_on_transport(transport)
1173
RepositoryFormat6().initialize(result, _internal=True)
1175
BzrBranchFormat4().initialize(result)
1177
WorkingTreeFormat2().initialize(result)
1178
except errors.NotLocalUrl:
1179
# emulate pre-check behaviour for working tree and silently
1184
def _open(self, transport):
1185
"""See BzrDirFormat._open."""
1186
return BzrDir6(transport, self)
1188
def __return_repository_format(self):
1189
"""Circular import protection."""
1190
from bzrlib.repository import RepositoryFormat6
1191
return RepositoryFormat6(self)
1192
repository_format = property(__return_repository_format)
1195
class BzrDirMetaFormat1(BzrDirFormat):
1196
"""Bzr meta control format 1
1198
This is the first format with split out working tree, branch and repository
1201
- Format 3 working trees [optional]
1202
- Format 5 branches [optional]
1203
- Format 7 repositories [optional]
1206
_lock_class = LockDir
1208
def get_converter(self, format=None):
1209
"""See BzrDirFormat.get_converter()."""
1211
format = BzrDirFormat.get_default_format()
1212
if not isinstance(self, format.__class__):
1213
# converting away from metadir is not implemented
1214
raise NotImplementedError(self.get_converter)
1215
return ConvertMetaToMeta(format)
1217
def get_format_string(self):
1218
"""See BzrDirFormat.get_format_string()."""
1219
return "Bazaar-NG meta directory, format 1\n"
1221
def get_format_description(self):
1222
"""See BzrDirFormat.get_format_description()."""
1223
return "Meta directory format 1"
1225
def _open(self, transport):
1226
"""See BzrDirFormat._open."""
1227
return BzrDirMeta1(transport, self)
1229
def __return_repository_format(self):
1230
"""Circular import protection."""
1231
if getattr(self, '_repository_format', None):
1232
return self._repository_format
1233
from bzrlib.repository import RepositoryFormat
1234
return RepositoryFormat.get_default_format()
1236
def __set_repository_format(self, value):
1237
"""Allow changint the repository format for metadir formats."""
1238
self._repository_format = value
1240
repository_format = property(__return_repository_format, __set_repository_format)
1243
BzrDirFormat.register_format(BzrDirFormat4())
1244
BzrDirFormat.register_format(BzrDirFormat5())
1245
BzrDirFormat.register_format(BzrDirFormat6())
1246
__default_format = BzrDirMetaFormat1()
1247
BzrDirFormat.register_format(__default_format)
1248
BzrDirFormat.set_default_format(__default_format)
1251
class BzrDirTestProviderAdapter(object):
1252
"""A tool to generate a suite testing multiple bzrdir formats at once.
1254
This is done by copying the test once for each transport and injecting
1255
the transport_server, transport_readonly_server, and bzrdir_format
1256
classes into each copy. Each copy is also given a new id() to make it
1260
def __init__(self, transport_server, transport_readonly_server, formats):
1261
self._transport_server = transport_server
1262
self._transport_readonly_server = transport_readonly_server
1263
self._formats = formats
1265
def adapt(self, test):
1266
result = TestSuite()
1267
for format in self._formats:
1268
new_test = deepcopy(test)
1269
new_test.transport_server = self._transport_server
1270
new_test.transport_readonly_server = self._transport_readonly_server
1271
new_test.bzrdir_format = format
1272
def make_new_test_id():
1273
new_id = "%s(%s)" % (new_test.id(), format.__class__.__name__)
1274
return lambda: new_id
1275
new_test.id = make_new_test_id()
1276
result.addTest(new_test)
1280
class ScratchDir(BzrDir6):
1281
"""Special test class: a bzrdir that cleans up itself..
1283
>>> d = ScratchDir()
1284
>>> base = d.transport.base
1287
>>> b.transport.__del__()
1292
def __init__(self, files=[], dirs=[], transport=None):
1293
"""Make a test branch.
1295
This creates a temporary directory and runs init-tree in it.
1297
If any files are listed, they are created in the working copy.
1299
if transport is None:
1300
transport = bzrlib.transport.local.ScratchTransport()
1301
# local import for scope restriction
1302
BzrDirFormat6().initialize(transport.base)
1303
super(ScratchDir, self).__init__(transport, BzrDirFormat6())
1304
self.create_repository()
1305
self.create_branch()
1306
self.create_workingtree()
1308
super(ScratchDir, self).__init__(transport, BzrDirFormat6())
1310
# BzrBranch creates a clone to .bzr and then forgets about the
1311
# original transport. A ScratchTransport() deletes itself and
1312
# everything underneath it when it goes away, so we need to
1313
# grab a local copy to prevent that from happening
1314
self._transport = transport
1317
self._transport.mkdir(d)
1320
self._transport.put(f, 'content of %s' % f)
1324
>>> orig = ScratchDir(files=["file1", "file2"])
1325
>>> os.listdir(orig.base)
1326
[u'.bzr', u'file1', u'file2']
1327
>>> clone = orig.clone()
1328
>>> if os.name != 'nt':
1329
... os.path.samefile(orig.base, clone.base)
1331
... orig.base == clone.base
1334
>>> os.listdir(clone.base)
1335
[u'.bzr', u'file1', u'file2']
1337
from shutil import copytree
1338
from bzrlib.osutils import mkdtemp
1341
copytree(self.base, base, symlinks=True)
1343
transport=bzrlib.transport.local.ScratchTransport(base))
1346
class Converter(object):
1347
"""Converts a disk format object from one format to another."""
1349
def convert(self, to_convert, pb):
1350
"""Perform the conversion of to_convert, giving feedback via pb.
1352
:param to_convert: The disk object to convert.
1353
:param pb: a progress bar to use for progress information.
1356
def step(self, message):
1357
"""Update the pb by a step."""
1359
self.pb.update(message, self.count, self.total)
1362
class ConvertBzrDir4To5(Converter):
1363
"""Converts format 4 bzr dirs to format 5."""
1366
super(ConvertBzrDir4To5, self).__init__()
1367
self.converted_revs = set()
1368
self.absent_revisions = set()
1372
def convert(self, to_convert, pb):
1373
"""See Converter.convert()."""
1374
self.bzrdir = to_convert
1376
self.pb.note('starting upgrade from format 4 to 5')
1377
if isinstance(self.bzrdir.transport, LocalTransport):
1378
self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
1379
self._convert_to_weaves()
1380
return BzrDir.open(self.bzrdir.root_transport.base)
1382
def _convert_to_weaves(self):
1383
self.pb.note('note: upgrade may be faster if all store files are ungzipped first')
1386
stat = self.bzrdir.transport.stat('weaves')
1387
if not S_ISDIR(stat.st_mode):
1388
self.bzrdir.transport.delete('weaves')
1389
self.bzrdir.transport.mkdir('weaves')
1390
except errors.NoSuchFile:
1391
self.bzrdir.transport.mkdir('weaves')
1392
# deliberately not a WeaveFile as we want to build it up slowly.
1393
self.inv_weave = Weave('inventory')
1394
# holds in-memory weaves for all files
1395
self.text_weaves = {}
1396
self.bzrdir.transport.delete('branch-format')
1397
self.branch = self.bzrdir.open_branch()
1398
self._convert_working_inv()
1399
rev_history = self.branch.revision_history()
1400
# to_read is a stack holding the revisions we still need to process;
1401
# appending to it adds new highest-priority revisions
1402
self.known_revisions = set(rev_history)
1403
self.to_read = rev_history[-1:]
1405
rev_id = self.to_read.pop()
1406
if (rev_id not in self.revisions
1407
and rev_id not in self.absent_revisions):
1408
self._load_one_rev(rev_id)
1410
to_import = self._make_order()
1411
for i, rev_id in enumerate(to_import):
1412
self.pb.update('converting revision', i, len(to_import))
1413
self._convert_one_rev(rev_id)
1415
self._write_all_weaves()
1416
self._write_all_revs()
1417
self.pb.note('upgraded to weaves:')
1418
self.pb.note(' %6d revisions and inventories', len(self.revisions))
1419
self.pb.note(' %6d revisions not present', len(self.absent_revisions))
1420
self.pb.note(' %6d texts', self.text_count)
1421
self._cleanup_spare_files_after_format4()
1422
self.branch.control_files.put_utf8('branch-format', BzrDirFormat5().get_format_string())
1424
def _cleanup_spare_files_after_format4(self):
1425
# FIXME working tree upgrade foo.
1426
for n in 'merged-patches', 'pending-merged-patches':
1428
## assert os.path.getsize(p) == 0
1429
self.bzrdir.transport.delete(n)
1430
except errors.NoSuchFile:
1432
self.bzrdir.transport.delete_tree('inventory-store')
1433
self.bzrdir.transport.delete_tree('text-store')
1435
def _convert_working_inv(self):
1436
inv = serializer_v4.read_inventory(self.branch.control_files.get('inventory'))
1437
new_inv_xml = serializer_v5.write_inventory_to_string(inv)
1438
# FIXME inventory is a working tree change.
1439
self.branch.control_files.put('inventory', new_inv_xml)
1441
def _write_all_weaves(self):
1442
controlweaves = WeaveStore(self.bzrdir.transport, prefixed=False)
1443
weave_transport = self.bzrdir.transport.clone('weaves')
1444
weaves = WeaveStore(weave_transport, prefixed=False)
1445
transaction = WriteTransaction()
1449
for file_id, file_weave in self.text_weaves.items():
1450
self.pb.update('writing weave', i, len(self.text_weaves))
1451
weaves._put_weave(file_id, file_weave, transaction)
1453
self.pb.update('inventory', 0, 1)
1454
controlweaves._put_weave('inventory', self.inv_weave, transaction)
1455
self.pb.update('inventory', 1, 1)
1459
def _write_all_revs(self):
1460
"""Write all revisions out in new form."""
1461
self.bzrdir.transport.delete_tree('revision-store')
1462
self.bzrdir.transport.mkdir('revision-store')
1463
revision_transport = self.bzrdir.transport.clone('revision-store')
1465
_revision_store = TextRevisionStore(TextStore(revision_transport,
1469
transaction = bzrlib.transactions.WriteTransaction()
1470
for i, rev_id in enumerate(self.converted_revs):
1471
self.pb.update('write revision', i, len(self.converted_revs))
1472
_revision_store.add_revision(self.revisions[rev_id], transaction)
1476
def _load_one_rev(self, rev_id):
1477
"""Load a revision object into memory.
1479
Any parents not either loaded or abandoned get queued to be
1481
self.pb.update('loading revision',
1482
len(self.revisions),
1483
len(self.known_revisions))
1484
if not self.branch.repository.has_revision(rev_id):
1486
self.pb.note('revision {%s} not present in branch; '
1487
'will be converted as a ghost',
1489
self.absent_revisions.add(rev_id)
1491
rev = self.branch.repository._revision_store.get_revision(rev_id,
1492
self.branch.repository.get_transaction())
1493
for parent_id in rev.parent_ids:
1494
self.known_revisions.add(parent_id)
1495
self.to_read.append(parent_id)
1496
self.revisions[rev_id] = rev
1498
def _load_old_inventory(self, rev_id):
1499
assert rev_id not in self.converted_revs
1500
old_inv_xml = self.branch.repository.inventory_store.get(rev_id).read()
1501
inv = serializer_v4.read_inventory_from_string(old_inv_xml)
1502
rev = self.revisions[rev_id]
1503
if rev.inventory_sha1:
1504
assert rev.inventory_sha1 == sha_string(old_inv_xml), \
1505
'inventory sha mismatch for {%s}' % rev_id
1508
def _load_updated_inventory(self, rev_id):
1509
assert rev_id in self.converted_revs
1510
inv_xml = self.inv_weave.get_text(rev_id)
1511
inv = serializer_v5.read_inventory_from_string(inv_xml)
1514
def _convert_one_rev(self, rev_id):
1515
"""Convert revision and all referenced objects to new format."""
1516
rev = self.revisions[rev_id]
1517
inv = self._load_old_inventory(rev_id)
1518
present_parents = [p for p in rev.parent_ids
1519
if p not in self.absent_revisions]
1520
self._convert_revision_contents(rev, inv, present_parents)
1521
self._store_new_weave(rev, inv, present_parents)
1522
self.converted_revs.add(rev_id)
1524
def _store_new_weave(self, rev, inv, present_parents):
1525
# the XML is now updated with text versions
1529
if ie.kind == 'root_directory':
1531
assert hasattr(ie, 'revision'), \
1532
'no revision on {%s} in {%s}' % \
1533
(file_id, rev.revision_id)
1534
new_inv_xml = serializer_v5.write_inventory_to_string(inv)
1535
new_inv_sha1 = sha_string(new_inv_xml)
1536
self.inv_weave.add_lines(rev.revision_id,
1538
new_inv_xml.splitlines(True))
1539
rev.inventory_sha1 = new_inv_sha1
1541
def _convert_revision_contents(self, rev, inv, present_parents):
1542
"""Convert all the files within a revision.
1544
Also upgrade the inventory to refer to the text revision ids."""
1545
rev_id = rev.revision_id
1546
mutter('converting texts of revision {%s}',
1548
parent_invs = map(self._load_updated_inventory, present_parents)
1551
self._convert_file_version(rev, ie, parent_invs)
1553
def _convert_file_version(self, rev, ie, parent_invs):
1554
"""Convert one version of one file.
1556
The file needs to be added into the weave if it is a merge
1557
of >=2 parents or if it's changed from its parent.
1559
if ie.kind == 'root_directory':
1561
file_id = ie.file_id
1562
rev_id = rev.revision_id
1563
w = self.text_weaves.get(file_id)
1566
self.text_weaves[file_id] = w
1567
text_changed = False
1568
previous_entries = ie.find_previous_heads(parent_invs,
1572
for old_revision in previous_entries:
1573
# if this fails, its a ghost ?
1574
assert old_revision in self.converted_revs
1575
self.snapshot_ie(previous_entries, ie, w, rev_id)
1577
assert getattr(ie, 'revision', None) is not None
1579
def snapshot_ie(self, previous_revisions, ie, w, rev_id):
1580
# TODO: convert this logic, which is ~= snapshot to
1581
# a call to:. This needs the path figured out. rather than a work_tree
1582
# a v4 revision_tree can be given, or something that looks enough like
1583
# one to give the file content to the entry if it needs it.
1584
# and we need something that looks like a weave store for snapshot to
1586
#ie.snapshot(rev, PATH, previous_revisions, REVISION_TREE, InMemoryWeaveStore(self.text_weaves))
1587
if len(previous_revisions) == 1:
1588
previous_ie = previous_revisions.values()[0]
1589
if ie._unchanged(previous_ie):
1590
ie.revision = previous_ie.revision
1593
text = self.branch.repository.text_store.get(ie.text_id)
1594
file_lines = text.readlines()
1595
assert sha_strings(file_lines) == ie.text_sha1
1596
assert sum(map(len, file_lines)) == ie.text_size
1597
w.add_lines(rev_id, previous_revisions, file_lines)
1598
self.text_count += 1
1600
w.add_lines(rev_id, previous_revisions, [])
1601
ie.revision = rev_id
1603
def _make_order(self):
1604
"""Return a suitable order for importing revisions.
1606
The order must be such that an revision is imported after all
1607
its (present) parents.
1609
todo = set(self.revisions.keys())
1610
done = self.absent_revisions.copy()
1613
# scan through looking for a revision whose parents
1615
for rev_id in sorted(list(todo)):
1616
rev = self.revisions[rev_id]
1617
parent_ids = set(rev.parent_ids)
1618
if parent_ids.issubset(done):
1619
# can take this one now
1620
order.append(rev_id)
1626
class ConvertBzrDir5To6(Converter):
1627
"""Converts format 5 bzr dirs to format 6."""
1629
def convert(self, to_convert, pb):
1630
"""See Converter.convert()."""
1631
self.bzrdir = to_convert
1633
self.pb.note('starting upgrade from format 5 to 6')
1634
self._convert_to_prefixed()
1635
return BzrDir.open(self.bzrdir.root_transport.base)
1637
def _convert_to_prefixed(self):
1638
from bzrlib.store import TransportStore
1639
self.bzrdir.transport.delete('branch-format')
1640
for store_name in ["weaves", "revision-store"]:
1641
self.pb.note("adding prefixes to %s" % store_name)
1642
store_transport = self.bzrdir.transport.clone(store_name)
1643
store = TransportStore(store_transport, prefixed=True)
1644
for urlfilename in store_transport.list_dir('.'):
1645
filename = urlunescape(urlfilename)
1646
if (filename.endswith(".weave") or
1647
filename.endswith(".gz") or
1648
filename.endswith(".sig")):
1649
file_id = os.path.splitext(filename)[0]
1652
prefix_dir = store.hash_prefix(file_id)
1653
# FIXME keep track of the dirs made RBC 20060121
1655
store_transport.move(filename, prefix_dir + '/' + filename)
1656
except errors.NoSuchFile: # catches missing dirs strangely enough
1657
store_transport.mkdir(prefix_dir)
1658
store_transport.move(filename, prefix_dir + '/' + filename)
1659
self.bzrdir._control_files.put_utf8('branch-format', BzrDirFormat6().get_format_string())
1662
class ConvertBzrDir6ToMeta(Converter):
1663
"""Converts format 6 bzr dirs to metadirs."""
1665
def convert(self, to_convert, pb):
1666
"""See Converter.convert()."""
1667
self.bzrdir = to_convert
1670
self.total = 20 # the steps we know about
1671
self.garbage_inventories = []
1673
self.pb.note('starting upgrade from format 6 to metadir')
1674
self.bzrdir._control_files.put_utf8('branch-format', "Converting to format 6")
1675
# its faster to move specific files around than to open and use the apis...
1676
# first off, nuke ancestry.weave, it was never used.
1678
self.step('Removing ancestry.weave')
1679
self.bzrdir.transport.delete('ancestry.weave')
1680
except errors.NoSuchFile:
1682
# find out whats there
1683
self.step('Finding branch files')
1684
last_revision = self.bzrdir.open_branch().last_revision()
1685
bzrcontents = self.bzrdir.transport.list_dir('.')
1686
for name in bzrcontents:
1687
if name.startswith('basis-inventory.'):
1688
self.garbage_inventories.append(name)
1689
# create new directories for repository, working tree and branch
1690
self.dir_mode = self.bzrdir._control_files._dir_mode
1691
self.file_mode = self.bzrdir._control_files._file_mode
1692
repository_names = [('inventory.weave', True),
1693
('revision-store', True),
1695
self.step('Upgrading repository ')
1696
self.bzrdir.transport.mkdir('repository', mode=self.dir_mode)
1697
self.make_lock('repository')
1698
# we hard code the formats here because we are converting into
1699
# the meta format. The meta format upgrader can take this to a
1700
# future format within each component.
1701
self.put_format('repository', bzrlib.repository.RepositoryFormat7())
1702
for entry in repository_names:
1703
self.move_entry('repository', entry)
1705
self.step('Upgrading branch ')
1706
self.bzrdir.transport.mkdir('branch', mode=self.dir_mode)
1707
self.make_lock('branch')
1708
self.put_format('branch', bzrlib.branch.BzrBranchFormat5())
1709
branch_files = [('revision-history', True),
1710
('branch-name', True),
1712
for entry in branch_files:
1713
self.move_entry('branch', entry)
1715
self.step('Upgrading working tree')
1716
self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
1717
self.make_lock('checkout')
1718
self.put_format('checkout', bzrlib.workingtree.WorkingTreeFormat3())
1719
self.bzrdir.transport.delete_multi(self.garbage_inventories, self.pb)
1720
checkout_files = [('pending-merges', True),
1721
('inventory', True),
1722
('stat-cache', False)]
1723
for entry in checkout_files:
1724
self.move_entry('checkout', entry)
1725
if last_revision is not None:
1726
self.bzrdir._control_files.put_utf8('checkout/last-revision',
1728
self.bzrdir._control_files.put_utf8('branch-format', BzrDirMetaFormat1().get_format_string())
1729
return BzrDir.open(self.bzrdir.root_transport.base)
1731
def make_lock(self, name):
1732
"""Make a lock for the new control dir name."""
1733
self.step('Make %s lock' % name)
1734
ld = LockDir(self.bzrdir.transport,
1736
file_modebits=self.file_mode,
1737
dir_modebits=self.dir_mode)
1740
def move_entry(self, new_dir, entry):
1741
"""Move then entry name into new_dir."""
1743
mandatory = entry[1]
1744
self.step('Moving %s' % name)
1746
self.bzrdir.transport.move(name, '%s/%s' % (new_dir, name))
1747
except errors.NoSuchFile:
1751
def put_format(self, dirname, format):
1752
self.bzrdir._control_files.put_utf8('%s/format' % dirname, format.get_format_string())
1755
class ConvertMetaToMeta(Converter):
1756
"""Converts the components of metadirs."""
1758
def __init__(self, target_format):
1759
"""Create a metadir to metadir converter.
1761
:param target_format: The final metadir format that is desired.
1763
self.target_format = target_format
1765
def convert(self, to_convert, pb):
1766
"""See Converter.convert()."""
1767
self.bzrdir = to_convert
1771
self.step('checking repository format')
1773
repo = self.bzrdir.open_repository()
1774
except errors.NoRepositoryPresent:
1777
if not isinstance(repo._format, self.target_format.repository_format.__class__):
1778
from bzrlib.repository import CopyConverter
1779
self.pb.note('starting repository conversion')
1780
converter = CopyConverter(self.target_format.repository_format)
1781
converter.convert(repo, pb)