/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

Various hopefully improvements, but wsgi is broken, handing over to spiv :).

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