1
# Copyright (C) 2005, 2006 Canonical Ltd
 
 
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.
 
 
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.
 
 
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
 
 
17
"""BzrDir logic. The BzrDir is the basic control directory used by bzr.
 
 
19
At format 7 this was split out into Branch, Repository and Checkout control
 
 
23
from copy import deepcopy
 
 
25
from cStringIO import StringIO
 
 
26
from unittest import TestSuite
 
 
29
import bzrlib.errors as errors
 
 
30
from bzrlib.lockable_files import LockableFiles, TransportLock
 
 
31
from bzrlib.lockdir import LockDir
 
 
32
from bzrlib.osutils import (
 
 
39
from bzrlib.store.revision.text import TextRevisionStore
 
 
40
from bzrlib.store.text import TextStore
 
 
41
from bzrlib.store.versioned import WeaveStore
 
 
42
from bzrlib.symbol_versioning import *
 
 
43
from bzrlib.trace import mutter
 
 
44
from bzrlib.transactions import WriteTransaction
 
 
45
from bzrlib.transport import get_transport
 
 
46
from bzrlib.transport.local import LocalTransport
 
 
47
import bzrlib.urlutils as urlutils
 
 
48
from bzrlib.weave import Weave
 
 
49
from bzrlib.xml4 import serializer_v4
 
 
54
    """A .bzr control diretory.
 
 
56
    BzrDir instances let you create or open any of the things that can be
 
 
57
    found within .bzr - checkouts, branches and repositories.
 
 
60
        the transport which this bzr dir is rooted at (i.e. file:///.../.bzr/)
 
 
62
        a transport connected to the directory this bzr was opened from.
 
 
66
        """Invoke break_lock on the first object in the bzrdir.
 
 
68
        If there is a tree, the tree is opened and break_lock() called.
 
 
69
        Otherwise, branch is tried, and finally repository.
 
 
72
            thing_to_unlock = self.open_workingtree()
 
 
73
        except (errors.NotLocalUrl, errors.NoWorkingTree):
 
 
75
                thing_to_unlock = self.open_branch()
 
 
76
            except errors.NotBranchError:
 
 
78
                    thing_to_unlock = self.open_repository()
 
 
79
                except errors.NoRepositoryPresent:
 
 
81
        thing_to_unlock.break_lock()
 
 
83
    def can_convert_format(self):
 
 
84
        """Return true if this bzrdir is one whose format we can convert from."""
 
 
88
    def _check_supported(format, allow_unsupported):
 
 
89
        """Check whether format is a supported format.
 
 
91
        If allow_unsupported is True, this is a no-op.
 
 
93
        if not allow_unsupported and not format.is_supported():
 
 
94
            # see open_downlevel to open legacy branches.
 
 
95
            raise errors.UnsupportedFormatError(
 
 
96
                    'sorry, format %s not supported' % format,
 
 
97
                    ['use a different bzr version',
 
 
98
                     'or remove the .bzr directory'
 
 
99
                     ' and "bzr init" again'])
 
 
101
    def clone(self, url, revision_id=None, basis=None, force_new_repo=False):
 
 
102
        """Clone this bzrdir and its contents to url verbatim.
 
 
104
        If urls last component does not exist, it will be created.
 
 
106
        if revision_id is not None, then the clone operation may tune
 
 
107
            itself to download less data.
 
 
108
        :param force_new_repo: Do not use a shared repository for the target 
 
 
109
                               even if one is available.
 
 
112
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
 
 
113
        result = self._format.initialize(url)
 
 
115
            local_repo = self.find_repository()
 
 
116
        except errors.NoRepositoryPresent:
 
 
119
            # may need to copy content in
 
 
121
                result_repo = local_repo.clone(
 
 
123
                    revision_id=revision_id,
 
 
125
                result_repo.set_make_working_trees(local_repo.make_working_trees())
 
 
128
                    result_repo = result.find_repository()
 
 
129
                    # fetch content this dir needs.
 
 
131
                        # XXX FIXME RBC 20060214 need tests for this when the basis
 
 
133
                        result_repo.fetch(basis_repo, revision_id=revision_id)
 
 
134
                    result_repo.fetch(local_repo, revision_id=revision_id)
 
 
135
                except errors.NoRepositoryPresent:
 
 
136
                    # needed to make one anyway.
 
 
137
                    result_repo = local_repo.clone(
 
 
139
                        revision_id=revision_id,
 
 
141
                    result_repo.set_make_working_trees(local_repo.make_working_trees())
 
 
142
        # 1 if there is a branch present
 
 
143
        #   make sure its content is available in the target repository
 
 
146
            self.open_branch().clone(result, revision_id=revision_id)
 
 
147
        except errors.NotBranchError:
 
 
150
            self.open_workingtree().clone(result, basis=basis_tree)
 
 
151
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
 
155
    def _get_basis_components(self, basis):
 
 
156
        """Retrieve the basis components that are available at basis."""
 
 
158
            return None, None, None
 
 
160
            basis_tree = basis.open_workingtree()
 
 
161
            basis_branch = basis_tree.branch
 
 
162
            basis_repo = basis_branch.repository
 
 
163
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
 
166
                basis_branch = basis.open_branch()
 
 
167
                basis_repo = basis_branch.repository
 
 
168
            except errors.NotBranchError:
 
 
171
                    basis_repo = basis.open_repository()
 
 
172
                except errors.NoRepositoryPresent:
 
 
174
        return basis_repo, basis_branch, basis_tree
 
 
176
    # TODO: This should be given a Transport, and should chdir up; otherwise
 
 
177
    # this will open a new connection.
 
 
178
    def _make_tail(self, url):
 
 
179
        head, tail = urlutils.split(url)
 
 
180
        if tail and tail != '.':
 
 
181
            t = bzrlib.transport.get_transport(head)
 
 
184
            except errors.FileExists:
 
 
187
    # TODO: Should take a Transport
 
 
189
    def create(cls, base):
 
 
190
        """Create a new BzrDir at the url 'base'.
 
 
192
        This will call the current default formats initialize with base
 
 
193
        as the only parameter.
 
 
195
        If you need a specific format, consider creating an instance
 
 
196
        of that and calling initialize().
 
 
198
        if cls is not BzrDir:
 
 
199
            raise AssertionError("BzrDir.create always creates the default format, "
 
 
200
                    "not one of %r" % cls)
 
 
201
        head, tail = urlutils.split(base)
 
 
202
        if tail and tail != '.':
 
 
203
            t = bzrlib.transport.get_transport(head)
 
 
206
            except errors.FileExists:
 
 
208
        return BzrDirFormat.get_default_format().initialize(safe_unicode(base))
 
 
210
    def create_branch(self):
 
 
211
        """Create a branch in this BzrDir.
 
 
213
        The bzrdirs format will control what branch format is created.
 
 
214
        For more control see BranchFormatXX.create(a_bzrdir).
 
 
216
        raise NotImplementedError(self.create_branch)
 
 
219
    def create_branch_and_repo(base, force_new_repo=False):
 
 
220
        """Create a new BzrDir, Branch and Repository at the url 'base'.
 
 
222
        This will use the current default BzrDirFormat, and use whatever 
 
 
223
        repository format that that uses via bzrdir.create_branch and
 
 
224
        create_repository. If a shared repository is available that is used
 
 
227
        The created Branch object is returned.
 
 
229
        :param base: The URL to create the branch at.
 
 
230
        :param force_new_repo: If True a new repository is always created.
 
 
232
        bzrdir = BzrDir.create(base)
 
 
233
        bzrdir._find_or_create_repository(force_new_repo)
 
 
234
        return bzrdir.create_branch()
 
 
236
    def _find_or_create_repository(self, force_new_repo):
 
 
237
        """Create a new repository if needed, returning the repository."""
 
 
239
            return self.create_repository()
 
 
241
            return self.find_repository()
 
 
242
        except errors.NoRepositoryPresent:
 
 
243
            return self.create_repository()
 
 
246
    def create_branch_convenience(base, force_new_repo=False,
 
 
247
                                  force_new_tree=None, format=None):
 
 
248
        """Create a new BzrDir, Branch and Repository at the url 'base'.
 
 
250
        This is a convenience function - it will use an existing repository
 
 
251
        if possible, can be told explicitly whether to create a working tree or
 
 
254
        This will use the current default BzrDirFormat, and use whatever 
 
 
255
        repository format that that uses via bzrdir.create_branch and
 
 
256
        create_repository. If a shared repository is available that is used
 
 
257
        preferentially. Whatever repository is used, its tree creation policy
 
 
260
        The created Branch object is returned.
 
 
261
        If a working tree cannot be made due to base not being a file:// url,
 
 
262
        no error is raised unless force_new_tree is True, in which case no 
 
 
263
        data is created on disk and NotLocalUrl is raised.
 
 
265
        :param base: The URL to create the branch at.
 
 
266
        :param force_new_repo: If True a new repository is always created.
 
 
267
        :param force_new_tree: If True or False force creation of a tree or 
 
 
268
                               prevent such creation respectively.
 
 
269
        :param format: Override for the for the bzrdir format to create
 
 
272
            # check for non local urls
 
 
273
            t = get_transport(safe_unicode(base))
 
 
274
            if not isinstance(t, LocalTransport):
 
 
275
                raise errors.NotLocalUrl(base)
 
 
277
            bzrdir = BzrDir.create(base)
 
 
279
            bzrdir = format.initialize(base)
 
 
280
        repo = bzrdir._find_or_create_repository(force_new_repo)
 
 
281
        result = bzrdir.create_branch()
 
 
282
        if force_new_tree or (repo.make_working_trees() and 
 
 
283
                              force_new_tree is None):
 
 
285
                bzrdir.create_workingtree()
 
 
286
            except errors.NotLocalUrl:
 
 
291
    def create_repository(base, shared=False):
 
 
292
        """Create a new BzrDir and Repository at the url 'base'.
 
 
294
        This will use the current default BzrDirFormat, and use whatever 
 
 
295
        repository format that that uses for bzrdirformat.create_repository.
 
 
297
        ;param shared: Create a shared repository rather than a standalone
 
 
299
        The Repository object is returned.
 
 
301
        This must be overridden as an instance method in child classes, where
 
 
302
        it should take no parameters and construct whatever repository format
 
 
303
        that child class desires.
 
 
305
        bzrdir = BzrDir.create(base)
 
 
306
        return bzrdir.create_repository()
 
 
309
    def create_standalone_workingtree(base):
 
 
310
        """Create a new BzrDir, WorkingTree, Branch and Repository at 'base'.
 
 
312
        'base' must be a local path or a file:// url.
 
 
314
        This will use the current default BzrDirFormat, and use whatever 
 
 
315
        repository format that that uses for bzrdirformat.create_workingtree,
 
 
316
        create_branch and create_repository.
 
 
318
        The WorkingTree object is returned.
 
 
320
        t = get_transport(safe_unicode(base))
 
 
321
        if not isinstance(t, LocalTransport):
 
 
322
            raise errors.NotLocalUrl(base)
 
 
323
        bzrdir = BzrDir.create_branch_and_repo(safe_unicode(base),
 
 
324
                                               force_new_repo=True).bzrdir
 
 
325
        return bzrdir.create_workingtree()
 
 
327
    def create_workingtree(self, revision_id=None):
 
 
328
        """Create a working tree at this BzrDir.
 
 
330
        revision_id: create it as of this revision id.
 
 
332
        raise NotImplementedError(self.create_workingtree)
 
 
334
    def find_repository(self):
 
 
335
        """Find the repository that should be used for a_bzrdir.
 
 
337
        This does not require a branch as we use it to find the repo for
 
 
338
        new branches as well as to hook existing branches up to their
 
 
342
            return self.open_repository()
 
 
343
        except errors.NoRepositoryPresent:
 
 
345
        next_transport = self.root_transport.clone('..')
 
 
348
                found_bzrdir = BzrDir.open_containing_from_transport(
 
 
350
            except errors.NotBranchError:
 
 
351
                raise errors.NoRepositoryPresent(self)
 
 
353
                repository = found_bzrdir.open_repository()
 
 
354
            except errors.NoRepositoryPresent:
 
 
355
                next_transport = found_bzrdir.root_transport.clone('..')
 
 
357
            if ((found_bzrdir.root_transport.base == 
 
 
358
                 self.root_transport.base) or repository.is_shared()):
 
 
361
                raise errors.NoRepositoryPresent(self)
 
 
362
        raise errors.NoRepositoryPresent(self)
 
 
364
    def get_branch_transport(self, branch_format):
 
 
365
        """Get the transport for use by branch format in this BzrDir.
 
 
367
        Note that bzr dirs that do not support format strings will raise
 
 
368
        IncompatibleFormat if the branch format they are given has
 
 
369
        a format string, and vice verca.
 
 
371
        If branch_format is None, the transport is returned with no 
 
 
372
        checking. if it is not None, then the returned transport is
 
 
373
        guaranteed to point to an existing directory ready for use.
 
 
375
        raise NotImplementedError(self.get_branch_transport)
 
 
377
    def get_repository_transport(self, repository_format):
 
 
378
        """Get the transport for use by repository format in this BzrDir.
 
 
380
        Note that bzr dirs that do not support format strings will raise
 
 
381
        IncompatibleFormat if the repository format they are given has
 
 
382
        a format string, and vice verca.
 
 
384
        If repository_format is None, the transport is returned with no 
 
 
385
        checking. if it is not None, then the returned transport is
 
 
386
        guaranteed to point to an existing directory ready for use.
 
 
388
        raise NotImplementedError(self.get_repository_transport)
 
 
390
    def get_workingtree_transport(self, tree_format):
 
 
391
        """Get the transport for use by workingtree format in this BzrDir.
 
 
393
        Note that bzr dirs that do not support format strings will raise
 
 
394
        IncompatibleFormat if the workingtree format they are given has
 
 
395
        a format string, and vice verca.
 
 
397
        If workingtree_format is None, the transport is returned with no 
 
 
398
        checking. if it is not None, then the returned transport is
 
 
399
        guaranteed to point to an existing directory ready for use.
 
 
401
        raise NotImplementedError(self.get_workingtree_transport)
 
 
403
    def __init__(self, _transport, _format):
 
 
404
        """Initialize a Bzr control dir object.
 
 
406
        Only really common logic should reside here, concrete classes should be
 
 
407
        made with varying behaviours.
 
 
409
        :param _format: the format that is creating this BzrDir instance.
 
 
410
        :param _transport: the transport this dir is based at.
 
 
412
        self._format = _format
 
 
413
        self.transport = _transport.clone('.bzr')
 
 
414
        self.root_transport = _transport
 
 
416
    def is_control_filename(self, filename):
 
 
417
        """True if filename is the name of a path which is reserved for bzrdir's.
 
 
419
        :param filename: A filename within the root transport of this bzrdir.
 
 
421
        This is true IF and ONLY IF the filename is part of the namespace reserved
 
 
422
        for bzr control dirs. Currently this is the '.bzr' directory in the root
 
 
423
        of the root_transport. it is expected that plugins will need to extend
 
 
424
        this in the future - for instance to make bzr talk with svn working
 
 
427
        # this might be better on the BzrDirFormat class because it refers to 
 
 
428
        # all the possible bzrdir disk formats. 
 
 
429
        # This method is tested via the workingtree is_control_filename tests- 
 
 
430
        # it was extractd from WorkingTree.is_control_filename. If the methods
 
 
431
        # contract is extended beyond the current trivial  implementation please
 
 
432
        # add new tests for it to the appropriate place.
 
 
433
        return filename == '.bzr' or filename.startswith('.bzr/')
 
 
435
    def needs_format_conversion(self, format=None):
 
 
436
        """Return true if this bzrdir needs convert_format run on it.
 
 
438
        For instance, if the repository format is out of date but the 
 
 
439
        branch and working tree are not, this should return True.
 
 
441
        :param format: Optional parameter indicating a specific desired
 
 
442
                       format we plan to arrive at.
 
 
444
        raise NotImplementedError(self.needs_format_conversion)
 
 
447
    def open_unsupported(base):
 
 
448
        """Open a branch which is not supported."""
 
 
449
        return BzrDir.open(base, _unsupported=True)
 
 
452
    def open(base, _unsupported=False):
 
 
453
        """Open an existing bzrdir, rooted at 'base' (url)
 
 
455
        _unsupported is a private parameter to the BzrDir class.
 
 
457
        t = get_transport(base)
 
 
458
        mutter("trying to open %r with transport %r", base, t)
 
 
459
        format = BzrDirFormat.find_format(t)
 
 
460
        BzrDir._check_supported(format, _unsupported)
 
 
461
        return format.open(t, _found=True)
 
 
463
    def open_branch(self, unsupported=False):
 
 
464
        """Open the branch object at this BzrDir if one is present.
 
 
466
        If unsupported is True, then no longer supported branch formats can
 
 
469
        TODO: static convenience version of this?
 
 
471
        raise NotImplementedError(self.open_branch)
 
 
474
    def open_containing(url):
 
 
475
        """Open an existing branch which contains url.
 
 
477
        :param url: url to search from.
 
 
478
        See open_containing_from_transport for more detail.
 
 
480
        return BzrDir.open_containing_from_transport(get_transport(url))
 
 
483
    def open_containing_from_transport(a_transport):
 
 
484
        """Open an existing branch which contains a_transport.base
 
 
486
        This probes for a branch at a_transport, and searches upwards from there.
 
 
488
        Basically we keep looking up until we find the control directory or
 
 
489
        run into the root.  If there isn't one, raises NotBranchError.
 
 
490
        If there is one and it is either an unrecognised format or an unsupported 
 
 
491
        format, UnknownFormatError or UnsupportedFormatError are raised.
 
 
492
        If there is one, it is returned, along with the unused portion of url.
 
 
494
        :return: The BzrDir that contains the path, and a Unicode path 
 
 
495
                for the rest of the URL.
 
 
497
        # this gets the normalised url back. I.e. '.' -> the full path.
 
 
498
        url = a_transport.base
 
 
501
                format = BzrDirFormat.find_format(a_transport)
 
 
502
                BzrDir._check_supported(format, False)
 
 
503
                return format.open(a_transport), urlutils.unescape(a_transport.relpath(url))
 
 
504
            except errors.NotBranchError, e:
 
 
505
                ## mutter('not a branch in: %r %s', a_transport.base, e)
 
 
507
            new_t = a_transport.clone('..')
 
 
508
            if new_t.base == a_transport.base:
 
 
509
                # reached the root, whatever that may be
 
 
510
                raise errors.NotBranchError(path=url)
 
 
513
    def open_repository(self, _unsupported=False):
 
 
514
        """Open the repository object at this BzrDir if one is present.
 
 
516
        This will not follow the Branch object pointer - its strictly a direct
 
 
517
        open facility. Most client code should use open_branch().repository to
 
 
520
        _unsupported is a private parameter, not part of the api.
 
 
521
        TODO: static convenience version of this?
 
 
523
        raise NotImplementedError(self.open_repository)
 
 
525
    def open_workingtree(self, _unsupported=False):
 
 
526
        """Open the workingtree object at this BzrDir if one is present.
 
 
528
        TODO: static convenience version of this?
 
 
530
        raise NotImplementedError(self.open_workingtree)
 
 
532
    def has_branch(self):
 
 
533
        """Tell if this bzrdir contains a branch.
 
 
535
        Note: if you're going to open the branch, you should just go ahead
 
 
536
        and try, and not ask permission first.  (This method just opens the 
 
 
537
        branch and discards it, and that's somewhat expensive.) 
 
 
542
        except errors.NotBranchError:
 
 
545
    def has_workingtree(self):
 
 
546
        """Tell if this bzrdir contains a working tree.
 
 
548
        This will still raise an exception if the bzrdir has a workingtree that
 
 
549
        is remote & inaccessible.
 
 
551
        Note: if you're going to open the working tree, you should just go ahead
 
 
552
        and try, and not ask permission first.  (This method just opens the 
 
 
553
        workingtree and discards it, and that's somewhat expensive.) 
 
 
556
            self.open_workingtree()
 
 
558
        except errors.NoWorkingTree:
 
 
561
    def sprout(self, url, revision_id=None, basis=None, force_new_repo=False):
 
 
562
        """Create a copy of this bzrdir prepared for use as a new line of
 
 
565
        If urls last component does not exist, it will be created.
 
 
567
        Attributes related to the identity of the source branch like
 
 
568
        branch nickname will be cleaned, a working tree is created
 
 
569
        whether one existed before or not; and a local branch is always
 
 
572
        if revision_id is not None, then the clone operation may tune
 
 
573
            itself to download less data.
 
 
576
        result = self._format.initialize(url)
 
 
577
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
 
 
579
            source_branch = self.open_branch()
 
 
580
            source_repository = source_branch.repository
 
 
581
        except errors.NotBranchError:
 
 
584
                source_repository = self.open_repository()
 
 
585
            except errors.NoRepositoryPresent:
 
 
586
                # copy the entire basis one if there is one
 
 
587
                # but there is no repository.
 
 
588
                source_repository = basis_repo
 
 
593
                result_repo = result.find_repository()
 
 
594
            except errors.NoRepositoryPresent:
 
 
596
        if source_repository is None and result_repo is not None:
 
 
598
        elif source_repository is None and result_repo is None:
 
 
599
            # no repo available, make a new one
 
 
600
            result.create_repository()
 
 
601
        elif source_repository is not None and result_repo is None:
 
 
602
            # have source, and want to make a new target repo
 
 
603
            # we dont clone the repo because that preserves attributes
 
 
604
            # like is_shared(), and we have not yet implemented a 
 
 
605
            # repository sprout().
 
 
606
            result_repo = result.create_repository()
 
 
607
        if result_repo is not None:
 
 
608
            # fetch needed content into target.
 
 
610
                # XXX FIXME RBC 20060214 need tests for this when the basis
 
 
612
                result_repo.fetch(basis_repo, revision_id=revision_id)
 
 
613
            result_repo.fetch(source_repository, revision_id=revision_id)
 
 
614
        if source_branch is not None:
 
 
615
            source_branch.sprout(result, revision_id=revision_id)
 
 
617
            result.create_branch()
 
 
618
        # TODO: jam 20060426 we probably need a test in here in the
 
 
619
        #       case that the newly sprouted branch is a remote one
 
 
620
        if result_repo is None or result_repo.make_working_trees():
 
 
621
            result.create_workingtree()
 
 
625
class BzrDirPreSplitOut(BzrDir):
 
 
626
    """A common class for the all-in-one formats."""
 
 
628
    def __init__(self, _transport, _format):
 
 
629
        """See BzrDir.__init__."""
 
 
630
        super(BzrDirPreSplitOut, self).__init__(_transport, _format)
 
 
631
        assert self._format._lock_class == TransportLock
 
 
632
        assert self._format._lock_file_name == 'branch-lock'
 
 
633
        self._control_files = LockableFiles(self.get_branch_transport(None),
 
 
634
                                            self._format._lock_file_name,
 
 
635
                                            self._format._lock_class)
 
 
637
    def break_lock(self):
 
 
638
        """Pre-splitout bzrdirs do not suffer from stale locks."""
 
 
639
        raise NotImplementedError(self.break_lock)
 
 
641
    def clone(self, url, revision_id=None, basis=None, force_new_repo=False):
 
 
642
        """See BzrDir.clone()."""
 
 
643
        from bzrlib.workingtree import WorkingTreeFormat2
 
 
645
        result = self._format._initialize_for_clone(url)
 
 
646
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
 
 
647
        self.open_repository().clone(result, revision_id=revision_id, basis=basis_repo)
 
 
648
        from_branch = self.open_branch()
 
 
649
        from_branch.clone(result, revision_id=revision_id)
 
 
651
            self.open_workingtree().clone(result, basis=basis_tree)
 
 
652
        except errors.NotLocalUrl:
 
 
653
            # make a new one, this format always has to have one.
 
 
655
                WorkingTreeFormat2().initialize(result)
 
 
656
            except errors.NotLocalUrl:
 
 
657
                # but we cannot do it for remote trees.
 
 
658
                to_branch = result.open_branch()
 
 
659
                WorkingTreeFormat2().stub_initialize_remote(to_branch.control_files)
 
 
662
    def create_branch(self):
 
 
663
        """See BzrDir.create_branch."""
 
 
664
        return self.open_branch()
 
 
666
    def create_repository(self, shared=False):
 
 
667
        """See BzrDir.create_repository."""
 
 
669
            raise errors.IncompatibleFormat('shared repository', self._format)
 
 
670
        return self.open_repository()
 
 
672
    def create_workingtree(self, revision_id=None):
 
 
673
        """See BzrDir.create_workingtree."""
 
 
674
        # this looks buggy but is not -really-
 
 
675
        # clone and sprout will have set the revision_id
 
 
676
        # and that will have set it for us, its only
 
 
677
        # specific uses of create_workingtree in isolation
 
 
678
        # that can do wonky stuff here, and that only
 
 
679
        # happens for creating checkouts, which cannot be 
 
 
680
        # done on this format anyway. So - acceptable wart.
 
 
681
        result = self.open_workingtree()
 
 
682
        if revision_id is not None:
 
 
683
            result.set_last_revision(revision_id)
 
 
686
    def get_branch_transport(self, branch_format):
 
 
687
        """See BzrDir.get_branch_transport()."""
 
 
688
        if branch_format is None:
 
 
689
            return self.transport
 
 
691
            branch_format.get_format_string()
 
 
692
        except NotImplementedError:
 
 
693
            return self.transport
 
 
694
        raise errors.IncompatibleFormat(branch_format, self._format)
 
 
696
    def get_repository_transport(self, repository_format):
 
 
697
        """See BzrDir.get_repository_transport()."""
 
 
698
        if repository_format is None:
 
 
699
            return self.transport
 
 
701
            repository_format.get_format_string()
 
 
702
        except NotImplementedError:
 
 
703
            return self.transport
 
 
704
        raise errors.IncompatibleFormat(repository_format, self._format)
 
 
706
    def get_workingtree_transport(self, workingtree_format):
 
 
707
        """See BzrDir.get_workingtree_transport()."""
 
 
708
        if workingtree_format is None:
 
 
709
            return self.transport
 
 
711
            workingtree_format.get_format_string()
 
 
712
        except NotImplementedError:
 
 
713
            return self.transport
 
 
714
        raise errors.IncompatibleFormat(workingtree_format, self._format)
 
 
716
    def needs_format_conversion(self, format=None):
 
 
717
        """See BzrDir.needs_format_conversion()."""
 
 
718
        # if the format is not the same as the system default,
 
 
719
        # an upgrade is needed.
 
 
721
            format = BzrDirFormat.get_default_format()
 
 
722
        return not isinstance(self._format, format.__class__)
 
 
724
    def open_branch(self, unsupported=False):
 
 
725
        """See BzrDir.open_branch."""
 
 
726
        from bzrlib.branch import BzrBranchFormat4
 
 
727
        format = BzrBranchFormat4()
 
 
728
        self._check_supported(format, unsupported)
 
 
729
        return format.open(self, _found=True)
 
 
731
    def sprout(self, url, revision_id=None, basis=None):
 
 
732
        """See BzrDir.sprout()."""
 
 
733
        from bzrlib.workingtree import WorkingTreeFormat2
 
 
735
        result = self._format._initialize_for_clone(url)
 
 
736
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
 
 
738
            self.open_repository().clone(result, revision_id=revision_id, basis=basis_repo)
 
 
739
        except errors.NoRepositoryPresent:
 
 
742
            self.open_branch().sprout(result, revision_id=revision_id)
 
 
743
        except errors.NotBranchError:
 
 
745
        # we always want a working tree
 
 
746
        WorkingTreeFormat2().initialize(result)
 
 
750
class BzrDir4(BzrDirPreSplitOut):
 
 
751
    """A .bzr version 4 control object.
 
 
753
    This is a deprecated format and may be removed after sept 2006.
 
 
756
    def create_repository(self, shared=False):
 
 
757
        """See BzrDir.create_repository."""
 
 
758
        return self._format.repository_format.initialize(self, shared)
 
 
760
    def needs_format_conversion(self, format=None):
 
 
761
        """Format 4 dirs are always in need of conversion."""
 
 
764
    def open_repository(self):
 
 
765
        """See BzrDir.open_repository."""
 
 
766
        from bzrlib.repository import RepositoryFormat4
 
 
767
        return RepositoryFormat4().open(self, _found=True)
 
 
770
class BzrDir5(BzrDirPreSplitOut):
 
 
771
    """A .bzr version 5 control object.
 
 
773
    This is a deprecated format and may be removed after sept 2006.
 
 
776
    def open_repository(self):
 
 
777
        """See BzrDir.open_repository."""
 
 
778
        from bzrlib.repository import RepositoryFormat5
 
 
779
        return RepositoryFormat5().open(self, _found=True)
 
 
781
    def open_workingtree(self, _unsupported=False):
 
 
782
        """See BzrDir.create_workingtree."""
 
 
783
        from bzrlib.workingtree import WorkingTreeFormat2
 
 
784
        return WorkingTreeFormat2().open(self, _found=True)
 
 
787
class BzrDir6(BzrDirPreSplitOut):
 
 
788
    """A .bzr version 6 control object.
 
 
790
    This is a deprecated format and may be removed after sept 2006.
 
 
793
    def open_repository(self):
 
 
794
        """See BzrDir.open_repository."""
 
 
795
        from bzrlib.repository import RepositoryFormat6
 
 
796
        return RepositoryFormat6().open(self, _found=True)
 
 
798
    def open_workingtree(self, _unsupported=False):
 
 
799
        """See BzrDir.create_workingtree."""
 
 
800
        from bzrlib.workingtree import WorkingTreeFormat2
 
 
801
        return WorkingTreeFormat2().open(self, _found=True)
 
 
804
class BzrDirMeta1(BzrDir):
 
 
805
    """A .bzr meta version 1 control object.
 
 
807
    This is the first control object where the 
 
 
808
    individual aspects are really split out: there are separate repository,
 
 
809
    workingtree and branch subdirectories and any subset of the three can be
 
 
810
    present within a BzrDir.
 
 
813
    def can_convert_format(self):
 
 
814
        """See BzrDir.can_convert_format()."""
 
 
817
    def create_branch(self):
 
 
818
        """See BzrDir.create_branch."""
 
 
819
        from bzrlib.branch import BranchFormat
 
 
820
        return BranchFormat.get_default_format().initialize(self)
 
 
822
    def create_repository(self, shared=False):
 
 
823
        """See BzrDir.create_repository."""
 
 
824
        return self._format.repository_format.initialize(self, shared)
 
 
826
    def create_workingtree(self, revision_id=None):
 
 
827
        """See BzrDir.create_workingtree."""
 
 
828
        from bzrlib.workingtree import WorkingTreeFormat
 
 
829
        return WorkingTreeFormat.get_default_format().initialize(self, revision_id)
 
 
831
    def _get_mkdir_mode(self):
 
 
832
        """Figure out the mode to use when creating a bzrdir subdir."""
 
 
833
        temp_control = LockableFiles(self.transport, '', TransportLock)
 
 
834
        return temp_control._dir_mode
 
 
836
    def get_branch_transport(self, branch_format):
 
 
837
        """See BzrDir.get_branch_transport()."""
 
 
838
        if branch_format is None:
 
 
839
            return self.transport.clone('branch')
 
 
841
            branch_format.get_format_string()
 
 
842
        except NotImplementedError:
 
 
843
            raise errors.IncompatibleFormat(branch_format, self._format)
 
 
845
            self.transport.mkdir('branch', mode=self._get_mkdir_mode())
 
 
846
        except errors.FileExists:
 
 
848
        return self.transport.clone('branch')
 
 
850
    def get_repository_transport(self, repository_format):
 
 
851
        """See BzrDir.get_repository_transport()."""
 
 
852
        if repository_format is None:
 
 
853
            return self.transport.clone('repository')
 
 
855
            repository_format.get_format_string()
 
 
856
        except NotImplementedError:
 
 
857
            raise errors.IncompatibleFormat(repository_format, self._format)
 
 
859
            self.transport.mkdir('repository', mode=self._get_mkdir_mode())
 
 
860
        except errors.FileExists:
 
 
862
        return self.transport.clone('repository')
 
 
864
    def get_workingtree_transport(self, workingtree_format):
 
 
865
        """See BzrDir.get_workingtree_transport()."""
 
 
866
        if workingtree_format is None:
 
 
867
            return self.transport.clone('checkout')
 
 
869
            workingtree_format.get_format_string()
 
 
870
        except NotImplementedError:
 
 
871
            raise errors.IncompatibleFormat(workingtree_format, self._format)
 
 
873
            self.transport.mkdir('checkout', mode=self._get_mkdir_mode())
 
 
874
        except errors.FileExists:
 
 
876
        return self.transport.clone('checkout')
 
 
878
    def needs_format_conversion(self, format=None):
 
 
879
        """See BzrDir.needs_format_conversion()."""
 
 
881
            format = BzrDirFormat.get_default_format()
 
 
882
        if not isinstance(self._format, format.__class__):
 
 
883
            # it is not a meta dir format, conversion is needed.
 
 
885
        # we might want to push this down to the repository?
 
 
887
            if not isinstance(self.open_repository()._format,
 
 
888
                              format.repository_format.__class__):
 
 
889
                # the repository needs an upgrade.
 
 
891
        except errors.NoRepositoryPresent:
 
 
893
        # currently there are no other possible conversions for meta1 formats.
 
 
896
    def open_branch(self, unsupported=False):
 
 
897
        """See BzrDir.open_branch."""
 
 
898
        from bzrlib.branch import BranchFormat
 
 
899
        format = BranchFormat.find_format(self)
 
 
900
        self._check_supported(format, unsupported)
 
 
901
        return format.open(self, _found=True)
 
 
903
    def open_repository(self, unsupported=False):
 
 
904
        """See BzrDir.open_repository."""
 
 
905
        from bzrlib.repository import RepositoryFormat
 
 
906
        format = RepositoryFormat.find_format(self)
 
 
907
        self._check_supported(format, unsupported)
 
 
908
        return format.open(self, _found=True)
 
 
910
    def open_workingtree(self, unsupported=False):
 
 
911
        """See BzrDir.open_workingtree."""
 
 
912
        from bzrlib.workingtree import WorkingTreeFormat
 
 
913
        format = WorkingTreeFormat.find_format(self)
 
 
914
        self._check_supported(format, unsupported)
 
 
915
        return format.open(self, _found=True)
 
 
918
class BzrDirFormat(object):
 
 
919
    """An encapsulation of the initialization and open routines for a format.
 
 
921
    Formats provide three things:
 
 
922
     * An initialization routine,
 
 
926
    Formats are placed in an dict by their format string for reference 
 
 
927
    during bzrdir opening. These should be subclasses of BzrDirFormat
 
 
930
    Once a format is deprecated, just deprecate the initialize and open
 
 
931
    methods on the format class. Do not deprecate the object, as the 
 
 
932
    object will be created every system load.
 
 
935
    _default_format = None
 
 
936
    """The default format used for new .bzr dirs."""
 
 
939
    """The known formats."""
 
 
941
    _lock_file_name = 'branch-lock'
 
 
943
    # _lock_class must be set in subclasses to the lock type, typ.
 
 
944
    # TransportLock or LockDir
 
 
947
    def find_format(klass, transport):
 
 
948
        """Return the format registered for URL."""
 
 
950
            format_string = transport.get(".bzr/branch-format").read()
 
 
951
            return klass._formats[format_string]
 
 
952
        except errors.NoSuchFile:
 
 
953
            raise errors.NotBranchError(path=transport.base)
 
 
955
            raise errors.UnknownFormatError(format_string)
 
 
958
    def get_default_format(klass):
 
 
959
        """Return the current default format."""
 
 
960
        return klass._default_format
 
 
962
    def get_format_string(self):
 
 
963
        """Return the ASCII format string that identifies this format."""
 
 
964
        raise NotImplementedError(self.get_format_string)
 
 
966
    def get_format_description(self):
 
 
967
        """Return the short description for this format."""
 
 
968
        raise NotImplementedError(self.get_format_description)
 
 
970
    def get_converter(self, format=None):
 
 
971
        """Return the converter to use to convert bzrdirs needing converts.
 
 
973
        This returns a bzrlib.bzrdir.Converter object.
 
 
975
        This should return the best upgrader to step this format towards the
 
 
976
        current default format. In the case of plugins we can/shouold provide
 
 
977
        some means for them to extend the range of returnable converters.
 
 
979
        :param format: Optional format to override the default foramt of the 
 
 
982
        raise NotImplementedError(self.get_converter)
 
 
984
    def initialize(self, url):
 
 
985
        """Create a bzr control dir at this url and return an opened copy.
 
 
987
        Subclasses should typically override initialize_on_transport
 
 
988
        instead of this method.
 
 
990
        return self.initialize_on_transport(get_transport(url))
 
 
992
    def initialize_on_transport(self, transport):
 
 
993
        """Initialize a new bzrdir in the base directory of a Transport."""
 
 
994
        # Since we don'transport have a .bzr directory, inherit the
 
 
995
        # mode from the root directory
 
 
996
        temp_control = LockableFiles(transport, '', TransportLock)
 
 
997
        temp_control._transport.mkdir('.bzr',
 
 
998
                                      # FIXME: RBC 20060121 dont peek under
 
 
1000
                                      mode=temp_control._dir_mode)
 
 
1001
        file_mode = temp_control._file_mode
 
 
1003
        mutter('created control directory in ' + transport.base)
 
 
1004
        control = transport.clone('.bzr')
 
 
1005
        utf8_files = [('README', 
 
 
1006
                       "This is a Bazaar-NG control directory.\n"
 
 
1007
                       "Do not change any files in this directory.\n"),
 
 
1008
                      ('branch-format', self.get_format_string()),
 
 
1010
        # NB: no need to escape relative paths that are url safe.
 
 
1011
        control_files = LockableFiles(control, self._lock_file_name, 
 
 
1013
        control_files.create_lock()
 
 
1014
        control_files.lock_write()
 
 
1016
            for file, content in utf8_files:
 
 
1017
                control_files.put_utf8(file, content)
 
 
1019
            control_files.unlock()
 
 
1020
        return self.open(transport, _found=True)
 
 
1022
    def is_supported(self):
 
 
1023
        """Is this format supported?
 
 
1025
        Supported formats must be initializable and openable.
 
 
1026
        Unsupported formats may not support initialization or committing or 
 
 
1027
        some other features depending on the reason for not being supported.
 
 
1031
    def open(self, transport, _found=False):
 
 
1032
        """Return an instance of this format for the dir transport points at.
 
 
1034
        _found is a private parameter, do not use it.
 
 
1037
            assert isinstance(BzrDirFormat.find_format(transport),
 
 
1039
        return self._open(transport)
 
 
1041
    def _open(self, transport):
 
 
1042
        """Template method helper for opening BzrDirectories.
 
 
1044
        This performs the actual open and any additional logic or parameter
 
 
1047
        raise NotImplementedError(self._open)
 
 
1050
    def register_format(klass, format):
 
 
1051
        klass._formats[format.get_format_string()] = format
 
 
1054
    def set_default_format(klass, format):
 
 
1055
        klass._default_format = format
 
 
1058
        return self.get_format_string()[:-1]
 
 
1061
    def unregister_format(klass, format):
 
 
1062
        assert klass._formats[format.get_format_string()] is format
 
 
1063
        del klass._formats[format.get_format_string()]
 
 
1066
class BzrDirFormat4(BzrDirFormat):
 
 
1067
    """Bzr dir format 4.
 
 
1069
    This format is a combined format for working tree, branch and repository.
 
 
1071
     - Format 1 working trees [always]
 
 
1072
     - Format 4 branches [always]
 
 
1073
     - Format 4 repositories [always]
 
 
1075
    This format is deprecated: it indexes texts using a text it which is
 
 
1076
    removed in format 5; write support for this format has been removed.
 
 
1079
    _lock_class = TransportLock
 
 
1081
    def get_format_string(self):
 
 
1082
        """See BzrDirFormat.get_format_string()."""
 
 
1083
        return "Bazaar-NG branch, format 0.0.4\n"
 
 
1085
    def get_format_description(self):
 
 
1086
        """See BzrDirFormat.get_format_description()."""
 
 
1087
        return "All-in-one format 4"
 
 
1089
    def get_converter(self, format=None):
 
 
1090
        """See BzrDirFormat.get_converter()."""
 
 
1091
        # there is one and only one upgrade path here.
 
 
1092
        return ConvertBzrDir4To5()
 
 
1094
    def initialize_on_transport(self, transport):
 
 
1095
        """Format 4 branches cannot be created."""
 
 
1096
        raise errors.UninitializableFormat(self)
 
 
1098
    def is_supported(self):
 
 
1099
        """Format 4 is not supported.
 
 
1101
        It is not supported because the model changed from 4 to 5 and the
 
 
1102
        conversion logic is expensive - so doing it on the fly was not 
 
 
1107
    def _open(self, transport):
 
 
1108
        """See BzrDirFormat._open."""
 
 
1109
        return BzrDir4(transport, self)
 
 
1111
    def __return_repository_format(self):
 
 
1112
        """Circular import protection."""
 
 
1113
        from bzrlib.repository import RepositoryFormat4
 
 
1114
        return RepositoryFormat4(self)
 
 
1115
    repository_format = property(__return_repository_format)
 
 
1118
class BzrDirFormat5(BzrDirFormat):
 
 
1119
    """Bzr control format 5.
 
 
1121
    This format is a combined format for working tree, branch and repository.
 
 
1123
     - Format 2 working trees [always] 
 
 
1124
     - Format 4 branches [always] 
 
 
1125
     - Format 5 repositories [always]
 
 
1126
       Unhashed stores in the repository.
 
 
1129
    _lock_class = TransportLock
 
 
1131
    def get_format_string(self):
 
 
1132
        """See BzrDirFormat.get_format_string()."""
 
 
1133
        return "Bazaar-NG branch, format 5\n"
 
 
1135
    def get_format_description(self):
 
 
1136
        """See BzrDirFormat.get_format_description()."""
 
 
1137
        return "All-in-one format 5"
 
 
1139
    def get_converter(self, format=None):
 
 
1140
        """See BzrDirFormat.get_converter()."""
 
 
1141
        # there is one and only one upgrade path here.
 
 
1142
        return ConvertBzrDir5To6()
 
 
1144
    def _initialize_for_clone(self, url):
 
 
1145
        return self.initialize_on_transport(get_transport(url), _cloning=True)
 
 
1147
    def initialize_on_transport(self, transport, _cloning=False):
 
 
1148
        """Format 5 dirs always have working tree, branch and repository.
 
 
1150
        Except when they are being cloned.
 
 
1152
        from bzrlib.branch import BzrBranchFormat4
 
 
1153
        from bzrlib.repository import RepositoryFormat5
 
 
1154
        from bzrlib.workingtree import WorkingTreeFormat2
 
 
1155
        result = (super(BzrDirFormat5, self).initialize_on_transport(transport))
 
 
1156
        RepositoryFormat5().initialize(result, _internal=True)
 
 
1158
            BzrBranchFormat4().initialize(result)
 
 
1159
            WorkingTreeFormat2().initialize(result)
 
 
1162
    def _open(self, transport):
 
 
1163
        """See BzrDirFormat._open."""
 
 
1164
        return BzrDir5(transport, self)
 
 
1166
    def __return_repository_format(self):
 
 
1167
        """Circular import protection."""
 
 
1168
        from bzrlib.repository import RepositoryFormat5
 
 
1169
        return RepositoryFormat5(self)
 
 
1170
    repository_format = property(__return_repository_format)
 
 
1173
class BzrDirFormat6(BzrDirFormat):
 
 
1174
    """Bzr control format 6.
 
 
1176
    This format is a combined format for working tree, branch and repository.
 
 
1178
     - Format 2 working trees [always] 
 
 
1179
     - Format 4 branches [always] 
 
 
1180
     - Format 6 repositories [always]
 
 
1183
    _lock_class = TransportLock
 
 
1185
    def get_format_string(self):
 
 
1186
        """See BzrDirFormat.get_format_string()."""
 
 
1187
        return "Bazaar-NG branch, format 6\n"
 
 
1189
    def get_format_description(self):
 
 
1190
        """See BzrDirFormat.get_format_description()."""
 
 
1191
        return "All-in-one format 6"
 
 
1193
    def get_converter(self, format=None):
 
 
1194
        """See BzrDirFormat.get_converter()."""
 
 
1195
        # there is one and only one upgrade path here.
 
 
1196
        return ConvertBzrDir6ToMeta()
 
 
1198
    def _initialize_for_clone(self, url):
 
 
1199
        return self.initialize_on_transport(get_transport(url), _cloning=True)
 
 
1201
    def initialize_on_transport(self, transport, _cloning=False):
 
 
1202
        """Format 6 dirs always have working tree, branch and repository.
 
 
1204
        Except when they are being cloned.
 
 
1206
        from bzrlib.branch import BzrBranchFormat4
 
 
1207
        from bzrlib.repository import RepositoryFormat6
 
 
1208
        from bzrlib.workingtree import WorkingTreeFormat2
 
 
1209
        result = super(BzrDirFormat6, self).initialize_on_transport(transport)
 
 
1210
        RepositoryFormat6().initialize(result, _internal=True)
 
 
1212
            BzrBranchFormat4().initialize(result)
 
 
1214
                WorkingTreeFormat2().initialize(result)
 
 
1215
            except errors.NotLocalUrl:
 
 
1216
                # emulate pre-check behaviour for working tree and silently 
 
 
1221
    def _open(self, transport):
 
 
1222
        """See BzrDirFormat._open."""
 
 
1223
        return BzrDir6(transport, self)
 
 
1225
    def __return_repository_format(self):
 
 
1226
        """Circular import protection."""
 
 
1227
        from bzrlib.repository import RepositoryFormat6
 
 
1228
        return RepositoryFormat6(self)
 
 
1229
    repository_format = property(__return_repository_format)
 
 
1232
class BzrDirMetaFormat1(BzrDirFormat):
 
 
1233
    """Bzr meta control format 1
 
 
1235
    This is the first format with split out working tree, branch and repository
 
 
1238
     - Format 3 working trees [optional]
 
 
1239
     - Format 5 branches [optional]
 
 
1240
     - Format 7 repositories [optional]
 
 
1243
    _lock_class = LockDir
 
 
1245
    def get_converter(self, format=None):
 
 
1246
        """See BzrDirFormat.get_converter()."""
 
 
1248
            format = BzrDirFormat.get_default_format()
 
 
1249
        if not isinstance(self, format.__class__):
 
 
1250
            # converting away from metadir is not implemented
 
 
1251
            raise NotImplementedError(self.get_converter)
 
 
1252
        return ConvertMetaToMeta(format)
 
 
1254
    def get_format_string(self):
 
 
1255
        """See BzrDirFormat.get_format_string()."""
 
 
1256
        return "Bazaar-NG meta directory, format 1\n"
 
 
1258
    def get_format_description(self):
 
 
1259
        """See BzrDirFormat.get_format_description()."""
 
 
1260
        return "Meta directory format 1"
 
 
1262
    def _open(self, transport):
 
 
1263
        """See BzrDirFormat._open."""
 
 
1264
        return BzrDirMeta1(transport, self)
 
 
1266
    def __return_repository_format(self):
 
 
1267
        """Circular import protection."""
 
 
1268
        if getattr(self, '_repository_format', None):
 
 
1269
            return self._repository_format
 
 
1270
        from bzrlib.repository import RepositoryFormat
 
 
1271
        return RepositoryFormat.get_default_format()
 
 
1273
    def __set_repository_format(self, value):
 
 
1274
        """Allow changint the repository format for metadir formats."""
 
 
1275
        self._repository_format = value
 
 
1277
    repository_format = property(__return_repository_format, __set_repository_format)
 
 
1280
BzrDirFormat.register_format(BzrDirFormat4())
 
 
1281
BzrDirFormat.register_format(BzrDirFormat5())
 
 
1282
BzrDirFormat.register_format(BzrDirFormat6())
 
 
1283
__default_format = BzrDirMetaFormat1()
 
 
1284
BzrDirFormat.register_format(__default_format)
 
 
1285
BzrDirFormat.set_default_format(__default_format)
 
 
1288
class BzrDirTestProviderAdapter(object):
 
 
1289
    """A tool to generate a suite testing multiple bzrdir formats at once.
 
 
1291
    This is done by copying the test once for each transport and injecting
 
 
1292
    the transport_server, transport_readonly_server, and bzrdir_format
 
 
1293
    classes into each copy. Each copy is also given a new id() to make it
 
 
1297
    def __init__(self, transport_server, transport_readonly_server, formats):
 
 
1298
        self._transport_server = transport_server
 
 
1299
        self._transport_readonly_server = transport_readonly_server
 
 
1300
        self._formats = formats
 
 
1302
    def adapt(self, test):
 
 
1303
        result = TestSuite()
 
 
1304
        for format in self._formats:
 
 
1305
            new_test = deepcopy(test)
 
 
1306
            new_test.transport_server = self._transport_server
 
 
1307
            new_test.transport_readonly_server = self._transport_readonly_server
 
 
1308
            new_test.bzrdir_format = format
 
 
1309
            def make_new_test_id():
 
 
1310
                new_id = "%s(%s)" % (new_test.id(), format.__class__.__name__)
 
 
1311
                return lambda: new_id
 
 
1312
            new_test.id = make_new_test_id()
 
 
1313
            result.addTest(new_test)
 
 
1317
class ScratchDir(BzrDir6):
 
 
1318
    """Special test class: a bzrdir that cleans up itself..
 
 
1320
    >>> d = ScratchDir()
 
 
1321
    >>> base = d.transport.base
 
 
1324
    >>> b.transport.__del__()
 
 
1329
    def __init__(self, files=[], dirs=[], transport=None):
 
 
1330
        """Make a test branch.
 
 
1332
        This creates a temporary directory and runs init-tree in it.
 
 
1334
        If any files are listed, they are created in the working copy.
 
 
1336
        if transport is None:
 
 
1337
            transport = bzrlib.transport.local.ScratchTransport()
 
 
1338
            # local import for scope restriction
 
 
1339
            BzrDirFormat6().initialize(transport.base)
 
 
1340
            super(ScratchDir, self).__init__(transport, BzrDirFormat6())
 
 
1341
            self.create_repository()
 
 
1342
            self.create_branch()
 
 
1343
            self.create_workingtree()
 
 
1345
            super(ScratchDir, self).__init__(transport, BzrDirFormat6())
 
 
1347
        # BzrBranch creates a clone to .bzr and then forgets about the
 
 
1348
        # original transport. A ScratchTransport() deletes itself and
 
 
1349
        # everything underneath it when it goes away, so we need to
 
 
1350
        # grab a local copy to prevent that from happening
 
 
1351
        self._transport = transport
 
 
1354
            self._transport.mkdir(d)
 
 
1357
            self._transport.put(f, 'content of %s' % f)
 
 
1361
        >>> orig = ScratchDir(files=["file1", "file2"])
 
 
1362
        >>> os.listdir(orig.base)
 
 
1363
        [u'.bzr', u'file1', u'file2']
 
 
1364
        >>> clone = orig.clone()
 
 
1365
        >>> if os.name != 'nt':
 
 
1366
        ...   os.path.samefile(orig.base, clone.base)
 
 
1368
        ...   orig.base == clone.base
 
 
1371
        >>> os.listdir(clone.base)
 
 
1372
        [u'.bzr', u'file1', u'file2']
 
 
1374
        from shutil import copytree
 
 
1375
        from bzrlib.osutils import mkdtemp
 
 
1378
        copytree(self.base, base, symlinks=True)
 
 
1380
            transport=bzrlib.transport.local.ScratchTransport(base))
 
 
1383
class Converter(object):
 
 
1384
    """Converts a disk format object from one format to another."""
 
 
1386
    def convert(self, to_convert, pb):
 
 
1387
        """Perform the conversion of to_convert, giving feedback via pb.
 
 
1389
        :param to_convert: The disk object to convert.
 
 
1390
        :param pb: a progress bar to use for progress information.
 
 
1393
    def step(self, message):
 
 
1394
        """Update the pb by a step."""
 
 
1396
        self.pb.update(message, self.count, self.total)
 
 
1399
class ConvertBzrDir4To5(Converter):
 
 
1400
    """Converts format 4 bzr dirs to format 5."""
 
 
1403
        super(ConvertBzrDir4To5, self).__init__()
 
 
1404
        self.converted_revs = set()
 
 
1405
        self.absent_revisions = set()
 
 
1409
    def convert(self, to_convert, pb):
 
 
1410
        """See Converter.convert()."""
 
 
1411
        self.bzrdir = to_convert
 
 
1413
        self.pb.note('starting upgrade from format 4 to 5')
 
 
1414
        if isinstance(self.bzrdir.transport, LocalTransport):
 
 
1415
            self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
 
 
1416
        self._convert_to_weaves()
 
 
1417
        return BzrDir.open(self.bzrdir.root_transport.base)
 
 
1419
    def _convert_to_weaves(self):
 
 
1420
        self.pb.note('note: upgrade may be faster if all store files are ungzipped first')
 
 
1423
            stat = self.bzrdir.transport.stat('weaves')
 
 
1424
            if not S_ISDIR(stat.st_mode):
 
 
1425
                self.bzrdir.transport.delete('weaves')
 
 
1426
                self.bzrdir.transport.mkdir('weaves')
 
 
1427
        except errors.NoSuchFile:
 
 
1428
            self.bzrdir.transport.mkdir('weaves')
 
 
1429
        # deliberately not a WeaveFile as we want to build it up slowly.
 
 
1430
        self.inv_weave = Weave('inventory')
 
 
1431
        # holds in-memory weaves for all files
 
 
1432
        self.text_weaves = {}
 
 
1433
        self.bzrdir.transport.delete('branch-format')
 
 
1434
        self.branch = self.bzrdir.open_branch()
 
 
1435
        self._convert_working_inv()
 
 
1436
        rev_history = self.branch.revision_history()
 
 
1437
        # to_read is a stack holding the revisions we still need to process;
 
 
1438
        # appending to it adds new highest-priority revisions
 
 
1439
        self.known_revisions = set(rev_history)
 
 
1440
        self.to_read = rev_history[-1:]
 
 
1442
            rev_id = self.to_read.pop()
 
 
1443
            if (rev_id not in self.revisions
 
 
1444
                and rev_id not in self.absent_revisions):
 
 
1445
                self._load_one_rev(rev_id)
 
 
1447
        to_import = self._make_order()
 
 
1448
        for i, rev_id in enumerate(to_import):
 
 
1449
            self.pb.update('converting revision', i, len(to_import))
 
 
1450
            self._convert_one_rev(rev_id)
 
 
1452
        self._write_all_weaves()
 
 
1453
        self._write_all_revs()
 
 
1454
        self.pb.note('upgraded to weaves:')
 
 
1455
        self.pb.note('  %6d revisions and inventories', len(self.revisions))
 
 
1456
        self.pb.note('  %6d revisions not present', len(self.absent_revisions))
 
 
1457
        self.pb.note('  %6d texts', self.text_count)
 
 
1458
        self._cleanup_spare_files_after_format4()
 
 
1459
        self.branch.control_files.put_utf8('branch-format', BzrDirFormat5().get_format_string())
 
 
1461
    def _cleanup_spare_files_after_format4(self):
 
 
1462
        # FIXME working tree upgrade foo.
 
 
1463
        for n in 'merged-patches', 'pending-merged-patches':
 
 
1465
                ## assert os.path.getsize(p) == 0
 
 
1466
                self.bzrdir.transport.delete(n)
 
 
1467
            except errors.NoSuchFile:
 
 
1469
        self.bzrdir.transport.delete_tree('inventory-store')
 
 
1470
        self.bzrdir.transport.delete_tree('text-store')
 
 
1472
    def _convert_working_inv(self):
 
 
1473
        inv = serializer_v4.read_inventory(self.branch.control_files.get('inventory'))
 
 
1474
        new_inv_xml = bzrlib.xml5.serializer_v5.write_inventory_to_string(inv)
 
 
1475
        # FIXME inventory is a working tree change.
 
 
1476
        self.branch.control_files.put('inventory', new_inv_xml)
 
 
1478
    def _write_all_weaves(self):
 
 
1479
        controlweaves = WeaveStore(self.bzrdir.transport, prefixed=False)
 
 
1480
        weave_transport = self.bzrdir.transport.clone('weaves')
 
 
1481
        weaves = WeaveStore(weave_transport, prefixed=False)
 
 
1482
        transaction = WriteTransaction()
 
 
1486
            for file_id, file_weave in self.text_weaves.items():
 
 
1487
                self.pb.update('writing weave', i, len(self.text_weaves))
 
 
1488
                weaves._put_weave(file_id, file_weave, transaction)
 
 
1490
            self.pb.update('inventory', 0, 1)
 
 
1491
            controlweaves._put_weave('inventory', self.inv_weave, transaction)
 
 
1492
            self.pb.update('inventory', 1, 1)
 
 
1496
    def _write_all_revs(self):
 
 
1497
        """Write all revisions out in new form."""
 
 
1498
        self.bzrdir.transport.delete_tree('revision-store')
 
 
1499
        self.bzrdir.transport.mkdir('revision-store')
 
 
1500
        revision_transport = self.bzrdir.transport.clone('revision-store')
 
 
1502
        _revision_store = TextRevisionStore(TextStore(revision_transport,
 
 
1506
            transaction = bzrlib.transactions.WriteTransaction()
 
 
1507
            for i, rev_id in enumerate(self.converted_revs):
 
 
1508
                self.pb.update('write revision', i, len(self.converted_revs))
 
 
1509
                _revision_store.add_revision(self.revisions[rev_id], transaction)
 
 
1513
    def _load_one_rev(self, rev_id):
 
 
1514
        """Load a revision object into memory.
 
 
1516
        Any parents not either loaded or abandoned get queued to be
 
 
1518
        self.pb.update('loading revision',
 
 
1519
                       len(self.revisions),
 
 
1520
                       len(self.known_revisions))
 
 
1521
        if not self.branch.repository.has_revision(rev_id):
 
 
1523
            self.pb.note('revision {%s} not present in branch; '
 
 
1524
                         'will be converted as a ghost',
 
 
1526
            self.absent_revisions.add(rev_id)
 
 
1528
            rev = self.branch.repository._revision_store.get_revision(rev_id,
 
 
1529
                self.branch.repository.get_transaction())
 
 
1530
            for parent_id in rev.parent_ids:
 
 
1531
                self.known_revisions.add(parent_id)
 
 
1532
                self.to_read.append(parent_id)
 
 
1533
            self.revisions[rev_id] = rev
 
 
1535
    def _load_old_inventory(self, rev_id):
 
 
1536
        assert rev_id not in self.converted_revs
 
 
1537
        old_inv_xml = self.branch.repository.inventory_store.get(rev_id).read()
 
 
1538
        inv = serializer_v4.read_inventory_from_string(old_inv_xml)
 
 
1539
        rev = self.revisions[rev_id]
 
 
1540
        if rev.inventory_sha1:
 
 
1541
            assert rev.inventory_sha1 == sha_string(old_inv_xml), \
 
 
1542
                'inventory sha mismatch for {%s}' % rev_id
 
 
1545
    def _load_updated_inventory(self, rev_id):
 
 
1546
        assert rev_id in self.converted_revs
 
 
1547
        inv_xml = self.inv_weave.get_text(rev_id)
 
 
1548
        inv = bzrlib.xml5.serializer_v5.read_inventory_from_string(inv_xml)
 
 
1551
    def _convert_one_rev(self, rev_id):
 
 
1552
        """Convert revision and all referenced objects to new format."""
 
 
1553
        rev = self.revisions[rev_id]
 
 
1554
        inv = self._load_old_inventory(rev_id)
 
 
1555
        present_parents = [p for p in rev.parent_ids
 
 
1556
                           if p not in self.absent_revisions]
 
 
1557
        self._convert_revision_contents(rev, inv, present_parents)
 
 
1558
        self._store_new_weave(rev, inv, present_parents)
 
 
1559
        self.converted_revs.add(rev_id)
 
 
1561
    def _store_new_weave(self, rev, inv, present_parents):
 
 
1562
        # the XML is now updated with text versions
 
 
1566
                if ie.kind == 'root_directory':
 
 
1568
                assert hasattr(ie, 'revision'), \
 
 
1569
                    'no revision on {%s} in {%s}' % \
 
 
1570
                    (file_id, rev.revision_id)
 
 
1571
        new_inv_xml = bzrlib.xml5.serializer_v5.write_inventory_to_string(inv)
 
 
1572
        new_inv_sha1 = sha_string(new_inv_xml)
 
 
1573
        self.inv_weave.add_lines(rev.revision_id, 
 
 
1575
                                 new_inv_xml.splitlines(True))
 
 
1576
        rev.inventory_sha1 = new_inv_sha1
 
 
1578
    def _convert_revision_contents(self, rev, inv, present_parents):
 
 
1579
        """Convert all the files within a revision.
 
 
1581
        Also upgrade the inventory to refer to the text revision ids."""
 
 
1582
        rev_id = rev.revision_id
 
 
1583
        mutter('converting texts of revision {%s}',
 
 
1585
        parent_invs = map(self._load_updated_inventory, present_parents)
 
 
1588
            self._convert_file_version(rev, ie, parent_invs)
 
 
1590
    def _convert_file_version(self, rev, ie, parent_invs):
 
 
1591
        """Convert one version of one file.
 
 
1593
        The file needs to be added into the weave if it is a merge
 
 
1594
        of >=2 parents or if it's changed from its parent.
 
 
1596
        if ie.kind == 'root_directory':
 
 
1598
        file_id = ie.file_id
 
 
1599
        rev_id = rev.revision_id
 
 
1600
        w = self.text_weaves.get(file_id)
 
 
1603
            self.text_weaves[file_id] = w
 
 
1604
        text_changed = False
 
 
1605
        previous_entries = ie.find_previous_heads(parent_invs,
 
 
1609
        for old_revision in previous_entries:
 
 
1610
                # if this fails, its a ghost ?
 
 
1611
                assert old_revision in self.converted_revs 
 
 
1612
        self.snapshot_ie(previous_entries, ie, w, rev_id)
 
 
1614
        assert getattr(ie, 'revision', None) is not None
 
 
1616
    def snapshot_ie(self, previous_revisions, ie, w, rev_id):
 
 
1617
        # TODO: convert this logic, which is ~= snapshot to
 
 
1618
        # a call to:. This needs the path figured out. rather than a work_tree
 
 
1619
        # a v4 revision_tree can be given, or something that looks enough like
 
 
1620
        # one to give the file content to the entry if it needs it.
 
 
1621
        # and we need something that looks like a weave store for snapshot to 
 
 
1623
        #ie.snapshot(rev, PATH, previous_revisions, REVISION_TREE, InMemoryWeaveStore(self.text_weaves))
 
 
1624
        if len(previous_revisions) == 1:
 
 
1625
            previous_ie = previous_revisions.values()[0]
 
 
1626
            if ie._unchanged(previous_ie):
 
 
1627
                ie.revision = previous_ie.revision
 
 
1630
            text = self.branch.repository.text_store.get(ie.text_id)
 
 
1631
            file_lines = text.readlines()
 
 
1632
            assert sha_strings(file_lines) == ie.text_sha1
 
 
1633
            assert sum(map(len, file_lines)) == ie.text_size
 
 
1634
            w.add_lines(rev_id, previous_revisions, file_lines)
 
 
1635
            self.text_count += 1
 
 
1637
            w.add_lines(rev_id, previous_revisions, [])
 
 
1638
        ie.revision = rev_id
 
 
1640
    def _make_order(self):
 
 
1641
        """Return a suitable order for importing revisions.
 
 
1643
        The order must be such that an revision is imported after all
 
 
1644
        its (present) parents.
 
 
1646
        todo = set(self.revisions.keys())
 
 
1647
        done = self.absent_revisions.copy()
 
 
1650
            # scan through looking for a revision whose parents
 
 
1652
            for rev_id in sorted(list(todo)):
 
 
1653
                rev = self.revisions[rev_id]
 
 
1654
                parent_ids = set(rev.parent_ids)
 
 
1655
                if parent_ids.issubset(done):
 
 
1656
                    # can take this one now
 
 
1657
                    order.append(rev_id)
 
 
1663
class ConvertBzrDir5To6(Converter):
 
 
1664
    """Converts format 5 bzr dirs to format 6."""
 
 
1666
    def convert(self, to_convert, pb):
 
 
1667
        """See Converter.convert()."""
 
 
1668
        self.bzrdir = to_convert
 
 
1670
        self.pb.note('starting upgrade from format 5 to 6')
 
 
1671
        self._convert_to_prefixed()
 
 
1672
        return BzrDir.open(self.bzrdir.root_transport.base)
 
 
1674
    def _convert_to_prefixed(self):
 
 
1675
        from bzrlib.store import TransportStore
 
 
1676
        self.bzrdir.transport.delete('branch-format')
 
 
1677
        for store_name in ["weaves", "revision-store"]:
 
 
1678
            self.pb.note("adding prefixes to %s" % store_name)
 
 
1679
            store_transport = self.bzrdir.transport.clone(store_name)
 
 
1680
            store = TransportStore(store_transport, prefixed=True)
 
 
1681
            for urlfilename in store_transport.list_dir('.'):
 
 
1682
                filename = urlutils.unescape(urlfilename)
 
 
1683
                if (filename.endswith(".weave") or
 
 
1684
                    filename.endswith(".gz") or
 
 
1685
                    filename.endswith(".sig")):
 
 
1686
                    file_id = os.path.splitext(filename)[0]
 
 
1689
                prefix_dir = store.hash_prefix(file_id)
 
 
1690
                # FIXME keep track of the dirs made RBC 20060121
 
 
1692
                    store_transport.move(filename, prefix_dir + '/' + filename)
 
 
1693
                except errors.NoSuchFile: # catches missing dirs strangely enough
 
 
1694
                    store_transport.mkdir(prefix_dir)
 
 
1695
                    store_transport.move(filename, prefix_dir + '/' + filename)
 
 
1696
        self.bzrdir._control_files.put_utf8('branch-format', BzrDirFormat6().get_format_string())
 
 
1699
class ConvertBzrDir6ToMeta(Converter):
 
 
1700
    """Converts format 6 bzr dirs to metadirs."""
 
 
1702
    def convert(self, to_convert, pb):
 
 
1703
        """See Converter.convert()."""
 
 
1704
        self.bzrdir = to_convert
 
 
1707
        self.total = 20 # the steps we know about
 
 
1708
        self.garbage_inventories = []
 
 
1710
        self.pb.note('starting upgrade from format 6 to metadir')
 
 
1711
        self.bzrdir._control_files.put_utf8('branch-format', "Converting to format 6")
 
 
1712
        # its faster to move specific files around than to open and use the apis...
 
 
1713
        # first off, nuke ancestry.weave, it was never used.
 
 
1715
            self.step('Removing ancestry.weave')
 
 
1716
            self.bzrdir.transport.delete('ancestry.weave')
 
 
1717
        except errors.NoSuchFile:
 
 
1719
        # find out whats there
 
 
1720
        self.step('Finding branch files')
 
 
1721
        last_revision = self.bzrdir.open_branch().last_revision()
 
 
1722
        bzrcontents = self.bzrdir.transport.list_dir('.')
 
 
1723
        for name in bzrcontents:
 
 
1724
            if name.startswith('basis-inventory.'):
 
 
1725
                self.garbage_inventories.append(name)
 
 
1726
        # create new directories for repository, working tree and branch
 
 
1727
        self.dir_mode = self.bzrdir._control_files._dir_mode
 
 
1728
        self.file_mode = self.bzrdir._control_files._file_mode
 
 
1729
        repository_names = [('inventory.weave', True),
 
 
1730
                            ('revision-store', True),
 
 
1732
        self.step('Upgrading repository  ')
 
 
1733
        self.bzrdir.transport.mkdir('repository', mode=self.dir_mode)
 
 
1734
        self.make_lock('repository')
 
 
1735
        # we hard code the formats here because we are converting into
 
 
1736
        # the meta format. The meta format upgrader can take this to a 
 
 
1737
        # future format within each component.
 
 
1738
        self.put_format('repository', bzrlib.repository.RepositoryFormat7())
 
 
1739
        for entry in repository_names:
 
 
1740
            self.move_entry('repository', entry)
 
 
1742
        self.step('Upgrading branch      ')
 
 
1743
        self.bzrdir.transport.mkdir('branch', mode=self.dir_mode)
 
 
1744
        self.make_lock('branch')
 
 
1745
        self.put_format('branch', bzrlib.branch.BzrBranchFormat5())
 
 
1746
        branch_files = [('revision-history', True),
 
 
1747
                        ('branch-name', True),
 
 
1749
        for entry in branch_files:
 
 
1750
            self.move_entry('branch', entry)
 
 
1752
        self.step('Upgrading working tree')
 
 
1753
        self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
 
 
1754
        self.make_lock('checkout')
 
 
1755
        self.put_format('checkout', bzrlib.workingtree.WorkingTreeFormat3())
 
 
1756
        self.bzrdir.transport.delete_multi(self.garbage_inventories, self.pb)
 
 
1757
        checkout_files = [('pending-merges', True),
 
 
1758
                          ('inventory', True),
 
 
1759
                          ('stat-cache', False)]
 
 
1760
        for entry in checkout_files:
 
 
1761
            self.move_entry('checkout', entry)
 
 
1762
        if last_revision is not None:
 
 
1763
            self.bzrdir._control_files.put_utf8('checkout/last-revision',
 
 
1765
        self.bzrdir._control_files.put_utf8('branch-format', BzrDirMetaFormat1().get_format_string())
 
 
1766
        return BzrDir.open(self.bzrdir.root_transport.base)
 
 
1768
    def make_lock(self, name):
 
 
1769
        """Make a lock for the new control dir name."""
 
 
1770
        self.step('Make %s lock' % name)
 
 
1771
        ld = LockDir(self.bzrdir.transport, 
 
 
1773
                     file_modebits=self.file_mode,
 
 
1774
                     dir_modebits=self.dir_mode)
 
 
1777
    def move_entry(self, new_dir, entry):
 
 
1778
        """Move then entry name into new_dir."""
 
 
1780
        mandatory = entry[1]
 
 
1781
        self.step('Moving %s' % name)
 
 
1783
            self.bzrdir.transport.move(name, '%s/%s' % (new_dir, name))
 
 
1784
        except errors.NoSuchFile:
 
 
1788
    def put_format(self, dirname, format):
 
 
1789
        self.bzrdir._control_files.put_utf8('%s/format' % dirname, format.get_format_string())
 
 
1792
class ConvertMetaToMeta(Converter):
 
 
1793
    """Converts the components of metadirs."""
 
 
1795
    def __init__(self, target_format):
 
 
1796
        """Create a metadir to metadir converter.
 
 
1798
        :param target_format: The final metadir format that is desired.
 
 
1800
        self.target_format = target_format
 
 
1802
    def convert(self, to_convert, pb):
 
 
1803
        """See Converter.convert()."""
 
 
1804
        self.bzrdir = to_convert
 
 
1808
        self.step('checking repository format')
 
 
1810
            repo = self.bzrdir.open_repository()
 
 
1811
        except errors.NoRepositoryPresent:
 
 
1814
            if not isinstance(repo._format, self.target_format.repository_format.__class__):
 
 
1815
                from bzrlib.repository import CopyConverter
 
 
1816
                self.pb.note('starting repository conversion')
 
 
1817
                converter = CopyConverter(self.target_format.repository_format)
 
 
1818
                converter.convert(repo, pb)