/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

  • Committer: John Arbash Meinel
  • Date: 2006-09-13 02:44:23 UTC
  • mto: This revision was merged to the branch mainline in revision 2071.
  • Revision ID: john@arbash-meinel.com-20060913024423-2f0729076ddd4e31
lazy_import osutils and sign_my_commits
Move doc tests into test_osutils, since lazy_import doesn't play nicely
with DocTest

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