/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

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