/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

  • Committer: Robert Collins
  • Date: 2006-05-09 05:36:32 UTC
  • mto: (1704.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 1706.
  • Revision ID: robertc@robertcollins.net-20060509053632-e606e04c2e78f123
Adjust test-of-tests to accomodate the global state of TEST_ROOT.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006 Canonical Ltd
 
2
 
 
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.
 
7
 
 
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.
 
12
 
 
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
 
16
 
 
17
"""BzrDir logic. The BzrDir is the basic control directory used by bzr.
 
18
 
 
19
At format 7 this was split out into Branch, Repository and Checkout control
 
20
directories.
 
21
"""
 
22
 
 
23
from copy import deepcopy
 
24
import os
 
25
from cStringIO import StringIO
 
26
from unittest import TestSuite
 
27
 
 
28
import bzrlib
 
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 (
 
34
                            abspath,
 
35
                            pathjoin,
 
36
                            safe_unicode,
 
37
                            sha_strings,
 
38
                            sha_string,
 
39
                            )
 
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
 
51
 
 
52
 
 
53
class BzrDir(object):
 
54
    """A .bzr control diretory.
 
55
    
 
56
    BzrDir instances let you create or open any of the things that can be
 
57
    found within .bzr - checkouts, branches and repositories.
 
58
    
 
59
    transport
 
60
        the transport which this bzr dir is rooted at (i.e. file:///.../.bzr/)
 
61
    root_transport
 
62
        a transport connected to the directory this bzr was opened from.
 
63
    """
 
64
 
 
65
    def break_lock(self):
 
66
        """Invoke break_lock on the first object in the bzrdir.
 
67
 
 
68
        If there is a tree, the tree is opened and break_lock() called.
 
69
        Otherwise, branch is tried, and finally repository.
 
70
        """
 
71
        try:
 
72
            thing_to_unlock = self.open_workingtree()
 
73
        except (errors.NotLocalUrl, errors.NoWorkingTree):
 
74
            try:
 
75
                thing_to_unlock = self.open_branch()
 
76
            except errors.NotBranchError:
 
77
                try:
 
78
                    thing_to_unlock = self.open_repository()
 
79
                except errors.NoRepositoryPresent:
 
80
                    return
 
81
        thing_to_unlock.break_lock()
 
82
 
 
83
    def can_convert_format(self):
 
84
        """Return true if this bzrdir is one whose format we can convert from."""
 
85
        return True
 
86
 
 
87
    @staticmethod
 
88
    def _check_supported(format, allow_unsupported):
 
89
        """Check whether format is a supported format.
 
90
 
 
91
        If allow_unsupported is True, this is a no-op.
 
92
        """
 
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'])
 
100
 
 
101
    def clone(self, url, revision_id=None, basis=None, force_new_repo=False):
 
102
        """Clone this bzrdir and its contents to url verbatim.
 
103
 
 
104
        If urls last component does not exist, it will be created.
 
105
 
 
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.
 
110
        """
 
111
        self._make_tail(url)
 
112
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
 
113
        result = self._format.initialize(url)
 
114
        try:
 
115
            local_repo = self.find_repository()
 
116
        except errors.NoRepositoryPresent:
 
117
            local_repo = None
 
118
        if local_repo:
 
119
            # may need to copy content in
 
120
            if force_new_repo:
 
121
                local_repo.clone(result, revision_id=revision_id, basis=basis_repo)
 
122
            else:
 
123
                try:
 
124
                    result_repo = result.find_repository()
 
125
                    # fetch content this dir needs.
 
126
                    if basis_repo:
 
127
                        # XXX FIXME RBC 20060214 need tests for this when the basis
 
128
                        # is incomplete
 
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
 
136
        #   clone it.
 
137
        try:
 
138
            self.open_branch().clone(result, revision_id=revision_id)
 
139
        except errors.NotBranchError:
 
140
            pass
 
141
        try:
 
142
            self.open_workingtree().clone(result, basis=basis_tree)
 
143
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
144
            pass
 
145
        return result
 
146
 
 
147
    def _get_basis_components(self, basis):
 
148
        """Retrieve the basis components that are available at basis."""
 
149
        if basis is None:
 
150
            return None, None, None
 
151
        try:
 
152
            basis_tree = basis.open_workingtree()
 
153
            basis_branch = basis_tree.branch
 
154
            basis_repo = basis_branch.repository
 
155
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
156
            basis_tree = None
 
157
            try:
 
158
                basis_branch = basis.open_branch()
 
159
                basis_repo = basis_branch.repository
 
160
            except errors.NotBranchError:
 
161
                basis_branch = None
 
162
                try:
 
163
                    basis_repo = basis.open_repository()
 
164
                except errors.NoRepositoryPresent:
 
165
                    basis_repo = None
 
166
        return basis_repo, basis_branch, basis_tree
 
167
 
 
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)
 
173
            try:
 
174
                t.mkdir(segments[-1])
 
175
            except errors.FileExists:
 
176
                pass
 
177
 
 
178
    @classmethod
 
179
    def create(cls, base):
 
180
        """Create a new BzrDir at the url 'base'.
 
181
        
 
182
        This will call the current default formats initialize with base
 
183
        as the only parameter.
 
184
 
 
185
        If you need a specific format, consider creating an instance
 
186
        of that and calling initialize().
 
187
        """
 
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)
 
195
            try:
 
196
                t.mkdir(segments[-1])
 
197
            except errors.FileExists:
 
198
                pass
 
199
        return BzrDirFormat.get_default_format().initialize(safe_unicode(base))
 
200
 
 
201
    def create_branch(self):
 
202
        """Create a branch in this BzrDir.
 
203
 
 
204
        The bzrdirs format will control what branch format is created.
 
205
        For more control see BranchFormatXX.create(a_bzrdir).
 
206
        """
 
207
        raise NotImplementedError(self.create_branch)
 
208
 
 
209
    @staticmethod
 
210
    def create_branch_and_repo(base, force_new_repo=False):
 
211
        """Create a new BzrDir, Branch and Repository at the url 'base'.
 
212
 
 
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
 
216
        preferentially.
 
217
 
 
218
        The created Branch object is returned.
 
219
 
 
220
        :param base: The URL to create the branch at.
 
221
        :param force_new_repo: If True a new repository is always created.
 
222
        """
 
223
        bzrdir = BzrDir.create(base)
 
224
        bzrdir._find_or_create_repository(force_new_repo)
 
225
        return bzrdir.create_branch()
 
226
 
 
227
    def _find_or_create_repository(self, force_new_repo):
 
228
        """Create a new repository if needed, returning the repository."""
 
229
        if force_new_repo:
 
230
            return self.create_repository()
 
231
        try:
 
232
            return self.find_repository()
 
233
        except errors.NoRepositoryPresent:
 
234
            return self.create_repository()
 
235
        
 
236
    @staticmethod
 
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'.
 
240
 
 
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
 
243
        not.
 
244
 
 
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
 
249
        is followed.
 
250
 
 
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.
 
255
 
 
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
 
261
        """
 
262
        if force_new_tree:
 
263
            # check for non local urls
 
264
            t = get_transport(safe_unicode(base))
 
265
            if not isinstance(t, LocalTransport):
 
266
                raise errors.NotLocalUrl(base)
 
267
        if format is None:
 
268
            bzrdir = BzrDir.create(base)
 
269
        else:
 
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):
 
275
            try:
 
276
                bzrdir.create_workingtree()
 
277
            except errors.NotLocalUrl:
 
278
                pass
 
279
        return result
 
280
        
 
281
    @staticmethod
 
282
    def create_repository(base, shared=False):
 
283
        """Create a new BzrDir and Repository at the url 'base'.
 
284
 
 
285
        This will use the current default BzrDirFormat, and use whatever 
 
286
        repository format that that uses for bzrdirformat.create_repository.
 
287
 
 
288
        ;param shared: Create a shared repository rather than a standalone
 
289
                       repository.
 
290
        The Repository object is returned.
 
291
 
 
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.
 
295
        """
 
296
        bzrdir = BzrDir.create(base)
 
297
        return bzrdir.create_repository()
 
298
 
 
299
    @staticmethod
 
300
    def create_standalone_workingtree(base):
 
301
        """Create a new BzrDir, WorkingTree, Branch and Repository at 'base'.
 
302
 
 
303
        'base' must be a local path or a file:// url.
 
304
 
 
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.
 
308
 
 
309
        The WorkingTree object is returned.
 
310
        """
 
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()
 
317
 
 
318
    def create_workingtree(self, revision_id=None):
 
319
        """Create a working tree at this BzrDir.
 
320
        
 
321
        revision_id: create it as of this revision id.
 
322
        """
 
323
        raise NotImplementedError(self.create_workingtree)
 
324
 
 
325
    def find_repository(self):
 
326
        """Find the repository that should be used for a_bzrdir.
 
327
 
 
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
 
330
        repository.
 
331
        """
 
332
        try:
 
333
            return self.open_repository()
 
334
        except errors.NoRepositoryPresent:
 
335
            pass
 
336
        next_transport = self.root_transport.clone('..')
 
337
        while True:
 
338
            try:
 
339
                found_bzrdir = BzrDir.open_containing_from_transport(
 
340
                    next_transport)[0]
 
341
            except errors.NotBranchError:
 
342
                raise errors.NoRepositoryPresent(self)
 
343
            try:
 
344
                repository = found_bzrdir.open_repository()
 
345
            except errors.NoRepositoryPresent:
 
346
                next_transport = found_bzrdir.root_transport.clone('..')
 
347
                continue
 
348
            if ((found_bzrdir.root_transport.base == 
 
349
                 self.root_transport.base) or repository.is_shared()):
 
350
                return repository
 
351
            else:
 
352
                raise errors.NoRepositoryPresent(self)
 
353
        raise errors.NoRepositoryPresent(self)
 
354
 
 
355
    def get_branch_transport(self, branch_format):
 
356
        """Get the transport for use by branch format in this BzrDir.
 
357
 
 
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.
 
361
 
 
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.
 
365
        """
 
366
        raise NotImplementedError(self.get_branch_transport)
 
367
        
 
368
    def get_repository_transport(self, repository_format):
 
369
        """Get the transport for use by repository format in this BzrDir.
 
370
 
 
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.
 
374
 
 
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.
 
378
        """
 
379
        raise NotImplementedError(self.get_repository_transport)
 
380
        
 
381
    def get_workingtree_transport(self, tree_format):
 
382
        """Get the transport for use by workingtree format in this BzrDir.
 
383
 
 
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.
 
387
 
 
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.
 
391
        """
 
392
        raise NotImplementedError(self.get_workingtree_transport)
 
393
        
 
394
    def __init__(self, _transport, _format):
 
395
        """Initialize a Bzr control dir object.
 
396
        
 
397
        Only really common logic should reside here, concrete classes should be
 
398
        made with varying behaviours.
 
399
 
 
400
        :param _format: the format that is creating this BzrDir instance.
 
401
        :param _transport: the transport this dir is based at.
 
402
        """
 
403
        self._format = _format
 
404
        self.transport = _transport.clone('.bzr')
 
405
        self.root_transport = _transport
 
406
 
 
407
    def needs_format_conversion(self, format=None):
 
408
        """Return true if this bzrdir needs convert_format run on it.
 
409
        
 
410
        For instance, if the repository format is out of date but the 
 
411
        branch and working tree are not, this should return True.
 
412
 
 
413
        :param format: Optional parameter indicating a specific desired
 
414
                       format we plan to arrive at.
 
415
        """
 
416
        raise NotImplementedError(self.needs_format_conversion)
 
417
 
 
418
    @staticmethod
 
419
    def open_unsupported(base):
 
420
        """Open a branch which is not supported."""
 
421
        return BzrDir.open(base, _unsupported=True)
 
422
        
 
423
    @staticmethod
 
424
    def open(base, _unsupported=False):
 
425
        """Open an existing bzrdir, rooted at 'base' (url)
 
426
        
 
427
        _unsupported is a private parameter to the BzrDir class.
 
428
        """
 
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)
 
434
 
 
435
    def open_branch(self, unsupported=False):
 
436
        """Open the branch object at this BzrDir if one is present.
 
437
 
 
438
        If unsupported is True, then no longer supported branch formats can
 
439
        still be opened.
 
440
        
 
441
        TODO: static convenience version of this?
 
442
        """
 
443
        raise NotImplementedError(self.open_branch)
 
444
 
 
445
    @staticmethod
 
446
    def open_containing(url):
 
447
        """Open an existing branch which contains url.
 
448
        
 
449
        :param url: url to search from.
 
450
        See open_containing_from_transport for more detail.
 
451
        """
 
452
        return BzrDir.open_containing_from_transport(get_transport(url))
 
453
    
 
454
    @staticmethod
 
455
    def open_containing_from_transport(a_transport):
 
456
        """Open an existing branch which contains a_transport.base
 
457
 
 
458
        This probes for a branch at a_transport, and searches upwards from there.
 
459
 
 
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.
 
465
        """
 
466
        # this gets the normalised url back. I.e. '.' -> the full path.
 
467
        url = a_transport.base
 
468
        while True:
 
469
            try:
 
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)
 
479
            a_transport = new_t
 
480
 
 
481
    def open_repository(self, _unsupported=False):
 
482
        """Open the repository object at this BzrDir if one is present.
 
483
 
 
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
 
486
        get at a repository.
 
487
 
 
488
        _unsupported is a private parameter, not part of the api.
 
489
        TODO: static convenience version of this?
 
490
        """
 
491
        raise NotImplementedError(self.open_repository)
 
492
 
 
493
    def open_workingtree(self, _unsupported=False):
 
494
        """Open the workingtree object at this BzrDir if one is present.
 
495
        
 
496
        TODO: static convenience version of this?
 
497
        """
 
498
        raise NotImplementedError(self.open_workingtree)
 
499
 
 
500
    def has_branch(self):
 
501
        """Tell if this bzrdir contains a branch.
 
502
        
 
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.) 
 
506
        """
 
507
        try:
 
508
            self.open_branch()
 
509
            return True
 
510
        except errors.NotBranchError:
 
511
            return False
 
512
 
 
513
    def has_workingtree(self):
 
514
        """Tell if this bzrdir contains a working tree.
 
515
 
 
516
        This will still raise an exception if the bzrdir has a workingtree that
 
517
        is remote & inaccessible.
 
518
        
 
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.) 
 
522
        """
 
523
        try:
 
524
            self.open_workingtree()
 
525
            return True
 
526
        except errors.NoWorkingTree:
 
527
            return False
 
528
 
 
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
 
531
        development.
 
532
 
 
533
        If urls last component does not exist, it will be created.
 
534
 
 
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
 
538
        created.
 
539
 
 
540
        if revision_id is not None, then the clone operation may tune
 
541
            itself to download less data.
 
542
        """
 
543
        self._make_tail(url)
 
544
        result = self._format.initialize(url)
 
545
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
 
546
        try:
 
547
            source_branch = self.open_branch()
 
548
            source_repository = source_branch.repository
 
549
        except errors.NotBranchError:
 
550
            source_branch = None
 
551
            try:
 
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
 
557
        if force_new_repo:
 
558
            result_repo = None
 
559
        else:
 
560
            try:
 
561
                result_repo = result.find_repository()
 
562
            except errors.NoRepositoryPresent:
 
563
                result_repo = None
 
564
        if source_repository is None and result_repo is not None:
 
565
            pass
 
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,
 
573
                                    basis=basis_repo)
 
574
        else:
 
575
            # fetch needed content into target.
 
576
            if basis_repo:
 
577
                # XXX FIXME RBC 20060214 need tests for this when the basis
 
578
                # is incomplete
 
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)
 
583
        else:
 
584
            result.create_branch()
 
585
        if result_repo is None or result_repo.make_working_trees():
 
586
            result.create_workingtree()
 
587
        return result
 
588
 
 
589
 
 
590
class BzrDirPreSplitOut(BzrDir):
 
591
    """A common class for the all-in-one formats."""
 
592
 
 
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)
 
601
 
 
602
    def break_lock(self):
 
603
        """Pre-splitout bzrdirs do not suffer from stale locks."""
 
604
        raise NotImplementedError(self.break_lock)
 
605
 
 
606
    def clone(self, url, revision_id=None, basis=None, force_new_repo=False):
 
607
        """See BzrDir.clone()."""
 
608
        from bzrlib.workingtree import WorkingTreeFormat2
 
609
        self._make_tail(url)
 
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)
 
614
        try:
 
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.
 
618
            try:
 
619
                WorkingTreeFormat2().initialize(result)
 
620
            except errors.NotLocalUrl:
 
621
                # but we canot do it for remote trees.
 
622
                pass
 
623
        return result
 
624
 
 
625
    def create_branch(self):
 
626
        """See BzrDir.create_branch."""
 
627
        return self.open_branch()
 
628
 
 
629
    def create_repository(self, shared=False):
 
630
        """See BzrDir.create_repository."""
 
631
        if shared:
 
632
            raise errors.IncompatibleFormat('shared repository', self._format)
 
633
        return self.open_repository()
 
634
 
 
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)
 
647
        return result
 
648
 
 
649
    def get_branch_transport(self, branch_format):
 
650
        """See BzrDir.get_branch_transport()."""
 
651
        if branch_format is None:
 
652
            return self.transport
 
653
        try:
 
654
            branch_format.get_format_string()
 
655
        except NotImplementedError:
 
656
            return self.transport
 
657
        raise errors.IncompatibleFormat(branch_format, self._format)
 
658
 
 
659
    def get_repository_transport(self, repository_format):
 
660
        """See BzrDir.get_repository_transport()."""
 
661
        if repository_format is None:
 
662
            return self.transport
 
663
        try:
 
664
            repository_format.get_format_string()
 
665
        except NotImplementedError:
 
666
            return self.transport
 
667
        raise errors.IncompatibleFormat(repository_format, self._format)
 
668
 
 
669
    def get_workingtree_transport(self, workingtree_format):
 
670
        """See BzrDir.get_workingtree_transport()."""
 
671
        if workingtree_format is None:
 
672
            return self.transport
 
673
        try:
 
674
            workingtree_format.get_format_string()
 
675
        except NotImplementedError:
 
676
            return self.transport
 
677
        raise errors.IncompatibleFormat(workingtree_format, self._format)
 
678
 
 
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.
 
683
        if format is None:
 
684
            format = BzrDirFormat.get_default_format()
 
685
        return not isinstance(self._format, format.__class__)
 
686
 
 
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)
 
693
 
 
694
    def sprout(self, url, revision_id=None, basis=None):
 
695
        """See BzrDir.sprout()."""
 
696
        from bzrlib.workingtree import WorkingTreeFormat2
 
697
        self._make_tail(url)
 
698
        result = self._format._initialize_for_clone(url)
 
699
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
 
700
        try:
 
701
            self.open_repository().clone(result, revision_id=revision_id, basis=basis_repo)
 
702
        except errors.NoRepositoryPresent:
 
703
            pass
 
704
        try:
 
705
            self.open_branch().sprout(result, revision_id=revision_id)
 
706
        except errors.NotBranchError:
 
707
            pass
 
708
        # we always want a working tree
 
709
        WorkingTreeFormat2().initialize(result)
 
710
        return result
 
711
 
 
712
 
 
713
class BzrDir4(BzrDirPreSplitOut):
 
714
    """A .bzr version 4 control object.
 
715
    
 
716
    This is a deprecated format and may be removed after sept 2006.
 
717
    """
 
718
 
 
719
    def create_repository(self, shared=False):
 
720
        """See BzrDir.create_repository."""
 
721
        return self._format.repository_format.initialize(self, shared)
 
722
 
 
723
    def needs_format_conversion(self, format=None):
 
724
        """Format 4 dirs are always in need of conversion."""
 
725
        return True
 
726
 
 
727
    def open_repository(self):
 
728
        """See BzrDir.open_repository."""
 
729
        from bzrlib.repository import RepositoryFormat4
 
730
        return RepositoryFormat4().open(self, _found=True)
 
731
 
 
732
 
 
733
class BzrDir5(BzrDirPreSplitOut):
 
734
    """A .bzr version 5 control object.
 
735
 
 
736
    This is a deprecated format and may be removed after sept 2006.
 
737
    """
 
738
 
 
739
    def open_repository(self):
 
740
        """See BzrDir.open_repository."""
 
741
        from bzrlib.repository import RepositoryFormat5
 
742
        return RepositoryFormat5().open(self, _found=True)
 
743
 
 
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)
 
748
 
 
749
 
 
750
class BzrDir6(BzrDirPreSplitOut):
 
751
    """A .bzr version 6 control object.
 
752
 
 
753
    This is a deprecated format and may be removed after sept 2006.
 
754
    """
 
755
 
 
756
    def open_repository(self):
 
757
        """See BzrDir.open_repository."""
 
758
        from bzrlib.repository import RepositoryFormat6
 
759
        return RepositoryFormat6().open(self, _found=True)
 
760
 
 
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)
 
765
 
 
766
 
 
767
class BzrDirMeta1(BzrDir):
 
768
    """A .bzr meta version 1 control object.
 
769
    
 
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.
 
774
    """
 
775
 
 
776
    def can_convert_format(self):
 
777
        """See BzrDir.can_convert_format()."""
 
778
        return True
 
779
 
 
780
    def create_branch(self):
 
781
        """See BzrDir.create_branch."""
 
782
        from bzrlib.branch import BranchFormat
 
783
        return BranchFormat.get_default_format().initialize(self)
 
784
 
 
785
    def create_repository(self, shared=False):
 
786
        """See BzrDir.create_repository."""
 
787
        return self._format.repository_format.initialize(self, shared)
 
788
 
 
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)
 
793
 
 
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
 
798
 
 
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')
 
803
        try:
 
804
            branch_format.get_format_string()
 
805
        except NotImplementedError:
 
806
            raise errors.IncompatibleFormat(branch_format, self._format)
 
807
        try:
 
808
            self.transport.mkdir('branch', mode=self._get_mkdir_mode())
 
809
        except errors.FileExists:
 
810
            pass
 
811
        return self.transport.clone('branch')
 
812
 
 
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')
 
817
        try:
 
818
            repository_format.get_format_string()
 
819
        except NotImplementedError:
 
820
            raise errors.IncompatibleFormat(repository_format, self._format)
 
821
        try:
 
822
            self.transport.mkdir('repository', mode=self._get_mkdir_mode())
 
823
        except errors.FileExists:
 
824
            pass
 
825
        return self.transport.clone('repository')
 
826
 
 
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')
 
831
        try:
 
832
            workingtree_format.get_format_string()
 
833
        except NotImplementedError:
 
834
            raise errors.IncompatibleFormat(workingtree_format, self._format)
 
835
        try:
 
836
            self.transport.mkdir('checkout', mode=self._get_mkdir_mode())
 
837
        except errors.FileExists:
 
838
            pass
 
839
        return self.transport.clone('checkout')
 
840
 
 
841
    def needs_format_conversion(self, format=None):
 
842
        """See BzrDir.needs_format_conversion()."""
 
843
        if format is None:
 
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.
 
847
            return True
 
848
        # we might want to push this down to the repository?
 
849
        try:
 
850
            if not isinstance(self.open_repository()._format,
 
851
                              format.repository_format.__class__):
 
852
                # the repository needs an upgrade.
 
853
                return True
 
854
        except errors.NoRepositoryPresent:
 
855
            pass
 
856
        # currently there are no other possible conversions for meta1 formats.
 
857
        return False
 
858
 
 
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)
 
865
 
 
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)
 
872
 
 
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)
 
879
 
 
880
 
 
881
class BzrDirFormat(object):
 
882
    """An encapsulation of the initialization and open routines for a format.
 
883
 
 
884
    Formats provide three things:
 
885
     * An initialization routine,
 
886
     * a format string,
 
887
     * an open routine.
 
888
 
 
889
    Formats are placed in an dict by their format string for reference 
 
890
    during bzrdir opening. These should be subclasses of BzrDirFormat
 
891
    for consistency.
 
892
 
 
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.
 
896
    """
 
897
 
 
898
    _default_format = None
 
899
    """The default format used for new .bzr dirs."""
 
900
 
 
901
    _formats = {}
 
902
    """The known formats."""
 
903
 
 
904
    _lock_file_name = 'branch-lock'
 
905
 
 
906
    # _lock_class must be set in subclasses to the lock type, typ.
 
907
    # TransportLock or LockDir
 
908
 
 
909
    @classmethod
 
910
    def find_format(klass, transport):
 
911
        """Return the format registered for URL."""
 
912
        try:
 
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)
 
917
        except KeyError:
 
918
            raise errors.UnknownFormatError(format_string)
 
919
 
 
920
    @classmethod
 
921
    def get_default_format(klass):
 
922
        """Return the current default format."""
 
923
        return klass._default_format
 
924
 
 
925
    def get_format_string(self):
 
926
        """Return the ASCII format string that identifies this format."""
 
927
        raise NotImplementedError(self.get_format_string)
 
928
 
 
929
    def get_format_description(self):
 
930
        """Return the short description for this format."""
 
931
        raise NotImplementedError(self.get_format_description)
 
932
 
 
933
    def get_converter(self, format=None):
 
934
        """Return the converter to use to convert bzrdirs needing converts.
 
935
 
 
936
        This returns a bzrlib.bzrdir.Converter object.
 
937
 
 
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.
 
941
 
 
942
        :param format: Optional format to override the default foramt of the 
 
943
                       library.
 
944
        """
 
945
        raise NotImplementedError(self.get_converter)
 
946
 
 
947
    def initialize(self, url):
 
948
        """Create a bzr control dir at this url and return an opened copy.
 
949
        
 
950
        Subclasses should typically override initialize_on_transport
 
951
        instead of this method.
 
952
        """
 
953
        return self.initialize_on_transport(get_transport(url))
 
954
 
 
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
 
962
                                      # the covers
 
963
                                      mode=temp_control._dir_mode)
 
964
        file_mode = temp_control._file_mode
 
965
        del temp_control
 
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()),
 
972
                      ]
 
973
        # NB: no need to escape relative paths that are url safe.
 
974
        control_files = LockableFiles(control, self._lock_file_name, 
 
975
                                      self._lock_class)
 
976
        control_files.create_lock()
 
977
        control_files.lock_write()
 
978
        try:
 
979
            for file, content in utf8_files:
 
980
                control_files.put_utf8(file, content)
 
981
        finally:
 
982
            control_files.unlock()
 
983
        return self.open(transport, _found=True)
 
984
 
 
985
    def is_supported(self):
 
986
        """Is this format supported?
 
987
 
 
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.
 
991
        """
 
992
        return True
 
993
 
 
994
    def open(self, transport, _found=False):
 
995
        """Return an instance of this format for the dir transport points at.
 
996
        
 
997
        _found is a private parameter, do not use it.
 
998
        """
 
999
        if not _found:
 
1000
            assert isinstance(BzrDirFormat.find_format(transport),
 
1001
                              self.__class__)
 
1002
        return self._open(transport)
 
1003
 
 
1004
    def _open(self, transport):
 
1005
        """Template method helper for opening BzrDirectories.
 
1006
 
 
1007
        This performs the actual open and any additional logic or parameter
 
1008
        passing.
 
1009
        """
 
1010
        raise NotImplementedError(self._open)
 
1011
 
 
1012
    @classmethod
 
1013
    def register_format(klass, format):
 
1014
        klass._formats[format.get_format_string()] = format
 
1015
 
 
1016
    @classmethod
 
1017
    def set_default_format(klass, format):
 
1018
        klass._default_format = format
 
1019
 
 
1020
    def __str__(self):
 
1021
        return self.get_format_string()[:-1]
 
1022
 
 
1023
    @classmethod
 
1024
    def unregister_format(klass, format):
 
1025
        assert klass._formats[format.get_format_string()] is format
 
1026
        del klass._formats[format.get_format_string()]
 
1027
 
 
1028
 
 
1029
class BzrDirFormat4(BzrDirFormat):
 
1030
    """Bzr dir format 4.
 
1031
 
 
1032
    This format is a combined format for working tree, branch and repository.
 
1033
    It has:
 
1034
     - Format 1 working trees [always]
 
1035
     - Format 4 branches [always]
 
1036
     - Format 4 repositories [always]
 
1037
 
 
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.
 
1040
    """
 
1041
 
 
1042
    _lock_class = TransportLock
 
1043
 
 
1044
    def get_format_string(self):
 
1045
        """See BzrDirFormat.get_format_string()."""
 
1046
        return "Bazaar-NG branch, format 0.0.4\n"
 
1047
 
 
1048
    def get_format_description(self):
 
1049
        """See BzrDirFormat.get_format_description()."""
 
1050
        return "All-in-one format 4"
 
1051
 
 
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()
 
1056
        
 
1057
    def initialize_on_transport(self, transport):
 
1058
        """Format 4 branches cannot be created."""
 
1059
        raise errors.UninitializableFormat(self)
 
1060
 
 
1061
    def is_supported(self):
 
1062
        """Format 4 is not supported.
 
1063
 
 
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 
 
1066
        feasible.
 
1067
        """
 
1068
        return False
 
1069
 
 
1070
    def _open(self, transport):
 
1071
        """See BzrDirFormat._open."""
 
1072
        return BzrDir4(transport, self)
 
1073
 
 
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)
 
1079
 
 
1080
 
 
1081
class BzrDirFormat5(BzrDirFormat):
 
1082
    """Bzr control format 5.
 
1083
 
 
1084
    This format is a combined format for working tree, branch and repository.
 
1085
    It has:
 
1086
     - Format 2 working trees [always] 
 
1087
     - Format 4 branches [always] 
 
1088
     - Format 5 repositories [always]
 
1089
       Unhashed stores in the repository.
 
1090
    """
 
1091
 
 
1092
    _lock_class = TransportLock
 
1093
 
 
1094
    def get_format_string(self):
 
1095
        """See BzrDirFormat.get_format_string()."""
 
1096
        return "Bazaar-NG branch, format 5\n"
 
1097
 
 
1098
    def get_format_description(self):
 
1099
        """See BzrDirFormat.get_format_description()."""
 
1100
        return "All-in-one format 5"
 
1101
 
 
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()
 
1106
 
 
1107
    def _initialize_for_clone(self, url):
 
1108
        return self.initialize_on_transport(get_transport(url), _cloning=True)
 
1109
        
 
1110
    def initialize_on_transport(self, transport, _cloning=False):
 
1111
        """Format 5 dirs always have working tree, branch and repository.
 
1112
        
 
1113
        Except when they are being cloned.
 
1114
        """
 
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)
 
1120
        if not _cloning:
 
1121
            BzrBranchFormat4().initialize(result)
 
1122
            WorkingTreeFormat2().initialize(result)
 
1123
        return result
 
1124
 
 
1125
    def _open(self, transport):
 
1126
        """See BzrDirFormat._open."""
 
1127
        return BzrDir5(transport, self)
 
1128
 
 
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)
 
1134
 
 
1135
 
 
1136
class BzrDirFormat6(BzrDirFormat):
 
1137
    """Bzr control format 6.
 
1138
 
 
1139
    This format is a combined format for working tree, branch and repository.
 
1140
    It has:
 
1141
     - Format 2 working trees [always] 
 
1142
     - Format 4 branches [always] 
 
1143
     - Format 6 repositories [always]
 
1144
    """
 
1145
 
 
1146
    _lock_class = TransportLock
 
1147
 
 
1148
    def get_format_string(self):
 
1149
        """See BzrDirFormat.get_format_string()."""
 
1150
        return "Bazaar-NG branch, format 6\n"
 
1151
 
 
1152
    def get_format_description(self):
 
1153
        """See BzrDirFormat.get_format_description()."""
 
1154
        return "All-in-one format 6"
 
1155
 
 
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()
 
1160
        
 
1161
    def _initialize_for_clone(self, url):
 
1162
        return self.initialize_on_transport(get_transport(url), _cloning=True)
 
1163
 
 
1164
    def initialize_on_transport(self, transport, _cloning=False):
 
1165
        """Format 6 dirs always have working tree, branch and repository.
 
1166
        
 
1167
        Except when they are being cloned.
 
1168
        """
 
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)
 
1174
        if not _cloning:
 
1175
            BzrBranchFormat4().initialize(result)
 
1176
            try:
 
1177
                WorkingTreeFormat2().initialize(result)
 
1178
            except errors.NotLocalUrl:
 
1179
                # emulate pre-check behaviour for working tree and silently 
 
1180
                # fail.
 
1181
                pass
 
1182
        return result
 
1183
 
 
1184
    def _open(self, transport):
 
1185
        """See BzrDirFormat._open."""
 
1186
        return BzrDir6(transport, self)
 
1187
 
 
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)
 
1193
 
 
1194
 
 
1195
class BzrDirMetaFormat1(BzrDirFormat):
 
1196
    """Bzr meta control format 1
 
1197
 
 
1198
    This is the first format with split out working tree, branch and repository
 
1199
    disk storage.
 
1200
    It has:
 
1201
     - Format 3 working trees [optional]
 
1202
     - Format 5 branches [optional]
 
1203
     - Format 7 repositories [optional]
 
1204
    """
 
1205
 
 
1206
    _lock_class = LockDir
 
1207
 
 
1208
    def get_converter(self, format=None):
 
1209
        """See BzrDirFormat.get_converter()."""
 
1210
        if format is None:
 
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)
 
1216
 
 
1217
    def get_format_string(self):
 
1218
        """See BzrDirFormat.get_format_string()."""
 
1219
        return "Bazaar-NG meta directory, format 1\n"
 
1220
 
 
1221
    def get_format_description(self):
 
1222
        """See BzrDirFormat.get_format_description()."""
 
1223
        return "Meta directory format 1"
 
1224
 
 
1225
    def _open(self, transport):
 
1226
        """See BzrDirFormat._open."""
 
1227
        return BzrDirMeta1(transport, self)
 
1228
 
 
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()
 
1235
 
 
1236
    def __set_repository_format(self, value):
 
1237
        """Allow changint the repository format for metadir formats."""
 
1238
        self._repository_format = value
 
1239
 
 
1240
    repository_format = property(__return_repository_format, __set_repository_format)
 
1241
 
 
1242
 
 
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)
 
1249
 
 
1250
 
 
1251
class BzrDirTestProviderAdapter(object):
 
1252
    """A tool to generate a suite testing multiple bzrdir formats at once.
 
1253
 
 
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
 
1257
    easy to identify.
 
1258
    """
 
1259
 
 
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
 
1264
    
 
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)
 
1277
        return result
 
1278
 
 
1279
 
 
1280
class ScratchDir(BzrDir6):
 
1281
    """Special test class: a bzrdir that cleans up itself..
 
1282
 
 
1283
    >>> d = ScratchDir()
 
1284
    >>> base = d.transport.base
 
1285
    >>> isdir(base)
 
1286
    True
 
1287
    >>> b.transport.__del__()
 
1288
    >>> isdir(base)
 
1289
    False
 
1290
    """
 
1291
 
 
1292
    def __init__(self, files=[], dirs=[], transport=None):
 
1293
        """Make a test branch.
 
1294
 
 
1295
        This creates a temporary directory and runs init-tree in it.
 
1296
 
 
1297
        If any files are listed, they are created in the working copy.
 
1298
        """
 
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()
 
1307
        else:
 
1308
            super(ScratchDir, self).__init__(transport, BzrDirFormat6())
 
1309
 
 
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
 
1315
 
 
1316
        for d in dirs:
 
1317
            self._transport.mkdir(d)
 
1318
            
 
1319
        for f in files:
 
1320
            self._transport.put(f, 'content of %s' % f)
 
1321
 
 
1322
    def clone(self):
 
1323
        """
 
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)
 
1330
        ... else:
 
1331
        ...   orig.base == clone.base
 
1332
        ...
 
1333
        False
 
1334
        >>> os.listdir(clone.base)
 
1335
        [u'.bzr', u'file1', u'file2']
 
1336
        """
 
1337
        from shutil import copytree
 
1338
        from bzrlib.osutils import mkdtemp
 
1339
        base = mkdtemp()
 
1340
        os.rmdir(base)
 
1341
        copytree(self.base, base, symlinks=True)
 
1342
        return ScratchDir(
 
1343
            transport=bzrlib.transport.local.ScratchTransport(base))
 
1344
 
 
1345
 
 
1346
class Converter(object):
 
1347
    """Converts a disk format object from one format to another."""
 
1348
 
 
1349
    def convert(self, to_convert, pb):
 
1350
        """Perform the conversion of to_convert, giving feedback via pb.
 
1351
 
 
1352
        :param to_convert: The disk object to convert.
 
1353
        :param pb: a progress bar to use for progress information.
 
1354
        """
 
1355
 
 
1356
    def step(self, message):
 
1357
        """Update the pb by a step."""
 
1358
        self.count +=1
 
1359
        self.pb.update(message, self.count, self.total)
 
1360
 
 
1361
 
 
1362
class ConvertBzrDir4To5(Converter):
 
1363
    """Converts format 4 bzr dirs to format 5."""
 
1364
 
 
1365
    def __init__(self):
 
1366
        super(ConvertBzrDir4To5, self).__init__()
 
1367
        self.converted_revs = set()
 
1368
        self.absent_revisions = set()
 
1369
        self.text_count = 0
 
1370
        self.revisions = {}
 
1371
        
 
1372
    def convert(self, to_convert, pb):
 
1373
        """See Converter.convert()."""
 
1374
        self.bzrdir = to_convert
 
1375
        self.pb = pb
 
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)
 
1381
 
 
1382
    def _convert_to_weaves(self):
 
1383
        self.pb.note('note: upgrade may be faster if all store files are ungzipped first')
 
1384
        try:
 
1385
            # TODO permissions
 
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:]
 
1404
        while self.to_read:
 
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)
 
1409
        self.pb.clear()
 
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)
 
1414
        self.pb.clear()
 
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())
 
1423
 
 
1424
    def _cleanup_spare_files_after_format4(self):
 
1425
        # FIXME working tree upgrade foo.
 
1426
        for n in 'merged-patches', 'pending-merged-patches':
 
1427
            try:
 
1428
                ## assert os.path.getsize(p) == 0
 
1429
                self.bzrdir.transport.delete(n)
 
1430
            except errors.NoSuchFile:
 
1431
                pass
 
1432
        self.bzrdir.transport.delete_tree('inventory-store')
 
1433
        self.bzrdir.transport.delete_tree('text-store')
 
1434
 
 
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)
 
1440
 
 
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()
 
1446
 
 
1447
        try:
 
1448
            i = 0
 
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)
 
1452
                i += 1
 
1453
            self.pb.update('inventory', 0, 1)
 
1454
            controlweaves._put_weave('inventory', self.inv_weave, transaction)
 
1455
            self.pb.update('inventory', 1, 1)
 
1456
        finally:
 
1457
            self.pb.clear()
 
1458
 
 
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')
 
1464
        # TODO permissions
 
1465
        _revision_store = TextRevisionStore(TextStore(revision_transport,
 
1466
                                                      prefixed=False,
 
1467
                                                      compressed=True))
 
1468
        try:
 
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)
 
1473
        finally:
 
1474
            self.pb.clear()
 
1475
            
 
1476
    def _load_one_rev(self, rev_id):
 
1477
        """Load a revision object into memory.
 
1478
 
 
1479
        Any parents not either loaded or abandoned get queued to be
 
1480
        loaded."""
 
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):
 
1485
            self.pb.clear()
 
1486
            self.pb.note('revision {%s} not present in branch; '
 
1487
                         'will be converted as a ghost',
 
1488
                         rev_id)
 
1489
            self.absent_revisions.add(rev_id)
 
1490
        else:
 
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
 
1497
 
 
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
 
1506
        return inv
 
1507
 
 
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)
 
1512
        return inv
 
1513
 
 
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)
 
1523
 
 
1524
    def _store_new_weave(self, rev, inv, present_parents):
 
1525
        # the XML is now updated with text versions
 
1526
        if __debug__:
 
1527
            for file_id in inv:
 
1528
                ie = inv[file_id]
 
1529
                if ie.kind == 'root_directory':
 
1530
                    continue
 
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, 
 
1537
                                 present_parents,
 
1538
                                 new_inv_xml.splitlines(True))
 
1539
        rev.inventory_sha1 = new_inv_sha1
 
1540
 
 
1541
    def _convert_revision_contents(self, rev, inv, present_parents):
 
1542
        """Convert all the files within a revision.
 
1543
 
 
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}',
 
1547
               rev_id)
 
1548
        parent_invs = map(self._load_updated_inventory, present_parents)
 
1549
        for file_id in inv:
 
1550
            ie = inv[file_id]
 
1551
            self._convert_file_version(rev, ie, parent_invs)
 
1552
 
 
1553
    def _convert_file_version(self, rev, ie, parent_invs):
 
1554
        """Convert one version of one file.
 
1555
 
 
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.
 
1558
        """
 
1559
        if ie.kind == 'root_directory':
 
1560
            return
 
1561
        file_id = ie.file_id
 
1562
        rev_id = rev.revision_id
 
1563
        w = self.text_weaves.get(file_id)
 
1564
        if w is None:
 
1565
            w = Weave(file_id)
 
1566
            self.text_weaves[file_id] = w
 
1567
        text_changed = False
 
1568
        previous_entries = ie.find_previous_heads(parent_invs,
 
1569
                                                  None,
 
1570
                                                  None,
 
1571
                                                  entry_vf=w)
 
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)
 
1576
        del ie.text_id
 
1577
        assert getattr(ie, 'revision', None) is not None
 
1578
 
 
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 
 
1585
        # save against.
 
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
 
1591
                return
 
1592
        if ie.has_text():
 
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
 
1599
        else:
 
1600
            w.add_lines(rev_id, previous_revisions, [])
 
1601
        ie.revision = rev_id
 
1602
 
 
1603
    def _make_order(self):
 
1604
        """Return a suitable order for importing revisions.
 
1605
 
 
1606
        The order must be such that an revision is imported after all
 
1607
        its (present) parents.
 
1608
        """
 
1609
        todo = set(self.revisions.keys())
 
1610
        done = self.absent_revisions.copy()
 
1611
        order = []
 
1612
        while todo:
 
1613
            # scan through looking for a revision whose parents
 
1614
            # are all done
 
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)
 
1621
                    todo.remove(rev_id)
 
1622
                    done.add(rev_id)
 
1623
        return order
 
1624
 
 
1625
 
 
1626
class ConvertBzrDir5To6(Converter):
 
1627
    """Converts format 5 bzr dirs to format 6."""
 
1628
 
 
1629
    def convert(self, to_convert, pb):
 
1630
        """See Converter.convert()."""
 
1631
        self.bzrdir = to_convert
 
1632
        self.pb = pb
 
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)
 
1636
 
 
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]
 
1650
                else:
 
1651
                    file_id = filename
 
1652
                prefix_dir = store.hash_prefix(file_id)
 
1653
                # FIXME keep track of the dirs made RBC 20060121
 
1654
                try:
 
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())
 
1660
 
 
1661
 
 
1662
class ConvertBzrDir6ToMeta(Converter):
 
1663
    """Converts format 6 bzr dirs to metadirs."""
 
1664
 
 
1665
    def convert(self, to_convert, pb):
 
1666
        """See Converter.convert()."""
 
1667
        self.bzrdir = to_convert
 
1668
        self.pb = pb
 
1669
        self.count = 0
 
1670
        self.total = 20 # the steps we know about
 
1671
        self.garbage_inventories = []
 
1672
 
 
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.
 
1677
        try:
 
1678
            self.step('Removing ancestry.weave')
 
1679
            self.bzrdir.transport.delete('ancestry.weave')
 
1680
        except errors.NoSuchFile:
 
1681
            pass
 
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),
 
1694
                            ('weaves', 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)
 
1704
 
 
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),
 
1711
                        ('parent', False)]
 
1712
        for entry in branch_files:
 
1713
            self.move_entry('branch', entry)
 
1714
 
 
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',
 
1727
                                                last_revision)
 
1728
        self.bzrdir._control_files.put_utf8('branch-format', BzrDirMetaFormat1().get_format_string())
 
1729
        return BzrDir.open(self.bzrdir.root_transport.base)
 
1730
 
 
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, 
 
1735
                     '%s/lock' % name,
 
1736
                     file_modebits=self.file_mode,
 
1737
                     dir_modebits=self.dir_mode)
 
1738
        ld.create()
 
1739
 
 
1740
    def move_entry(self, new_dir, entry):
 
1741
        """Move then entry name into new_dir."""
 
1742
        name = entry[0]
 
1743
        mandatory = entry[1]
 
1744
        self.step('Moving %s' % name)
 
1745
        try:
 
1746
            self.bzrdir.transport.move(name, '%s/%s' % (new_dir, name))
 
1747
        except errors.NoSuchFile:
 
1748
            if mandatory:
 
1749
                raise
 
1750
 
 
1751
    def put_format(self, dirname, format):
 
1752
        self.bzrdir._control_files.put_utf8('%s/format' % dirname, format.get_format_string())
 
1753
 
 
1754
 
 
1755
class ConvertMetaToMeta(Converter):
 
1756
    """Converts the components of metadirs."""
 
1757
 
 
1758
    def __init__(self, target_format):
 
1759
        """Create a metadir to metadir converter.
 
1760
 
 
1761
        :param target_format: The final metadir format that is desired.
 
1762
        """
 
1763
        self.target_format = target_format
 
1764
 
 
1765
    def convert(self, to_convert, pb):
 
1766
        """See Converter.convert()."""
 
1767
        self.bzrdir = to_convert
 
1768
        self.pb = pb
 
1769
        self.count = 0
 
1770
        self.total = 1
 
1771
        self.step('checking repository format')
 
1772
        try:
 
1773
            repo = self.bzrdir.open_repository()
 
1774
        except errors.NoRepositoryPresent:
 
1775
            pass
 
1776
        else:
 
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)
 
1782
        return to_convert