/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: John Arbash Meinel
  • Date: 2006-05-02 20:46:11 UTC
  • mto: This revision was merged to the branch mainline in revision 1752.
  • Revision ID: john@arbash-meinel.com-20060502204611-02caa5c20fb84ef8
Moved url functions into bzrlib.urlutils

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
 
47
from bzrlib.transport.local import LocalTransport
 
48
import bzrlib.urlutils as urlutils
 
49
from bzrlib.weave import Weave
 
50
from bzrlib.xml4 import serializer_v4
 
51
from bzrlib.xml5 import serializer_v5
 
52
 
 
53
 
 
54
class BzrDir(object):
 
55
    """A .bzr control diretory.
 
56
    
 
57
    BzrDir instances let you create or open any of the things that can be
 
58
    found within .bzr - checkouts, branches and repositories.
 
59
    
 
60
    transport
 
61
        the transport which this bzr dir is rooted at (i.e. file:///.../.bzr/)
 
62
    root_transport
 
63
        a transport connected to the directory this bzr was opened from.
 
64
    """
 
65
 
 
66
    def can_convert_format(self):
 
67
        """Return true if this bzrdir is one whose format we can convert from."""
 
68
        return True
 
69
 
 
70
    @staticmethod
 
71
    def _check_supported(format, allow_unsupported):
 
72
        """Check whether format is a supported format.
 
73
 
 
74
        If allow_unsupported is True, this is a no-op.
 
75
        """
 
76
        if not allow_unsupported and not format.is_supported():
 
77
            # see open_downlevel to open legacy branches.
 
78
            raise errors.UnsupportedFormatError(
 
79
                    'sorry, format %s not supported' % format,
 
80
                    ['use a different bzr version',
 
81
                     'or remove the .bzr directory'
 
82
                     ' and "bzr init" again'])
 
83
 
 
84
    def clone(self, url, revision_id=None, basis=None, force_new_repo=False):
 
85
        """Clone this bzrdir and its contents to url verbatim.
 
86
 
 
87
        If urls last component does not exist, it will be created.
 
88
 
 
89
        if revision_id is not None, then the clone operation may tune
 
90
            itself to download less data.
 
91
        :param force_new_repo: Do not use a shared repository for the target 
 
92
                               even if one is available.
 
93
        """
 
94
        self._make_tail(url)
 
95
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
 
96
        result = self._format.initialize(url)
 
97
        try:
 
98
            local_repo = self.find_repository()
 
99
        except errors.NoRepositoryPresent:
 
100
            local_repo = None
 
101
        if local_repo:
 
102
            # may need to copy content in
 
103
            if force_new_repo:
 
104
                local_repo.clone(result, revision_id=revision_id, basis=basis_repo)
 
105
            else:
 
106
                try:
 
107
                    result_repo = result.find_repository()
 
108
                    # fetch content this dir needs.
 
109
                    if basis_repo:
 
110
                        # XXX FIXME RBC 20060214 need tests for this when the basis
 
111
                        # is incomplete
 
112
                        result_repo.fetch(basis_repo, revision_id=revision_id)
 
113
                    result_repo.fetch(local_repo, revision_id=revision_id)
 
114
                except errors.NoRepositoryPresent:
 
115
                    # needed to make one anyway.
 
116
                    local_repo.clone(result, revision_id=revision_id, basis=basis_repo)
 
117
        # 1 if there is a branch present
 
118
        #   make sure its content is available in the target repository
 
119
        #   clone it.
 
120
        try:
 
121
            self.open_branch().clone(result, revision_id=revision_id)
 
122
        except errors.NotBranchError:
 
123
            pass
 
124
        try:
 
125
            self.open_workingtree().clone(result, basis=basis_tree)
 
126
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
127
            pass
 
128
        return result
 
129
 
 
130
    def _get_basis_components(self, basis):
 
131
        """Retrieve the basis components that are available at basis."""
 
132
        if basis is None:
 
133
            return None, None, None
 
134
        try:
 
135
            basis_tree = basis.open_workingtree()
 
136
            basis_branch = basis_tree.branch
 
137
            basis_repo = basis_branch.repository
 
138
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
139
            basis_tree = None
 
140
            try:
 
141
                basis_branch = basis.open_branch()
 
142
                basis_repo = basis_branch.repository
 
143
            except errors.NotBranchError:
 
144
                basis_branch = None
 
145
                try:
 
146
                    basis_repo = basis.open_repository()
 
147
                except errors.NoRepositoryPresent:
 
148
                    basis_repo = None
 
149
        return basis_repo, basis_branch, basis_tree
 
150
 
 
151
    def _make_tail(self, url):
 
152
        segments = url.split('/')
 
153
        if segments and segments[-1] not in ('', '.'):
 
154
            parent = '/'.join(segments[:-1])
 
155
            print '_make_tail(%s) => parent: %s, segment: %s' % (
 
156
                url, parent, segments[-1])
 
157
            t = bzrlib.transport.get_transport(parent)
 
158
            try:
 
159
                t.mkdir(segments[-1])
 
160
            except errors.FileExists:
 
161
                pass
 
162
 
 
163
    @classmethod
 
164
    def create(cls, base):
 
165
        """Create a new BzrDir at the url 'base'.
 
166
        
 
167
        This will call the current default formats initialize with base
 
168
        as the only parameter.
 
169
 
 
170
        If you need a specific format, consider creating an instance
 
171
        of that and calling initialize().
 
172
        """
 
173
        if cls is not BzrDir:
 
174
            raise AssertionError("BzrDir.create always creates the default format, "
 
175
                    "not one of %r" % cls)
 
176
        segments = base.split('/')
 
177
        if segments and segments[-1] not in ('', '.'):
 
178
            parent = '/'.join(segments[:-1])
 
179
            t = bzrlib.transport.get_transport(parent)
 
180
            try:
 
181
                t.mkdir(segments[-1])
 
182
            except errors.FileExists:
 
183
                pass
 
184
        return BzrDirFormat.get_default_format().initialize(safe_unicode(base))
 
185
 
 
186
    def create_branch(self):
 
187
        """Create a branch in this BzrDir.
 
188
 
 
189
        The bzrdirs format will control what branch format is created.
 
190
        For more control see BranchFormatXX.create(a_bzrdir).
 
191
        """
 
192
        raise NotImplementedError(self.create_branch)
 
193
 
 
194
    @staticmethod
 
195
    def create_branch_and_repo(base, force_new_repo=False):
 
196
        """Create a new BzrDir, Branch and Repository at the url 'base'.
 
197
 
 
198
        This will use the current default BzrDirFormat, and use whatever 
 
199
        repository format that that uses via bzrdir.create_branch and
 
200
        create_repository. If a shared repository is available that is used
 
201
        preferentially.
 
202
 
 
203
        The created Branch object is returned.
 
204
 
 
205
        :param base: The URL to create the branch at.
 
206
        :param force_new_repo: If True a new repository is always created.
 
207
        """
 
208
        bzrdir = BzrDir.create(base)
 
209
        bzrdir._find_or_create_repository(force_new_repo)
 
210
        return bzrdir.create_branch()
 
211
 
 
212
    def _find_or_create_repository(self, force_new_repo):
 
213
        """Create a new repository if needed, returning the repository."""
 
214
        if force_new_repo:
 
215
            return self.create_repository()
 
216
        try:
 
217
            return self.find_repository()
 
218
        except errors.NoRepositoryPresent:
 
219
            return self.create_repository()
 
220
        
 
221
    @staticmethod
 
222
    def create_branch_convenience(base, force_new_repo=False,
 
223
                                  force_new_tree=None, format=None):
 
224
        """Create a new BzrDir, Branch and Repository at the url 'base'.
 
225
 
 
226
        This is a convenience function - it will use an existing repository
 
227
        if possible, can be told explicitly whether to create a working tree or
 
228
        not.
 
229
 
 
230
        This will use the current default BzrDirFormat, and use whatever 
 
231
        repository format that that uses via bzrdir.create_branch and
 
232
        create_repository. If a shared repository is available that is used
 
233
        preferentially. Whatever repository is used, its tree creation policy
 
234
        is followed.
 
235
 
 
236
        The created Branch object is returned.
 
237
        If a working tree cannot be made due to base not being a file:// url,
 
238
        no error is raised unless force_new_tree is True, in which case no 
 
239
        data is created on disk and NotLocalUrl is raised.
 
240
 
 
241
        :param base: The URL to create the branch at.
 
242
        :param force_new_repo: If True a new repository is always created.
 
243
        :param force_new_tree: If True or False force creation of a tree or 
 
244
                               prevent such creation respectively.
 
245
        :param format: Override for the for the bzrdir format to create
 
246
        """
 
247
        if force_new_tree:
 
248
            # check for non local urls
 
249
            t = get_transport(safe_unicode(base))
 
250
            if not isinstance(t, LocalTransport):
 
251
                raise errors.NotLocalUrl(base)
 
252
        if format is None:
 
253
            bzrdir = BzrDir.create(base)
 
254
        else:
 
255
            bzrdir = format.initialize(base)
 
256
        repo = bzrdir._find_or_create_repository(force_new_repo)
 
257
        result = bzrdir.create_branch()
 
258
        if force_new_tree or (repo.make_working_trees() and 
 
259
                              force_new_tree is None):
 
260
            try:
 
261
                bzrdir.create_workingtree()
 
262
            except errors.NotLocalUrl:
 
263
                pass
 
264
        return result
 
265
        
 
266
    @staticmethod
 
267
    def create_repository(base, shared=False):
 
268
        """Create a new BzrDir and Repository at the url 'base'.
 
269
 
 
270
        This will use the current default BzrDirFormat, and use whatever 
 
271
        repository format that that uses for bzrdirformat.create_repository.
 
272
 
 
273
        ;param shared: Create a shared repository rather than a standalone
 
274
                       repository.
 
275
        The Repository object is returned.
 
276
 
 
277
        This must be overridden as an instance method in child classes, where
 
278
        it should take no parameters and construct whatever repository format
 
279
        that child class desires.
 
280
        """
 
281
        bzrdir = BzrDir.create(base)
 
282
        return bzrdir.create_repository()
 
283
 
 
284
    @staticmethod
 
285
    def create_standalone_workingtree(base):
 
286
        """Create a new BzrDir, WorkingTree, Branch and Repository at 'base'.
 
287
 
 
288
        'base' must be a local path or a file:// url.
 
289
 
 
290
        This will use the current default BzrDirFormat, and use whatever 
 
291
        repository format that that uses for bzrdirformat.create_workingtree,
 
292
        create_branch and create_repository.
 
293
 
 
294
        The WorkingTree object is returned.
 
295
        """
 
296
        t = get_transport(safe_unicode(base))
 
297
        if not isinstance(t, LocalTransport):
 
298
            raise errors.NotLocalUrl(base)
 
299
        bzrdir = BzrDir.create_branch_and_repo(safe_unicode(base),
 
300
                                               force_new_repo=True).bzrdir
 
301
        return bzrdir.create_workingtree()
 
302
 
 
303
    def create_workingtree(self, revision_id=None):
 
304
        """Create a working tree at this BzrDir.
 
305
        
 
306
        revision_id: create it as of this revision id.
 
307
        """
 
308
        raise NotImplementedError(self.create_workingtree)
 
309
 
 
310
    def find_repository(self):
 
311
        """Find the repository that should be used for a_bzrdir.
 
312
 
 
313
        This does not require a branch as we use it to find the repo for
 
314
        new branches as well as to hook existing branches up to their
 
315
        repository.
 
316
        """
 
317
        try:
 
318
            return self.open_repository()
 
319
        except errors.NoRepositoryPresent:
 
320
            pass
 
321
        next_transport = self.root_transport.clone('..')
 
322
        while True:
 
323
            try:
 
324
                found_bzrdir = BzrDir.open_containing_from_transport(
 
325
                    next_transport)[0]
 
326
            except errors.NotBranchError:
 
327
                raise errors.NoRepositoryPresent(self)
 
328
            try:
 
329
                repository = found_bzrdir.open_repository()
 
330
            except errors.NoRepositoryPresent:
 
331
                next_transport = found_bzrdir.root_transport.clone('..')
 
332
                continue
 
333
            if ((found_bzrdir.root_transport.base == 
 
334
                 self.root_transport.base) or repository.is_shared()):
 
335
                return repository
 
336
            else:
 
337
                raise errors.NoRepositoryPresent(self)
 
338
        raise errors.NoRepositoryPresent(self)
 
339
 
 
340
    def get_branch_transport(self, branch_format):
 
341
        """Get the transport for use by branch format in this BzrDir.
 
342
 
 
343
        Note that bzr dirs that do not support format strings will raise
 
344
        IncompatibleFormat if the branch format they are given has
 
345
        a format string, and vice verca.
 
346
 
 
347
        If branch_format is None, the transport is returned with no 
 
348
        checking. if it is not None, then the returned transport is
 
349
        guaranteed to point to an existing directory ready for use.
 
350
        """
 
351
        raise NotImplementedError(self.get_branch_transport)
 
352
        
 
353
    def get_repository_transport(self, repository_format):
 
354
        """Get the transport for use by repository format in this BzrDir.
 
355
 
 
356
        Note that bzr dirs that do not support format strings will raise
 
357
        IncompatibleFormat if the repository format they are given has
 
358
        a format string, and vice verca.
 
359
 
 
360
        If repository_format is None, the transport is returned with no 
 
361
        checking. if it is not None, then the returned transport is
 
362
        guaranteed to point to an existing directory ready for use.
 
363
        """
 
364
        raise NotImplementedError(self.get_repository_transport)
 
365
        
 
366
    def get_workingtree_transport(self, tree_format):
 
367
        """Get the transport for use by workingtree format in this BzrDir.
 
368
 
 
369
        Note that bzr dirs that do not support format strings will raise
 
370
        IncompatibleFormat if the workingtree format they are given has
 
371
        a format string, and vice verca.
 
372
 
 
373
        If workingtree_format is None, the transport is returned with no 
 
374
        checking. if it is not None, then the returned transport is
 
375
        guaranteed to point to an existing directory ready for use.
 
376
        """
 
377
        raise NotImplementedError(self.get_workingtree_transport)
 
378
        
 
379
    def __init__(self, _transport, _format):
 
380
        """Initialize a Bzr control dir object.
 
381
        
 
382
        Only really common logic should reside here, concrete classes should be
 
383
        made with varying behaviours.
 
384
 
 
385
        :param _format: the format that is creating this BzrDir instance.
 
386
        :param _transport: the transport this dir is based at.
 
387
        """
 
388
        self._format = _format
 
389
        self.transport = _transport.clone('.bzr')
 
390
        self.root_transport = _transport
 
391
 
 
392
    def needs_format_conversion(self, format=None):
 
393
        """Return true if this bzrdir needs convert_format run on it.
 
394
        
 
395
        For instance, if the repository format is out of date but the 
 
396
        branch and working tree are not, this should return True.
 
397
 
 
398
        :param format: Optional parameter indicating a specific desired
 
399
                       format we plan to arrive at.
 
400
        """
 
401
        raise NotImplementedError(self.needs_format_conversion)
 
402
 
 
403
    @staticmethod
 
404
    def open_unsupported(base):
 
405
        """Open a branch which is not supported."""
 
406
        return BzrDir.open(base, _unsupported=True)
 
407
        
 
408
    @staticmethod
 
409
    def open(base, _unsupported=False):
 
410
        """Open an existing bzrdir, rooted at 'base' (url)
 
411
        
 
412
        _unsupported is a private parameter to the BzrDir class.
 
413
        """
 
414
        t = get_transport(base)
 
415
        mutter("trying to open %r with transport %r", base, t)
 
416
        format = BzrDirFormat.find_format(t)
 
417
        BzrDir._check_supported(format, _unsupported)
 
418
        return format.open(t, _found=True)
 
419
 
 
420
    def open_branch(self, unsupported=False):
 
421
        """Open the branch object at this BzrDir if one is present.
 
422
 
 
423
        If unsupported is True, then no longer supported branch formats can
 
424
        still be opened.
 
425
        
 
426
        TODO: static convenience version of this?
 
427
        """
 
428
        raise NotImplementedError(self.open_branch)
 
429
 
 
430
    @staticmethod
 
431
    def open_containing(url):
 
432
        """Open an existing branch which contains url.
 
433
        
 
434
        :param url: url to search from.
 
435
        See open_containing_from_transport for more detail.
 
436
        """
 
437
        return BzrDir.open_containing_from_transport(get_transport(url))
 
438
    
 
439
    @staticmethod
 
440
    def open_containing_from_transport(a_transport):
 
441
        """Open an existing branch which contains a_transport.base
 
442
 
 
443
        This probes for a branch at a_transport, and searches upwards from there.
 
444
 
 
445
        Basically we keep looking up until we find the control directory or
 
446
        run into the root.  If there isn't one, raises NotBranchError.
 
447
        If there is one and it is either an unrecognised format or an unsupported 
 
448
        format, UnknownFormatError or UnsupportedFormatError are raised.
 
449
        If there is one, it is returned, along with the unused portion of url.
 
450
 
 
451
        :return: The BzrDir that contains the path, and a Unicode path 
 
452
                for the rest of the URL.
 
453
        """
 
454
        # this gets the normalised url back. I.e. '.' -> the full path.
 
455
        url = a_transport.base
 
456
        while True:
 
457
            try:
 
458
                format = BzrDirFormat.find_format(a_transport)
 
459
                BzrDir._check_supported(format, False)
 
460
                return format.open(a_transport), urlutils.unescape(a_transport.relpath(url))
 
461
            except errors.NotBranchError, e:
 
462
                mutter('not a branch in: %r %s', a_transport.base, e)
 
463
            new_t = a_transport.clone('..')
 
464
            if new_t.base == a_transport.base:
 
465
                # reached the root, whatever that may be
 
466
                raise errors.NotBranchError(path=url)
 
467
            a_transport = new_t
 
468
 
 
469
    def open_repository(self, _unsupported=False):
 
470
        """Open the repository object at this BzrDir if one is present.
 
471
 
 
472
        This will not follow the Branch object pointer - its strictly a direct
 
473
        open facility. Most client code should use open_branch().repository to
 
474
        get at a repository.
 
475
 
 
476
        _unsupported is a private parameter, not part of the api.
 
477
        TODO: static convenience version of this?
 
478
        """
 
479
        raise NotImplementedError(self.open_repository)
 
480
 
 
481
    def open_workingtree(self, _unsupported=False):
 
482
        """Open the workingtree object at this BzrDir if one is present.
 
483
        
 
484
        TODO: static convenience version of this?
 
485
        """
 
486
        raise NotImplementedError(self.open_workingtree)
 
487
 
 
488
    def has_branch(self):
 
489
        """Tell if this bzrdir contains a branch.
 
490
        
 
491
        Note: if you're going to open the branch, you should just go ahead
 
492
        and try, and not ask permission first.  (This method just opens the 
 
493
        branch and discards it, and that's somewhat expensive.) 
 
494
        """
 
495
        try:
 
496
            self.open_branch()
 
497
            return True
 
498
        except errors.NotBranchError:
 
499
            return False
 
500
 
 
501
    def has_workingtree(self):
 
502
        """Tell if this bzrdir contains a working tree.
 
503
 
 
504
        This will still raise an exception if the bzrdir has a workingtree that
 
505
        is remote & inaccessible.
 
506
        
 
507
        Note: if you're going to open the working tree, you should just go ahead
 
508
        and try, and not ask permission first.  (This method just opens the 
 
509
        workingtree and discards it, and that's somewhat expensive.) 
 
510
        """
 
511
        try:
 
512
            self.open_workingtree()
 
513
            return True
 
514
        except errors.NoWorkingTree:
 
515
            return False
 
516
 
 
517
    def sprout(self, url, revision_id=None, basis=None, force_new_repo=False):
 
518
        """Create a copy of this bzrdir prepared for use as a new line of
 
519
        development.
 
520
 
 
521
        If urls last component does not exist, it will be created.
 
522
 
 
523
        Attributes related to the identity of the source branch like
 
524
        branch nickname will be cleaned, a working tree is created
 
525
        whether one existed before or not; and a local branch is always
 
526
        created.
 
527
 
 
528
        if revision_id is not None, then the clone operation may tune
 
529
            itself to download less data.
 
530
        """
 
531
        self._make_tail(url)
 
532
        result = self._format.initialize(url)
 
533
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
 
534
        try:
 
535
            source_branch = self.open_branch()
 
536
            source_repository = source_branch.repository
 
537
        except errors.NotBranchError:
 
538
            source_branch = None
 
539
            try:
 
540
                source_repository = self.open_repository()
 
541
            except errors.NoRepositoryPresent:
 
542
                # copy the entire basis one if there is one
 
543
                # but there is no repository.
 
544
                source_repository = basis_repo
 
545
        if force_new_repo:
 
546
            result_repo = None
 
547
        else:
 
548
            try:
 
549
                result_repo = result.find_repository()
 
550
            except errors.NoRepositoryPresent:
 
551
                result_repo = None
 
552
        if source_repository is None and result_repo is not None:
 
553
            pass
 
554
        elif source_repository is None and result_repo is None:
 
555
            # no repo available, make a new one
 
556
            result.create_repository()
 
557
        elif source_repository is not None and result_repo is None:
 
558
            # have soure, and want to make a new target repo
 
559
            source_repository.clone(result,
 
560
                                    revision_id=revision_id,
 
561
                                    basis=basis_repo)
 
562
        else:
 
563
            # fetch needed content into target.
 
564
            if basis_repo:
 
565
                # XXX FIXME RBC 20060214 need tests for this when the basis
 
566
                # is incomplete
 
567
                result_repo.fetch(basis_repo, revision_id=revision_id)
 
568
            result_repo.fetch(source_repository, revision_id=revision_id)
 
569
        if source_branch is not None:
 
570
            source_branch.sprout(result, revision_id=revision_id)
 
571
        else:
 
572
            result.create_branch()
 
573
        # TODO: jam 20060426 we probably need a test in here in the
 
574
        #       case that the newly sprouted branch is a remote one
 
575
        if result_repo is None or result_repo.make_working_trees():
 
576
            result.create_workingtree()
 
577
        return result
 
578
 
 
579
 
 
580
class BzrDirPreSplitOut(BzrDir):
 
581
    """A common class for the all-in-one formats."""
 
582
 
 
583
    def __init__(self, _transport, _format):
 
584
        """See BzrDir.__init__."""
 
585
        super(BzrDirPreSplitOut, self).__init__(_transport, _format)
 
586
        assert self._format._lock_class == TransportLock
 
587
        assert self._format._lock_file_name == 'branch-lock'
 
588
        self._control_files = LockableFiles(self.get_branch_transport(None),
 
589
                                            self._format._lock_file_name,
 
590
                                            self._format._lock_class)
 
591
 
 
592
    def clone(self, url, revision_id=None, basis=None, force_new_repo=False):
 
593
        """See BzrDir.clone()."""
 
594
        from bzrlib.workingtree import WorkingTreeFormat2
 
595
        self._make_tail(url)
 
596
        result = self._format._initialize_for_clone(url)
 
597
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
 
598
        self.open_repository().clone(result, revision_id=revision_id, basis=basis_repo)
 
599
        self.open_branch().clone(result, revision_id=revision_id)
 
600
        try:
 
601
            self.open_workingtree().clone(result, basis=basis_tree)
 
602
        except errors.NotLocalUrl:
 
603
            # make a new one, this format always has to have one.
 
604
            try:
 
605
                WorkingTreeFormat2().initialize(result)
 
606
            except errors.NotLocalUrl:
 
607
                # but we canot do it for remote trees.
 
608
                pass
 
609
        return result
 
610
 
 
611
    def create_branch(self):
 
612
        """See BzrDir.create_branch."""
 
613
        return self.open_branch()
 
614
 
 
615
    def create_repository(self, shared=False):
 
616
        """See BzrDir.create_repository."""
 
617
        if shared:
 
618
            raise errors.IncompatibleFormat('shared repository', self._format)
 
619
        return self.open_repository()
 
620
 
 
621
    def create_workingtree(self, revision_id=None):
 
622
        """See BzrDir.create_workingtree."""
 
623
        # this looks buggy but is not -really-
 
624
        # clone and sprout will have set the revision_id
 
625
        # and that will have set it for us, its only
 
626
        # specific uses of create_workingtree in isolation
 
627
        # that can do wonky stuff here, and that only
 
628
        # happens for creating checkouts, which cannot be 
 
629
        # done on this format anyway. So - acceptable wart.
 
630
        result = self.open_workingtree()
 
631
        if revision_id is not None:
 
632
            result.set_last_revision(revision_id)
 
633
        return result
 
634
 
 
635
    def get_branch_transport(self, branch_format):
 
636
        """See BzrDir.get_branch_transport()."""
 
637
        if branch_format is None:
 
638
            return self.transport
 
639
        try:
 
640
            branch_format.get_format_string()
 
641
        except NotImplementedError:
 
642
            return self.transport
 
643
        raise errors.IncompatibleFormat(branch_format, self._format)
 
644
 
 
645
    def get_repository_transport(self, repository_format):
 
646
        """See BzrDir.get_repository_transport()."""
 
647
        if repository_format is None:
 
648
            return self.transport
 
649
        try:
 
650
            repository_format.get_format_string()
 
651
        except NotImplementedError:
 
652
            return self.transport
 
653
        raise errors.IncompatibleFormat(repository_format, self._format)
 
654
 
 
655
    def get_workingtree_transport(self, workingtree_format):
 
656
        """See BzrDir.get_workingtree_transport()."""
 
657
        if workingtree_format is None:
 
658
            return self.transport
 
659
        try:
 
660
            workingtree_format.get_format_string()
 
661
        except NotImplementedError:
 
662
            return self.transport
 
663
        raise errors.IncompatibleFormat(workingtree_format, self._format)
 
664
 
 
665
    def needs_format_conversion(self, format=None):
 
666
        """See BzrDir.needs_format_conversion()."""
 
667
        # if the format is not the same as the system default,
 
668
        # an upgrade is needed.
 
669
        if format is None:
 
670
            format = BzrDirFormat.get_default_format()
 
671
        return not isinstance(self._format, format.__class__)
 
672
 
 
673
    def open_branch(self, unsupported=False):
 
674
        """See BzrDir.open_branch."""
 
675
        from bzrlib.branch import BzrBranchFormat4
 
676
        format = BzrBranchFormat4()
 
677
        self._check_supported(format, unsupported)
 
678
        return format.open(self, _found=True)
 
679
 
 
680
    def sprout(self, url, revision_id=None, basis=None):
 
681
        """See BzrDir.sprout()."""
 
682
        from bzrlib.workingtree import WorkingTreeFormat2
 
683
        self._make_tail(url)
 
684
        result = self._format._initialize_for_clone(url)
 
685
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
 
686
        try:
 
687
            self.open_repository().clone(result, revision_id=revision_id, basis=basis_repo)
 
688
        except errors.NoRepositoryPresent:
 
689
            pass
 
690
        try:
 
691
            self.open_branch().sprout(result, revision_id=revision_id)
 
692
        except errors.NotBranchError:
 
693
            pass
 
694
        # we always want a working tree
 
695
        WorkingTreeFormat2().initialize(result)
 
696
        return result
 
697
 
 
698
 
 
699
class BzrDir4(BzrDirPreSplitOut):
 
700
    """A .bzr version 4 control object.
 
701
    
 
702
    This is a deprecated format and may be removed after sept 2006.
 
703
    """
 
704
 
 
705
    def create_repository(self, shared=False):
 
706
        """See BzrDir.create_repository."""
 
707
        return self._format.repository_format.initialize(self, shared)
 
708
 
 
709
    def needs_format_conversion(self, format=None):
 
710
        """Format 4 dirs are always in need of conversion."""
 
711
        return True
 
712
 
 
713
    def open_repository(self):
 
714
        """See BzrDir.open_repository."""
 
715
        from bzrlib.repository import RepositoryFormat4
 
716
        return RepositoryFormat4().open(self, _found=True)
 
717
 
 
718
 
 
719
class BzrDir5(BzrDirPreSplitOut):
 
720
    """A .bzr version 5 control object.
 
721
 
 
722
    This is a deprecated format and may be removed after sept 2006.
 
723
    """
 
724
 
 
725
    def open_repository(self):
 
726
        """See BzrDir.open_repository."""
 
727
        from bzrlib.repository import RepositoryFormat5
 
728
        return RepositoryFormat5().open(self, _found=True)
 
729
 
 
730
    def open_workingtree(self, _unsupported=False):
 
731
        """See BzrDir.create_workingtree."""
 
732
        from bzrlib.workingtree import WorkingTreeFormat2
 
733
        return WorkingTreeFormat2().open(self, _found=True)
 
734
 
 
735
 
 
736
class BzrDir6(BzrDirPreSplitOut):
 
737
    """A .bzr version 6 control object.
 
738
 
 
739
    This is a deprecated format and may be removed after sept 2006.
 
740
    """
 
741
 
 
742
    def open_repository(self):
 
743
        """See BzrDir.open_repository."""
 
744
        from bzrlib.repository import RepositoryFormat6
 
745
        return RepositoryFormat6().open(self, _found=True)
 
746
 
 
747
    def open_workingtree(self, _unsupported=False):
 
748
        """See BzrDir.create_workingtree."""
 
749
        from bzrlib.workingtree import WorkingTreeFormat2
 
750
        return WorkingTreeFormat2().open(self, _found=True)
 
751
 
 
752
 
 
753
class BzrDirMeta1(BzrDir):
 
754
    """A .bzr meta version 1 control object.
 
755
    
 
756
    This is the first control object where the 
 
757
    individual aspects are really split out: there are separate repository,
 
758
    workingtree and branch subdirectories and any subset of the three can be
 
759
    present within a BzrDir.
 
760
    """
 
761
 
 
762
    def can_convert_format(self):
 
763
        """See BzrDir.can_convert_format()."""
 
764
        return True
 
765
 
 
766
    def create_branch(self):
 
767
        """See BzrDir.create_branch."""
 
768
        from bzrlib.branch import BranchFormat
 
769
        return BranchFormat.get_default_format().initialize(self)
 
770
 
 
771
    def create_repository(self, shared=False):
 
772
        """See BzrDir.create_repository."""
 
773
        return self._format.repository_format.initialize(self, shared)
 
774
 
 
775
    def create_workingtree(self, revision_id=None):
 
776
        """See BzrDir.create_workingtree."""
 
777
        from bzrlib.workingtree import WorkingTreeFormat
 
778
        return WorkingTreeFormat.get_default_format().initialize(self, revision_id)
 
779
 
 
780
    def _get_mkdir_mode(self):
 
781
        """Figure out the mode to use when creating a bzrdir subdir."""
 
782
        temp_control = LockableFiles(self.transport, '', TransportLock)
 
783
        return temp_control._dir_mode
 
784
 
 
785
    def get_branch_transport(self, branch_format):
 
786
        """See BzrDir.get_branch_transport()."""
 
787
        if branch_format is None:
 
788
            return self.transport.clone('branch')
 
789
        try:
 
790
            branch_format.get_format_string()
 
791
        except NotImplementedError:
 
792
            raise errors.IncompatibleFormat(branch_format, self._format)
 
793
        try:
 
794
            self.transport.mkdir('branch', mode=self._get_mkdir_mode())
 
795
        except errors.FileExists:
 
796
            pass
 
797
        return self.transport.clone('branch')
 
798
 
 
799
    def get_repository_transport(self, repository_format):
 
800
        """See BzrDir.get_repository_transport()."""
 
801
        if repository_format is None:
 
802
            return self.transport.clone('repository')
 
803
        try:
 
804
            repository_format.get_format_string()
 
805
        except NotImplementedError:
 
806
            raise errors.IncompatibleFormat(repository_format, self._format)
 
807
        try:
 
808
            self.transport.mkdir('repository', mode=self._get_mkdir_mode())
 
809
        except errors.FileExists:
 
810
            pass
 
811
        return self.transport.clone('repository')
 
812
 
 
813
    def get_workingtree_transport(self, workingtree_format):
 
814
        """See BzrDir.get_workingtree_transport()."""
 
815
        if workingtree_format is None:
 
816
            return self.transport.clone('checkout')
 
817
        try:
 
818
            workingtree_format.get_format_string()
 
819
        except NotImplementedError:
 
820
            raise errors.IncompatibleFormat(workingtree_format, self._format)
 
821
        try:
 
822
            self.transport.mkdir('checkout', mode=self._get_mkdir_mode())
 
823
        except errors.FileExists:
 
824
            pass
 
825
        return self.transport.clone('checkout')
 
826
 
 
827
    def needs_format_conversion(self, format=None):
 
828
        """See BzrDir.needs_format_conversion()."""
 
829
        if format is None:
 
830
            format = BzrDirFormat.get_default_format()
 
831
        if not isinstance(self._format, format.__class__):
 
832
            # it is not a meta dir format, conversion is needed.
 
833
            return True
 
834
        # we might want to push this down to the repository?
 
835
        try:
 
836
            if not isinstance(self.open_repository()._format,
 
837
                              format.repository_format.__class__):
 
838
                # the repository needs an upgrade.
 
839
                return True
 
840
        except errors.NoRepositoryPresent:
 
841
            pass
 
842
        # currently there are no other possible conversions for meta1 formats.
 
843
        return False
 
844
 
 
845
    def open_branch(self, unsupported=False):
 
846
        """See BzrDir.open_branch."""
 
847
        from bzrlib.branch import BranchFormat
 
848
        format = BranchFormat.find_format(self)
 
849
        self._check_supported(format, unsupported)
 
850
        return format.open(self, _found=True)
 
851
 
 
852
    def open_repository(self, unsupported=False):
 
853
        """See BzrDir.open_repository."""
 
854
        from bzrlib.repository import RepositoryFormat
 
855
        format = RepositoryFormat.find_format(self)
 
856
        self._check_supported(format, unsupported)
 
857
        return format.open(self, _found=True)
 
858
 
 
859
    def open_workingtree(self, unsupported=False):
 
860
        """See BzrDir.open_workingtree."""
 
861
        from bzrlib.workingtree import WorkingTreeFormat
 
862
        format = WorkingTreeFormat.find_format(self)
 
863
        self._check_supported(format, unsupported)
 
864
        return format.open(self, _found=True)
 
865
 
 
866
 
 
867
class BzrDirFormat(object):
 
868
    """An encapsulation of the initialization and open routines for a format.
 
869
 
 
870
    Formats provide three things:
 
871
     * An initialization routine,
 
872
     * a format string,
 
873
     * an open routine.
 
874
 
 
875
    Formats are placed in an dict by their format string for reference 
 
876
    during bzrdir opening. These should be subclasses of BzrDirFormat
 
877
    for consistency.
 
878
 
 
879
    Once a format is deprecated, just deprecate the initialize and open
 
880
    methods on the format class. Do not deprecate the object, as the 
 
881
    object will be created every system load.
 
882
    """
 
883
 
 
884
    _default_format = None
 
885
    """The default format used for new .bzr dirs."""
 
886
 
 
887
    _formats = {}
 
888
    """The known formats."""
 
889
 
 
890
    _lock_file_name = 'branch-lock'
 
891
 
 
892
    # _lock_class must be set in subclasses to the lock type, typ.
 
893
    # TransportLock or LockDir
 
894
 
 
895
    @classmethod
 
896
    def find_format(klass, transport):
 
897
        """Return the format registered for URL."""
 
898
        try:
 
899
            format_string = transport.get(".bzr/branch-format").read()
 
900
            return klass._formats[format_string]
 
901
        except errors.NoSuchFile:
 
902
            raise errors.NotBranchError(path=transport.base)
 
903
        except KeyError:
 
904
            raise errors.UnknownFormatError(format_string)
 
905
 
 
906
    @classmethod
 
907
    def get_default_format(klass):
 
908
        """Return the current default format."""
 
909
        return klass._default_format
 
910
 
 
911
    def get_format_string(self):
 
912
        """Return the ASCII format string that identifies this format."""
 
913
        raise NotImplementedError(self.get_format_string)
 
914
 
 
915
    def get_format_description(self):
 
916
        """Return the short description for this format."""
 
917
        raise NotImplementedError(self.get_format_description)
 
918
 
 
919
    def get_converter(self, format=None):
 
920
        """Return the converter to use to convert bzrdirs needing converts.
 
921
 
 
922
        This returns a bzrlib.bzrdir.Converter object.
 
923
 
 
924
        This should return the best upgrader to step this format towards the
 
925
        current default format. In the case of plugins we can/shouold provide
 
926
        some means for them to extend the range of returnable converters.
 
927
 
 
928
        :param format: Optional format to override the default foramt of the 
 
929
                       library.
 
930
        """
 
931
        raise NotImplementedError(self.get_converter)
 
932
 
 
933
    def initialize(self, url):
 
934
        """Create a bzr control dir at this url and return an opened copy.
 
935
        
 
936
        Subclasses should typically override initialize_on_transport
 
937
        instead of this method.
 
938
        """
 
939
        return self.initialize_on_transport(get_transport(url))
 
940
 
 
941
    def initialize_on_transport(self, transport):
 
942
        """Initialize a new bzrdir in the base directory of a Transport."""
 
943
        # Since we don'transport have a .bzr directory, inherit the
 
944
        # mode from the root directory
 
945
        temp_control = LockableFiles(transport, '', TransportLock)
 
946
        temp_control._transport.mkdir('.bzr',
 
947
                                      # FIXME: RBC 20060121 dont peek under
 
948
                                      # the covers
 
949
                                      mode=temp_control._dir_mode)
 
950
        file_mode = temp_control._file_mode
 
951
        del temp_control
 
952
        mutter('created control directory in ' + transport.base)
 
953
        control = transport.clone('.bzr')
 
954
        utf8_files = [('README', 
 
955
                       "This is a Bazaar-NG control directory.\n"
 
956
                       "Do not change any files in this directory.\n"),
 
957
                      ('branch-format', self.get_format_string()),
 
958
                      ]
 
959
        # NB: no need to escape relative paths that are url safe.
 
960
        control_files = LockableFiles(control, self._lock_file_name, 
 
961
                                      self._lock_class)
 
962
        control_files.create_lock()
 
963
        control_files.lock_write()
 
964
        try:
 
965
            for file, content in utf8_files:
 
966
                control_files.put_utf8(file, content)
 
967
        finally:
 
968
            control_files.unlock()
 
969
        return self.open(transport, _found=True)
 
970
 
 
971
    def is_supported(self):
 
972
        """Is this format supported?
 
973
 
 
974
        Supported formats must be initializable and openable.
 
975
        Unsupported formats may not support initialization or committing or 
 
976
        some other features depending on the reason for not being supported.
 
977
        """
 
978
        return True
 
979
 
 
980
    def open(self, transport, _found=False):
 
981
        """Return an instance of this format for the dir transport points at.
 
982
        
 
983
        _found is a private parameter, do not use it.
 
984
        """
 
985
        if not _found:
 
986
            assert isinstance(BzrDirFormat.find_format(transport),
 
987
                              self.__class__)
 
988
        return self._open(transport)
 
989
 
 
990
    def _open(self, transport):
 
991
        """Template method helper for opening BzrDirectories.
 
992
 
 
993
        This performs the actual open and any additional logic or parameter
 
994
        passing.
 
995
        """
 
996
        raise NotImplementedError(self._open)
 
997
 
 
998
    @classmethod
 
999
    def register_format(klass, format):
 
1000
        klass._formats[format.get_format_string()] = format
 
1001
 
 
1002
    @classmethod
 
1003
    def set_default_format(klass, format):
 
1004
        klass._default_format = format
 
1005
 
 
1006
    def __str__(self):
 
1007
        return self.get_format_string()[:-1]
 
1008
 
 
1009
    @classmethod
 
1010
    def unregister_format(klass, format):
 
1011
        assert klass._formats[format.get_format_string()] is format
 
1012
        del klass._formats[format.get_format_string()]
 
1013
 
 
1014
 
 
1015
class BzrDirFormat4(BzrDirFormat):
 
1016
    """Bzr dir format 4.
 
1017
 
 
1018
    This format is a combined format for working tree, branch and repository.
 
1019
    It has:
 
1020
     - Format 1 working trees [always]
 
1021
     - Format 4 branches [always]
 
1022
     - Format 4 repositories [always]
 
1023
 
 
1024
    This format is deprecated: it indexes texts using a text it which is
 
1025
    removed in format 5; write support for this format has been removed.
 
1026
    """
 
1027
 
 
1028
    _lock_class = TransportLock
 
1029
 
 
1030
    def get_format_string(self):
 
1031
        """See BzrDirFormat.get_format_string()."""
 
1032
        return "Bazaar-NG branch, format 0.0.4\n"
 
1033
 
 
1034
    def get_format_description(self):
 
1035
        """See BzrDirFormat.get_format_description()."""
 
1036
        return "All-in-one format 4"
 
1037
 
 
1038
    def get_converter(self, format=None):
 
1039
        """See BzrDirFormat.get_converter()."""
 
1040
        # there is one and only one upgrade path here.
 
1041
        return ConvertBzrDir4To5()
 
1042
        
 
1043
    def initialize_on_transport(self, transport):
 
1044
        """Format 4 branches cannot be created."""
 
1045
        raise errors.UninitializableFormat(self)
 
1046
 
 
1047
    def is_supported(self):
 
1048
        """Format 4 is not supported.
 
1049
 
 
1050
        It is not supported because the model changed from 4 to 5 and the
 
1051
        conversion logic is expensive - so doing it on the fly was not 
 
1052
        feasible.
 
1053
        """
 
1054
        return False
 
1055
 
 
1056
    def _open(self, transport):
 
1057
        """See BzrDirFormat._open."""
 
1058
        return BzrDir4(transport, self)
 
1059
 
 
1060
    def __return_repository_format(self):
 
1061
        """Circular import protection."""
 
1062
        from bzrlib.repository import RepositoryFormat4
 
1063
        return RepositoryFormat4(self)
 
1064
    repository_format = property(__return_repository_format)
 
1065
 
 
1066
 
 
1067
class BzrDirFormat5(BzrDirFormat):
 
1068
    """Bzr control format 5.
 
1069
 
 
1070
    This format is a combined format for working tree, branch and repository.
 
1071
    It has:
 
1072
     - Format 2 working trees [always] 
 
1073
     - Format 4 branches [always] 
 
1074
     - Format 5 repositories [always]
 
1075
       Unhashed stores in the repository.
 
1076
    """
 
1077
 
 
1078
    _lock_class = TransportLock
 
1079
 
 
1080
    def get_format_string(self):
 
1081
        """See BzrDirFormat.get_format_string()."""
 
1082
        return "Bazaar-NG branch, format 5\n"
 
1083
 
 
1084
    def get_format_description(self):
 
1085
        """See BzrDirFormat.get_format_description()."""
 
1086
        return "All-in-one format 5"
 
1087
 
 
1088
    def get_converter(self, format=None):
 
1089
        """See BzrDirFormat.get_converter()."""
 
1090
        # there is one and only one upgrade path here.
 
1091
        return ConvertBzrDir5To6()
 
1092
 
 
1093
    def _initialize_for_clone(self, url):
 
1094
        return self.initialize_on_transport(get_transport(url), _cloning=True)
 
1095
        
 
1096
    def initialize_on_transport(self, transport, _cloning=False):
 
1097
        """Format 5 dirs always have working tree, branch and repository.
 
1098
        
 
1099
        Except when they are being cloned.
 
1100
        """
 
1101
        from bzrlib.branch import BzrBranchFormat4
 
1102
        from bzrlib.repository import RepositoryFormat5
 
1103
        from bzrlib.workingtree import WorkingTreeFormat2
 
1104
        result = (super(BzrDirFormat5, self).initialize_on_transport(transport))
 
1105
        RepositoryFormat5().initialize(result, _internal=True)
 
1106
        if not _cloning:
 
1107
            BzrBranchFormat4().initialize(result)
 
1108
            WorkingTreeFormat2().initialize(result)
 
1109
        return result
 
1110
 
 
1111
    def _open(self, transport):
 
1112
        """See BzrDirFormat._open."""
 
1113
        return BzrDir5(transport, self)
 
1114
 
 
1115
    def __return_repository_format(self):
 
1116
        """Circular import protection."""
 
1117
        from bzrlib.repository import RepositoryFormat5
 
1118
        return RepositoryFormat5(self)
 
1119
    repository_format = property(__return_repository_format)
 
1120
 
 
1121
 
 
1122
class BzrDirFormat6(BzrDirFormat):
 
1123
    """Bzr control format 6.
 
1124
 
 
1125
    This format is a combined format for working tree, branch and repository.
 
1126
    It has:
 
1127
     - Format 2 working trees [always] 
 
1128
     - Format 4 branches [always] 
 
1129
     - Format 6 repositories [always]
 
1130
    """
 
1131
 
 
1132
    _lock_class = TransportLock
 
1133
 
 
1134
    def get_format_string(self):
 
1135
        """See BzrDirFormat.get_format_string()."""
 
1136
        return "Bazaar-NG branch, format 6\n"
 
1137
 
 
1138
    def get_format_description(self):
 
1139
        """See BzrDirFormat.get_format_description()."""
 
1140
        return "All-in-one format 6"
 
1141
 
 
1142
    def get_converter(self, format=None):
 
1143
        """See BzrDirFormat.get_converter()."""
 
1144
        # there is one and only one upgrade path here.
 
1145
        return ConvertBzrDir6ToMeta()
 
1146
        
 
1147
    def _initialize_for_clone(self, url):
 
1148
        return self.initialize_on_transport(get_transport(url), _cloning=True)
 
1149
 
 
1150
    def initialize_on_transport(self, transport, _cloning=False):
 
1151
        """Format 6 dirs always have working tree, branch and repository.
 
1152
        
 
1153
        Except when they are being cloned.
 
1154
        """
 
1155
        from bzrlib.branch import BzrBranchFormat4
 
1156
        from bzrlib.repository import RepositoryFormat6
 
1157
        from bzrlib.workingtree import WorkingTreeFormat2
 
1158
        result = super(BzrDirFormat6, self).initialize_on_transport(transport)
 
1159
        RepositoryFormat6().initialize(result, _internal=True)
 
1160
        if not _cloning:
 
1161
            BzrBranchFormat4().initialize(result)
 
1162
            try:
 
1163
                WorkingTreeFormat2().initialize(result)
 
1164
            except errors.NotLocalUrl:
 
1165
                # emulate pre-check behaviour for working tree and silently 
 
1166
                # fail.
 
1167
                pass
 
1168
        return result
 
1169
 
 
1170
    def _open(self, transport):
 
1171
        """See BzrDirFormat._open."""
 
1172
        return BzrDir6(transport, self)
 
1173
 
 
1174
    def __return_repository_format(self):
 
1175
        """Circular import protection."""
 
1176
        from bzrlib.repository import RepositoryFormat6
 
1177
        return RepositoryFormat6(self)
 
1178
    repository_format = property(__return_repository_format)
 
1179
 
 
1180
 
 
1181
class BzrDirMetaFormat1(BzrDirFormat):
 
1182
    """Bzr meta control format 1
 
1183
 
 
1184
    This is the first format with split out working tree, branch and repository
 
1185
    disk storage.
 
1186
    It has:
 
1187
     - Format 3 working trees [optional]
 
1188
     - Format 5 branches [optional]
 
1189
     - Format 7 repositories [optional]
 
1190
    """
 
1191
 
 
1192
    _lock_class = LockDir
 
1193
 
 
1194
    def get_converter(self, format=None):
 
1195
        """See BzrDirFormat.get_converter()."""
 
1196
        if format is None:
 
1197
            format = BzrDirFormat.get_default_format()
 
1198
        if not isinstance(self, format.__class__):
 
1199
            # converting away from metadir is not implemented
 
1200
            raise NotImplementedError(self.get_converter)
 
1201
        return ConvertMetaToMeta(format)
 
1202
 
 
1203
    def get_format_string(self):
 
1204
        """See BzrDirFormat.get_format_string()."""
 
1205
        return "Bazaar-NG meta directory, format 1\n"
 
1206
 
 
1207
    def get_format_description(self):
 
1208
        """See BzrDirFormat.get_format_description()."""
 
1209
        return "Meta directory format 1"
 
1210
 
 
1211
    def _open(self, transport):
 
1212
        """See BzrDirFormat._open."""
 
1213
        return BzrDirMeta1(transport, self)
 
1214
 
 
1215
    def __return_repository_format(self):
 
1216
        """Circular import protection."""
 
1217
        if getattr(self, '_repository_format', None):
 
1218
            return self._repository_format
 
1219
        from bzrlib.repository import RepositoryFormat
 
1220
        return RepositoryFormat.get_default_format()
 
1221
 
 
1222
    def __set_repository_format(self, value):
 
1223
        """Allow changint the repository format for metadir formats."""
 
1224
        self._repository_format = value
 
1225
 
 
1226
    repository_format = property(__return_repository_format, __set_repository_format)
 
1227
 
 
1228
 
 
1229
BzrDirFormat.register_format(BzrDirFormat4())
 
1230
BzrDirFormat.register_format(BzrDirFormat5())
 
1231
BzrDirFormat.register_format(BzrDirFormat6())
 
1232
__default_format = BzrDirMetaFormat1()
 
1233
BzrDirFormat.register_format(__default_format)
 
1234
BzrDirFormat.set_default_format(__default_format)
 
1235
 
 
1236
 
 
1237
class BzrDirTestProviderAdapter(object):
 
1238
    """A tool to generate a suite testing multiple bzrdir formats at once.
 
1239
 
 
1240
    This is done by copying the test once for each transport and injecting
 
1241
    the transport_server, transport_readonly_server, and bzrdir_format
 
1242
    classes into each copy. Each copy is also given a new id() to make it
 
1243
    easy to identify.
 
1244
    """
 
1245
 
 
1246
    def __init__(self, transport_server, transport_readonly_server, formats):
 
1247
        self._transport_server = transport_server
 
1248
        self._transport_readonly_server = transport_readonly_server
 
1249
        self._formats = formats
 
1250
    
 
1251
    def adapt(self, test):
 
1252
        result = TestSuite()
 
1253
        for format in self._formats:
 
1254
            new_test = deepcopy(test)
 
1255
            new_test.transport_server = self._transport_server
 
1256
            new_test.transport_readonly_server = self._transport_readonly_server
 
1257
            new_test.bzrdir_format = format
 
1258
            def make_new_test_id():
 
1259
                new_id = "%s(%s)" % (new_test.id(), format.__class__.__name__)
 
1260
                return lambda: new_id
 
1261
            new_test.id = make_new_test_id()
 
1262
            result.addTest(new_test)
 
1263
        return result
 
1264
 
 
1265
 
 
1266
class ScratchDir(BzrDir6):
 
1267
    """Special test class: a bzrdir that cleans up itself..
 
1268
 
 
1269
    >>> d = ScratchDir()
 
1270
    >>> base = d.transport.base
 
1271
    >>> isdir(base)
 
1272
    True
 
1273
    >>> b.transport.__del__()
 
1274
    >>> isdir(base)
 
1275
    False
 
1276
    """
 
1277
 
 
1278
    def __init__(self, files=[], dirs=[], transport=None):
 
1279
        """Make a test branch.
 
1280
 
 
1281
        This creates a temporary directory and runs init-tree in it.
 
1282
 
 
1283
        If any files are listed, they are created in the working copy.
 
1284
        """
 
1285
        if transport is None:
 
1286
            transport = bzrlib.transport.local.ScratchTransport()
 
1287
            # local import for scope restriction
 
1288
            BzrDirFormat6().initialize(transport.base)
 
1289
            super(ScratchDir, self).__init__(transport, BzrDirFormat6())
 
1290
            self.create_repository()
 
1291
            self.create_branch()
 
1292
            self.create_workingtree()
 
1293
        else:
 
1294
            super(ScratchDir, self).__init__(transport, BzrDirFormat6())
 
1295
 
 
1296
        # BzrBranch creates a clone to .bzr and then forgets about the
 
1297
        # original transport. A ScratchTransport() deletes itself and
 
1298
        # everything underneath it when it goes away, so we need to
 
1299
        # grab a local copy to prevent that from happening
 
1300
        self._transport = transport
 
1301
 
 
1302
        for d in dirs:
 
1303
            self._transport.mkdir(d)
 
1304
            
 
1305
        for f in files:
 
1306
            self._transport.put(f, 'content of %s' % f)
 
1307
 
 
1308
    def clone(self):
 
1309
        """
 
1310
        >>> orig = ScratchDir(files=["file1", "file2"])
 
1311
        >>> os.listdir(orig.base)
 
1312
        [u'.bzr', u'file1', u'file2']
 
1313
        >>> clone = orig.clone()
 
1314
        >>> if os.name != 'nt':
 
1315
        ...   os.path.samefile(orig.base, clone.base)
 
1316
        ... else:
 
1317
        ...   orig.base == clone.base
 
1318
        ...
 
1319
        False
 
1320
        >>> os.listdir(clone.base)
 
1321
        [u'.bzr', u'file1', u'file2']
 
1322
        """
 
1323
        from shutil import copytree
 
1324
        from bzrlib.osutils import mkdtemp
 
1325
        base = mkdtemp()
 
1326
        os.rmdir(base)
 
1327
        copytree(self.base, base, symlinks=True)
 
1328
        return ScratchDir(
 
1329
            transport=bzrlib.transport.local.ScratchTransport(base))
 
1330
 
 
1331
 
 
1332
class Converter(object):
 
1333
    """Converts a disk format object from one format to another."""
 
1334
 
 
1335
    def convert(self, to_convert, pb):
 
1336
        """Perform the conversion of to_convert, giving feedback via pb.
 
1337
 
 
1338
        :param to_convert: The disk object to convert.
 
1339
        :param pb: a progress bar to use for progress information.
 
1340
        """
 
1341
 
 
1342
    def step(self, message):
 
1343
        """Update the pb by a step."""
 
1344
        self.count +=1
 
1345
        self.pb.update(message, self.count, self.total)
 
1346
 
 
1347
 
 
1348
class ConvertBzrDir4To5(Converter):
 
1349
    """Converts format 4 bzr dirs to format 5."""
 
1350
 
 
1351
    def __init__(self):
 
1352
        super(ConvertBzrDir4To5, self).__init__()
 
1353
        self.converted_revs = set()
 
1354
        self.absent_revisions = set()
 
1355
        self.text_count = 0
 
1356
        self.revisions = {}
 
1357
        
 
1358
    def convert(self, to_convert, pb):
 
1359
        """See Converter.convert()."""
 
1360
        self.bzrdir = to_convert
 
1361
        self.pb = pb
 
1362
        self.pb.note('starting upgrade from format 4 to 5')
 
1363
        if isinstance(self.bzrdir.transport, LocalTransport):
 
1364
            self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
 
1365
        self._convert_to_weaves()
 
1366
        return BzrDir.open(self.bzrdir.root_transport.base)
 
1367
 
 
1368
    def _convert_to_weaves(self):
 
1369
        self.pb.note('note: upgrade may be faster if all store files are ungzipped first')
 
1370
        try:
 
1371
            # TODO permissions
 
1372
            stat = self.bzrdir.transport.stat('weaves')
 
1373
            if not S_ISDIR(stat.st_mode):
 
1374
                self.bzrdir.transport.delete('weaves')
 
1375
                self.bzrdir.transport.mkdir('weaves')
 
1376
        except errors.NoSuchFile:
 
1377
            self.bzrdir.transport.mkdir('weaves')
 
1378
        # deliberately not a WeaveFile as we want to build it up slowly.
 
1379
        self.inv_weave = Weave('inventory')
 
1380
        # holds in-memory weaves for all files
 
1381
        self.text_weaves = {}
 
1382
        self.bzrdir.transport.delete('branch-format')
 
1383
        self.branch = self.bzrdir.open_branch()
 
1384
        self._convert_working_inv()
 
1385
        rev_history = self.branch.revision_history()
 
1386
        # to_read is a stack holding the revisions we still need to process;
 
1387
        # appending to it adds new highest-priority revisions
 
1388
        self.known_revisions = set(rev_history)
 
1389
        self.to_read = rev_history[-1:]
 
1390
        while self.to_read:
 
1391
            rev_id = self.to_read.pop()
 
1392
            if (rev_id not in self.revisions
 
1393
                and rev_id not in self.absent_revisions):
 
1394
                self._load_one_rev(rev_id)
 
1395
        self.pb.clear()
 
1396
        to_import = self._make_order()
 
1397
        for i, rev_id in enumerate(to_import):
 
1398
            self.pb.update('converting revision', i, len(to_import))
 
1399
            self._convert_one_rev(rev_id)
 
1400
        self.pb.clear()
 
1401
        self._write_all_weaves()
 
1402
        self._write_all_revs()
 
1403
        self.pb.note('upgraded to weaves:')
 
1404
        self.pb.note('  %6d revisions and inventories', len(self.revisions))
 
1405
        self.pb.note('  %6d revisions not present', len(self.absent_revisions))
 
1406
        self.pb.note('  %6d texts', self.text_count)
 
1407
        self._cleanup_spare_files_after_format4()
 
1408
        self.branch.control_files.put_utf8('branch-format', BzrDirFormat5().get_format_string())
 
1409
 
 
1410
    def _cleanup_spare_files_after_format4(self):
 
1411
        # FIXME working tree upgrade foo.
 
1412
        for n in 'merged-patches', 'pending-merged-patches':
 
1413
            try:
 
1414
                ## assert os.path.getsize(p) == 0
 
1415
                self.bzrdir.transport.delete(n)
 
1416
            except errors.NoSuchFile:
 
1417
                pass
 
1418
        self.bzrdir.transport.delete_tree('inventory-store')
 
1419
        self.bzrdir.transport.delete_tree('text-store')
 
1420
 
 
1421
    def _convert_working_inv(self):
 
1422
        inv = serializer_v4.read_inventory(self.branch.control_files.get('inventory'))
 
1423
        new_inv_xml = serializer_v5.write_inventory_to_string(inv)
 
1424
        # FIXME inventory is a working tree change.
 
1425
        self.branch.control_files.put('inventory', new_inv_xml)
 
1426
 
 
1427
    def _write_all_weaves(self):
 
1428
        controlweaves = WeaveStore(self.bzrdir.transport, prefixed=False)
 
1429
        weave_transport = self.bzrdir.transport.clone('weaves')
 
1430
        weaves = WeaveStore(weave_transport, prefixed=False)
 
1431
        transaction = WriteTransaction()
 
1432
 
 
1433
        try:
 
1434
            i = 0
 
1435
            for file_id, file_weave in self.text_weaves.items():
 
1436
                self.pb.update('writing weave', i, len(self.text_weaves))
 
1437
                weaves._put_weave(file_id, file_weave, transaction)
 
1438
                i += 1
 
1439
            self.pb.update('inventory', 0, 1)
 
1440
            controlweaves._put_weave('inventory', self.inv_weave, transaction)
 
1441
            self.pb.update('inventory', 1, 1)
 
1442
        finally:
 
1443
            self.pb.clear()
 
1444
 
 
1445
    def _write_all_revs(self):
 
1446
        """Write all revisions out in new form."""
 
1447
        self.bzrdir.transport.delete_tree('revision-store')
 
1448
        self.bzrdir.transport.mkdir('revision-store')
 
1449
        revision_transport = self.bzrdir.transport.clone('revision-store')
 
1450
        # TODO permissions
 
1451
        _revision_store = TextRevisionStore(TextStore(revision_transport,
 
1452
                                                      prefixed=False,
 
1453
                                                      compressed=True))
 
1454
        try:
 
1455
            transaction = bzrlib.transactions.WriteTransaction()
 
1456
            for i, rev_id in enumerate(self.converted_revs):
 
1457
                self.pb.update('write revision', i, len(self.converted_revs))
 
1458
                _revision_store.add_revision(self.revisions[rev_id], transaction)
 
1459
        finally:
 
1460
            self.pb.clear()
 
1461
            
 
1462
    def _load_one_rev(self, rev_id):
 
1463
        """Load a revision object into memory.
 
1464
 
 
1465
        Any parents not either loaded or abandoned get queued to be
 
1466
        loaded."""
 
1467
        self.pb.update('loading revision',
 
1468
                       len(self.revisions),
 
1469
                       len(self.known_revisions))
 
1470
        if not self.branch.repository.has_revision(rev_id):
 
1471
            self.pb.clear()
 
1472
            self.pb.note('revision {%s} not present in branch; '
 
1473
                         'will be converted as a ghost',
 
1474
                         rev_id)
 
1475
            self.absent_revisions.add(rev_id)
 
1476
        else:
 
1477
            rev = self.branch.repository._revision_store.get_revision(rev_id,
 
1478
                self.branch.repository.get_transaction())
 
1479
            for parent_id in rev.parent_ids:
 
1480
                self.known_revisions.add(parent_id)
 
1481
                self.to_read.append(parent_id)
 
1482
            self.revisions[rev_id] = rev
 
1483
 
 
1484
    def _load_old_inventory(self, rev_id):
 
1485
        assert rev_id not in self.converted_revs
 
1486
        old_inv_xml = self.branch.repository.inventory_store.get(rev_id).read()
 
1487
        inv = serializer_v4.read_inventory_from_string(old_inv_xml)
 
1488
        rev = self.revisions[rev_id]
 
1489
        if rev.inventory_sha1:
 
1490
            assert rev.inventory_sha1 == sha_string(old_inv_xml), \
 
1491
                'inventory sha mismatch for {%s}' % rev_id
 
1492
        return inv
 
1493
 
 
1494
    def _load_updated_inventory(self, rev_id):
 
1495
        assert rev_id in self.converted_revs
 
1496
        inv_xml = self.inv_weave.get_text(rev_id)
 
1497
        inv = serializer_v5.read_inventory_from_string(inv_xml)
 
1498
        return inv
 
1499
 
 
1500
    def _convert_one_rev(self, rev_id):
 
1501
        """Convert revision and all referenced objects to new format."""
 
1502
        rev = self.revisions[rev_id]
 
1503
        inv = self._load_old_inventory(rev_id)
 
1504
        present_parents = [p for p in rev.parent_ids
 
1505
                           if p not in self.absent_revisions]
 
1506
        self._convert_revision_contents(rev, inv, present_parents)
 
1507
        self._store_new_weave(rev, inv, present_parents)
 
1508
        self.converted_revs.add(rev_id)
 
1509
 
 
1510
    def _store_new_weave(self, rev, inv, present_parents):
 
1511
        # the XML is now updated with text versions
 
1512
        if __debug__:
 
1513
            for file_id in inv:
 
1514
                ie = inv[file_id]
 
1515
                if ie.kind == 'root_directory':
 
1516
                    continue
 
1517
                assert hasattr(ie, 'revision'), \
 
1518
                    'no revision on {%s} in {%s}' % \
 
1519
                    (file_id, rev.revision_id)
 
1520
        new_inv_xml = serializer_v5.write_inventory_to_string(inv)
 
1521
        new_inv_sha1 = sha_string(new_inv_xml)
 
1522
        self.inv_weave.add_lines(rev.revision_id, 
 
1523
                                 present_parents,
 
1524
                                 new_inv_xml.splitlines(True))
 
1525
        rev.inventory_sha1 = new_inv_sha1
 
1526
 
 
1527
    def _convert_revision_contents(self, rev, inv, present_parents):
 
1528
        """Convert all the files within a revision.
 
1529
 
 
1530
        Also upgrade the inventory to refer to the text revision ids."""
 
1531
        rev_id = rev.revision_id
 
1532
        mutter('converting texts of revision {%s}',
 
1533
               rev_id)
 
1534
        parent_invs = map(self._load_updated_inventory, present_parents)
 
1535
        for file_id in inv:
 
1536
            ie = inv[file_id]
 
1537
            self._convert_file_version(rev, ie, parent_invs)
 
1538
 
 
1539
    def _convert_file_version(self, rev, ie, parent_invs):
 
1540
        """Convert one version of one file.
 
1541
 
 
1542
        The file needs to be added into the weave if it is a merge
 
1543
        of >=2 parents or if it's changed from its parent.
 
1544
        """
 
1545
        if ie.kind == 'root_directory':
 
1546
            return
 
1547
        file_id = ie.file_id
 
1548
        rev_id = rev.revision_id
 
1549
        w = self.text_weaves.get(file_id)
 
1550
        if w is None:
 
1551
            w = Weave(file_id)
 
1552
            self.text_weaves[file_id] = w
 
1553
        text_changed = False
 
1554
        previous_entries = ie.find_previous_heads(parent_invs,
 
1555
                                                  None,
 
1556
                                                  None,
 
1557
                                                  entry_vf=w)
 
1558
        for old_revision in previous_entries:
 
1559
                # if this fails, its a ghost ?
 
1560
                assert old_revision in self.converted_revs 
 
1561
        self.snapshot_ie(previous_entries, ie, w, rev_id)
 
1562
        del ie.text_id
 
1563
        assert getattr(ie, 'revision', None) is not None
 
1564
 
 
1565
    def snapshot_ie(self, previous_revisions, ie, w, rev_id):
 
1566
        # TODO: convert this logic, which is ~= snapshot to
 
1567
        # a call to:. This needs the path figured out. rather than a work_tree
 
1568
        # a v4 revision_tree can be given, or something that looks enough like
 
1569
        # one to give the file content to the entry if it needs it.
 
1570
        # and we need something that looks like a weave store for snapshot to 
 
1571
        # save against.
 
1572
        #ie.snapshot(rev, PATH, previous_revisions, REVISION_TREE, InMemoryWeaveStore(self.text_weaves))
 
1573
        if len(previous_revisions) == 1:
 
1574
            previous_ie = previous_revisions.values()[0]
 
1575
            if ie._unchanged(previous_ie):
 
1576
                ie.revision = previous_ie.revision
 
1577
                return
 
1578
        if ie.has_text():
 
1579
            text = self.branch.repository.text_store.get(ie.text_id)
 
1580
            file_lines = text.readlines()
 
1581
            assert sha_strings(file_lines) == ie.text_sha1
 
1582
            assert sum(map(len, file_lines)) == ie.text_size
 
1583
            w.add_lines(rev_id, previous_revisions, file_lines)
 
1584
            self.text_count += 1
 
1585
        else:
 
1586
            w.add_lines(rev_id, previous_revisions, [])
 
1587
        ie.revision = rev_id
 
1588
 
 
1589
    def _make_order(self):
 
1590
        """Return a suitable order for importing revisions.
 
1591
 
 
1592
        The order must be such that an revision is imported after all
 
1593
        its (present) parents.
 
1594
        """
 
1595
        todo = set(self.revisions.keys())
 
1596
        done = self.absent_revisions.copy()
 
1597
        order = []
 
1598
        while todo:
 
1599
            # scan through looking for a revision whose parents
 
1600
            # are all done
 
1601
            for rev_id in sorted(list(todo)):
 
1602
                rev = self.revisions[rev_id]
 
1603
                parent_ids = set(rev.parent_ids)
 
1604
                if parent_ids.issubset(done):
 
1605
                    # can take this one now
 
1606
                    order.append(rev_id)
 
1607
                    todo.remove(rev_id)
 
1608
                    done.add(rev_id)
 
1609
        return order
 
1610
 
 
1611
 
 
1612
class ConvertBzrDir5To6(Converter):
 
1613
    """Converts format 5 bzr dirs to format 6."""
 
1614
 
 
1615
    def convert(self, to_convert, pb):
 
1616
        """See Converter.convert()."""
 
1617
        self.bzrdir = to_convert
 
1618
        self.pb = pb
 
1619
        self.pb.note('starting upgrade from format 5 to 6')
 
1620
        self._convert_to_prefixed()
 
1621
        return BzrDir.open(self.bzrdir.root_transport.base)
 
1622
 
 
1623
    def _convert_to_prefixed(self):
 
1624
        from bzrlib.store import TransportStore
 
1625
        self.bzrdir.transport.delete('branch-format')
 
1626
        for store_name in ["weaves", "revision-store"]:
 
1627
            self.pb.note("adding prefixes to %s" % store_name)
 
1628
            store_transport = self.bzrdir.transport.clone(store_name)
 
1629
            store = TransportStore(store_transport, prefixed=True)
 
1630
            for urlfilename in store_transport.list_dir('.'):
 
1631
                filename = urlutils.unescape(urlfilename)
 
1632
                if (filename.endswith(".weave") or
 
1633
                    filename.endswith(".gz") or
 
1634
                    filename.endswith(".sig")):
 
1635
                    file_id = os.path.splitext(filename)[0]
 
1636
                else:
 
1637
                    file_id = filename
 
1638
                prefix_dir = store.hash_prefix(file_id)
 
1639
                # FIXME keep track of the dirs made RBC 20060121
 
1640
                try:
 
1641
                    store_transport.move(filename, prefix_dir + '/' + filename)
 
1642
                except errors.NoSuchFile: # catches missing dirs strangely enough
 
1643
                    store_transport.mkdir(prefix_dir)
 
1644
                    store_transport.move(filename, prefix_dir + '/' + filename)
 
1645
        self.bzrdir._control_files.put_utf8('branch-format', BzrDirFormat6().get_format_string())
 
1646
 
 
1647
 
 
1648
class ConvertBzrDir6ToMeta(Converter):
 
1649
    """Converts format 6 bzr dirs to metadirs."""
 
1650
 
 
1651
    def convert(self, to_convert, pb):
 
1652
        """See Converter.convert()."""
 
1653
        self.bzrdir = to_convert
 
1654
        self.pb = pb
 
1655
        self.count = 0
 
1656
        self.total = 20 # the steps we know about
 
1657
        self.garbage_inventories = []
 
1658
 
 
1659
        self.pb.note('starting upgrade from format 6 to metadir')
 
1660
        self.bzrdir._control_files.put_utf8('branch-format', "Converting to format 6")
 
1661
        # its faster to move specific files around than to open and use the apis...
 
1662
        # first off, nuke ancestry.weave, it was never used.
 
1663
        try:
 
1664
            self.step('Removing ancestry.weave')
 
1665
            self.bzrdir.transport.delete('ancestry.weave')
 
1666
        except errors.NoSuchFile:
 
1667
            pass
 
1668
        # find out whats there
 
1669
        self.step('Finding branch files')
 
1670
        last_revision = self.bzrdir.open_branch().last_revision()
 
1671
        bzrcontents = self.bzrdir.transport.list_dir('.')
 
1672
        for name in bzrcontents:
 
1673
            if name.startswith('basis-inventory.'):
 
1674
                self.garbage_inventories.append(name)
 
1675
        # create new directories for repository, working tree and branch
 
1676
        self.dir_mode = self.bzrdir._control_files._dir_mode
 
1677
        self.file_mode = self.bzrdir._control_files._file_mode
 
1678
        repository_names = [('inventory.weave', True),
 
1679
                            ('revision-store', True),
 
1680
                            ('weaves', True)]
 
1681
        self.step('Upgrading repository  ')
 
1682
        self.bzrdir.transport.mkdir('repository', mode=self.dir_mode)
 
1683
        self.make_lock('repository')
 
1684
        # we hard code the formats here because we are converting into
 
1685
        # the meta format. The meta format upgrader can take this to a 
 
1686
        # future format within each component.
 
1687
        self.put_format('repository', bzrlib.repository.RepositoryFormat7())
 
1688
        for entry in repository_names:
 
1689
            self.move_entry('repository', entry)
 
1690
 
 
1691
        self.step('Upgrading branch      ')
 
1692
        self.bzrdir.transport.mkdir('branch', mode=self.dir_mode)
 
1693
        self.make_lock('branch')
 
1694
        self.put_format('branch', bzrlib.branch.BzrBranchFormat5())
 
1695
        branch_files = [('revision-history', True),
 
1696
                        ('branch-name', True),
 
1697
                        ('parent', False)]
 
1698
        for entry in branch_files:
 
1699
            self.move_entry('branch', entry)
 
1700
 
 
1701
        self.step('Upgrading working tree')
 
1702
        self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
 
1703
        self.make_lock('checkout')
 
1704
        self.put_format('checkout', bzrlib.workingtree.WorkingTreeFormat3())
 
1705
        self.bzrdir.transport.delete_multi(self.garbage_inventories, self.pb)
 
1706
        checkout_files = [('pending-merges', True),
 
1707
                          ('inventory', True),
 
1708
                          ('stat-cache', False)]
 
1709
        for entry in checkout_files:
 
1710
            self.move_entry('checkout', entry)
 
1711
        if last_revision is not None:
 
1712
            self.bzrdir._control_files.put_utf8('checkout/last-revision',
 
1713
                                                last_revision)
 
1714
        self.bzrdir._control_files.put_utf8('branch-format', BzrDirMetaFormat1().get_format_string())
 
1715
        return BzrDir.open(self.bzrdir.root_transport.base)
 
1716
 
 
1717
    def make_lock(self, name):
 
1718
        """Make a lock for the new control dir name."""
 
1719
        self.step('Make %s lock' % name)
 
1720
        ld = LockDir(self.bzrdir.transport, 
 
1721
                     '%s/lock' % name,
 
1722
                     file_modebits=self.file_mode,
 
1723
                     dir_modebits=self.dir_mode)
 
1724
        ld.create()
 
1725
 
 
1726
    def move_entry(self, new_dir, entry):
 
1727
        """Move then entry name into new_dir."""
 
1728
        name = entry[0]
 
1729
        mandatory = entry[1]
 
1730
        self.step('Moving %s' % name)
 
1731
        try:
 
1732
            self.bzrdir.transport.move(name, '%s/%s' % (new_dir, name))
 
1733
        except errors.NoSuchFile:
 
1734
            if mandatory:
 
1735
                raise
 
1736
 
 
1737
    def put_format(self, dirname, format):
 
1738
        self.bzrdir._control_files.put_utf8('%s/format' % dirname, format.get_format_string())
 
1739
 
 
1740
 
 
1741
class ConvertMetaToMeta(Converter):
 
1742
    """Converts the components of metadirs."""
 
1743
 
 
1744
    def __init__(self, target_format):
 
1745
        """Create a metadir to metadir converter.
 
1746
 
 
1747
        :param target_format: The final metadir format that is desired.
 
1748
        """
 
1749
        self.target_format = target_format
 
1750
 
 
1751
    def convert(self, to_convert, pb):
 
1752
        """See Converter.convert()."""
 
1753
        self.bzrdir = to_convert
 
1754
        self.pb = pb
 
1755
        self.count = 0
 
1756
        self.total = 1
 
1757
        self.step('checking repository format')
 
1758
        try:
 
1759
            repo = self.bzrdir.open_repository()
 
1760
        except errors.NoRepositoryPresent:
 
1761
            pass
 
1762
        else:
 
1763
            if not isinstance(repo._format, self.target_format.repository_format.__class__):
 
1764
                from bzrlib.repository import CopyConverter
 
1765
                self.pb.note('starting repository conversion')
 
1766
                converter = CopyConverter(self.target_format.repository_format)
 
1767
                converter.convert(repo, pb)
 
1768
        return to_convert