~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

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