~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

  • Committer: Wouter van Heyst
  • Date: 2006-06-07 16:05:27 UTC
  • mto: This revision was merged to the branch mainline in revision 1752.
  • Revision ID: larstiq@larstiq.dyndns.org-20060607160527-2b3649154d0e2e84
more code cleanup

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