/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

fix up reparent_children

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