/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

Merge bzr.dev

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