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
# TODO: remove unittest dependency; put that stuff inside the test suite
 
 
25
# TODO: Can we move specific formats into separate modules to make this file
 
 
28
from cStringIO import StringIO
 
 
32
from bzrlib.lazy_import import lazy_import
 
 
33
lazy_import(globals(), """
 
 
34
from copy import deepcopy
 
 
35
from stat import S_ISDIR
 
 
45
    revision as _mod_revision,
 
 
46
    repository as _mod_repository,
 
 
52
from bzrlib.osutils import (
 
 
57
from bzrlib.smart.client import SmartClient
 
 
58
from bzrlib.store.revision.text import TextRevisionStore
 
 
59
from bzrlib.store.text import TextStore
 
 
60
from bzrlib.store.versioned import WeaveStore
 
 
61
from bzrlib.transactions import WriteTransaction
 
 
62
from bzrlib.transport import get_transport
 
 
63
from bzrlib.weave import Weave
 
 
66
from bzrlib.trace import mutter
 
 
67
from bzrlib.transport.local import LocalTransport
 
 
71
    """A .bzr control diretory.
 
 
73
    BzrDir instances let you create or open any of the things that can be
 
 
74
    found within .bzr - checkouts, branches and repositories.
 
 
77
        the transport which this bzr dir is rooted at (i.e. file:///.../.bzr/)
 
 
79
        a transport connected to the directory this bzr was opened from.
 
 
83
        """Invoke break_lock on the first object in the bzrdir.
 
 
85
        If there is a tree, the tree is opened and break_lock() called.
 
 
86
        Otherwise, branch is tried, and finally repository.
 
 
88
        # XXX: This seems more like a UI function than something that really
 
 
89
        # belongs in this class.
 
 
91
            thing_to_unlock = self.open_workingtree()
 
 
92
        except (errors.NotLocalUrl, errors.NoWorkingTree):
 
 
94
                thing_to_unlock = self.open_branch()
 
 
95
            except errors.NotBranchError:
 
 
97
                    thing_to_unlock = self.open_repository()
 
 
98
                except errors.NoRepositoryPresent:
 
 
100
        thing_to_unlock.break_lock()
 
 
102
    def can_convert_format(self):
 
 
103
        """Return true if this bzrdir is one whose format we can convert from."""
 
 
106
    def check_conversion_target(self, target_format):
 
 
107
        target_repo_format = target_format.repository_format
 
 
108
        source_repo_format = self._format.repository_format
 
 
109
        source_repo_format.check_conversion_target(target_repo_format)
 
 
112
    def _check_supported(format, allow_unsupported):
 
 
113
        """Check whether format is a supported format.
 
 
115
        If allow_unsupported is True, this is a no-op.
 
 
117
        if not allow_unsupported and not format.is_supported():
 
 
118
            # see open_downlevel to open legacy branches.
 
 
119
            raise errors.UnsupportedFormatError(format=format)
 
 
121
    def clone(self, url, revision_id=None, basis=None, force_new_repo=False):
 
 
122
        """Clone this bzrdir and its contents to url verbatim.
 
 
124
        If urls last component does not exist, it will be created.
 
 
126
        if revision_id is not None, then the clone operation may tune
 
 
127
            itself to download less data.
 
 
128
        :param force_new_repo: Do not use a shared repository for the target 
 
 
129
                               even if one is available.
 
 
132
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
 
 
133
        result = self._format.initialize(url)
 
 
135
            local_repo = self.find_repository()
 
 
136
        except errors.NoRepositoryPresent:
 
 
139
            # may need to copy content in
 
 
141
                result_repo = local_repo.clone(
 
 
143
                    revision_id=revision_id,
 
 
145
                result_repo.set_make_working_trees(local_repo.make_working_trees())
 
 
148
                    result_repo = result.find_repository()
 
 
149
                    # fetch content this dir needs.
 
 
151
                        # XXX FIXME RBC 20060214 need tests for this when the basis
 
 
153
                        result_repo.fetch(basis_repo, revision_id=revision_id)
 
 
154
                    result_repo.fetch(local_repo, revision_id=revision_id)
 
 
155
                except errors.NoRepositoryPresent:
 
 
156
                    # needed to make one anyway.
 
 
157
                    result_repo = local_repo.clone(
 
 
159
                        revision_id=revision_id,
 
 
161
                    result_repo.set_make_working_trees(local_repo.make_working_trees())
 
 
162
        # 1 if there is a branch present
 
 
163
        #   make sure its content is available in the target repository
 
 
166
            self.open_branch().clone(result, revision_id=revision_id)
 
 
167
        except errors.NotBranchError:
 
 
170
            self.open_workingtree().clone(result, basis=basis_tree)
 
 
171
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
 
175
    def _get_basis_components(self, basis):
 
 
176
        """Retrieve the basis components that are available at basis."""
 
 
178
            return None, None, None
 
 
180
            basis_tree = basis.open_workingtree()
 
 
181
            basis_branch = basis_tree.branch
 
 
182
            basis_repo = basis_branch.repository
 
 
183
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
 
186
                basis_branch = basis.open_branch()
 
 
187
                basis_repo = basis_branch.repository
 
 
188
            except errors.NotBranchError:
 
 
191
                    basis_repo = basis.open_repository()
 
 
192
                except errors.NoRepositoryPresent:
 
 
194
        return basis_repo, basis_branch, basis_tree
 
 
196
    # TODO: This should be given a Transport, and should chdir up; otherwise
 
 
197
    # this will open a new connection.
 
 
198
    def _make_tail(self, url):
 
 
199
        head, tail = urlutils.split(url)
 
 
200
        if tail and tail != '.':
 
 
201
            t = get_transport(head)
 
 
204
            except errors.FileExists:
 
 
207
    # TODO: Should take a Transport
 
 
209
    def create(cls, base, format=None):
 
 
210
        """Create a new BzrDir at the url 'base'.
 
 
212
        This will call the current default formats initialize with base
 
 
213
        as the only parameter.
 
 
215
        :param format: If supplied, the format of branch to create.  If not
 
 
216
            supplied, the default is used.
 
 
218
        if cls is not BzrDir:
 
 
219
            raise AssertionError("BzrDir.create always creates the default"
 
 
220
                " format, not one of %r" % cls)
 
 
221
        head, tail = urlutils.split(base)
 
 
222
        if tail and tail != '.':
 
 
223
            t = get_transport(head)
 
 
226
            except errors.FileExists:
 
 
229
            format = BzrDirFormat.get_default_format()
 
 
230
        return format.initialize(safe_unicode(base))
 
 
232
    def create_branch(self):
 
 
233
        """Create a branch in this BzrDir.
 
 
235
        The bzrdirs format will control what branch format is created.
 
 
236
        For more control see BranchFormatXX.create(a_bzrdir).
 
 
238
        raise NotImplementedError(self.create_branch)
 
 
241
    def create_branch_and_repo(base, force_new_repo=False, format=None):
 
 
242
        """Create a new BzrDir, Branch and Repository at the url 'base'.
 
 
244
        This will use the current default BzrDirFormat, and use whatever 
 
 
245
        repository format that that uses via bzrdir.create_branch and
 
 
246
        create_repository. If a shared repository is available that is used
 
 
249
        The created Branch object is returned.
 
 
251
        :param base: The URL to create the branch at.
 
 
252
        :param force_new_repo: If True a new repository is always created.
 
 
254
        bzrdir = BzrDir.create(base, format)
 
 
255
        bzrdir._find_or_create_repository(force_new_repo)
 
 
256
        return bzrdir.create_branch()
 
 
258
    def _find_or_create_repository(self, force_new_repo):
 
 
259
        """Create a new repository if needed, returning the repository."""
 
 
261
            return self.create_repository()
 
 
263
            return self.find_repository()
 
 
264
        except errors.NoRepositoryPresent:
 
 
265
            return self.create_repository()
 
 
268
    def create_branch_convenience(base, force_new_repo=False,
 
 
269
                                  force_new_tree=None, format=None):
 
 
270
        """Create a new BzrDir, Branch and Repository at the url 'base'.
 
 
272
        This is a convenience function - it will use an existing repository
 
 
273
        if possible, can be told explicitly whether to create a working tree or
 
 
276
        This will use the current default BzrDirFormat, and use whatever 
 
 
277
        repository format that that uses via bzrdir.create_branch and
 
 
278
        create_repository. If a shared repository is available that is used
 
 
279
        preferentially. Whatever repository is used, its tree creation policy
 
 
282
        The created Branch object is returned.
 
 
283
        If a working tree cannot be made due to base not being a file:// url,
 
 
284
        no error is raised unless force_new_tree is True, in which case no 
 
 
285
        data is created on disk and NotLocalUrl is raised.
 
 
287
        :param base: The URL to create the branch at.
 
 
288
        :param force_new_repo: If True a new repository is always created.
 
 
289
        :param force_new_tree: If True or False force creation of a tree or 
 
 
290
                               prevent such creation respectively.
 
 
291
        :param format: Override for the for the bzrdir format to create
 
 
294
            # check for non local urls
 
 
295
            t = get_transport(safe_unicode(base))
 
 
296
            if not isinstance(t, LocalTransport):
 
 
297
                raise errors.NotLocalUrl(base)
 
 
298
        bzrdir = BzrDir.create(base, format)
 
 
299
        repo = bzrdir._find_or_create_repository(force_new_repo)
 
 
300
        result = bzrdir.create_branch()
 
 
301
        if force_new_tree or (repo.make_working_trees() and 
 
 
302
                              force_new_tree is None):
 
 
304
                bzrdir.create_workingtree()
 
 
305
            except errors.NotLocalUrl:
 
 
310
    def create_repository(base, shared=False, format=None):
 
 
311
        """Create a new BzrDir and Repository at the url 'base'.
 
 
313
        If no format is supplied, this will default to the current default
 
 
314
        BzrDirFormat by default, and use whatever repository format that that
 
 
315
        uses for bzrdirformat.create_repository.
 
 
317
        :param shared: Create a shared repository rather than a standalone
 
 
319
        The Repository object is returned.
 
 
321
        This must be overridden as an instance method in child classes, where
 
 
322
        it should take no parameters and construct whatever repository format
 
 
323
        that child class desires.
 
 
325
        bzrdir = BzrDir.create(base, format)
 
 
326
        return bzrdir.create_repository(shared)
 
 
329
    def create_standalone_workingtree(base, format=None):
 
 
330
        """Create a new BzrDir, WorkingTree, Branch and Repository at 'base'.
 
 
332
        'base' must be a local path or a file:// url.
 
 
334
        This will use the current default BzrDirFormat, and use whatever 
 
 
335
        repository format that that uses for bzrdirformat.create_workingtree,
 
 
336
        create_branch and create_repository.
 
 
338
        :return: The WorkingTree object.
 
 
340
        t = get_transport(safe_unicode(base))
 
 
341
        if not isinstance(t, LocalTransport):
 
 
342
            raise errors.NotLocalUrl(base)
 
 
343
        bzrdir = BzrDir.create_branch_and_repo(safe_unicode(base),
 
 
345
                                               format=format).bzrdir
 
 
346
        return bzrdir.create_workingtree()
 
 
348
    def create_workingtree(self, revision_id=None):
 
 
349
        """Create a working tree at this BzrDir.
 
 
351
        revision_id: create it as of this revision id.
 
 
353
        raise NotImplementedError(self.create_workingtree)
 
 
355
    def destroy_workingtree(self):
 
 
356
        """Destroy the working tree at this BzrDir.
 
 
358
        Formats that do not support this may raise UnsupportedOperation.
 
 
360
        raise NotImplementedError(self.destroy_workingtree)
 
 
362
    def destroy_workingtree_metadata(self):
 
 
363
        """Destroy the control files for the working tree at this BzrDir.
 
 
365
        The contents of working tree files are not affected.
 
 
366
        Formats that do not support this may raise UnsupportedOperation.
 
 
368
        raise NotImplementedError(self.destroy_workingtree_metadata)
 
 
370
    def find_repository(self):
 
 
371
        """Find the repository that should be used for a_bzrdir.
 
 
373
        This does not require a branch as we use it to find the repo for
 
 
374
        new branches as well as to hook existing branches up to their
 
 
378
            return self.open_repository()
 
 
379
        except errors.NoRepositoryPresent:
 
 
381
        next_transport = self.root_transport.clone('..')
 
 
383
            # find the next containing bzrdir
 
 
385
                found_bzrdir = BzrDir.open_containing_from_transport(
 
 
387
            except errors.NotBranchError:
 
 
389
                raise errors.NoRepositoryPresent(self)
 
 
390
            # does it have a repository ?
 
 
392
                repository = found_bzrdir.open_repository()
 
 
393
            except errors.NoRepositoryPresent:
 
 
394
                next_transport = found_bzrdir.root_transport.clone('..')
 
 
395
                if (found_bzrdir.root_transport.base == next_transport.base):
 
 
396
                    # top of the file system
 
 
400
            if ((found_bzrdir.root_transport.base ==
 
 
401
                 self.root_transport.base) or repository.is_shared()):
 
 
404
                raise errors.NoRepositoryPresent(self)
 
 
405
        raise errors.NoRepositoryPresent(self)
 
 
407
    def get_branch_reference(self):
 
 
408
        """Return the referenced URL for the branch in this bzrdir.
 
 
410
        :raises NotBranchError: If there is no Branch.
 
 
411
        :return: The URL the branch in this bzrdir references if it is a
 
 
412
            reference branch, or None for regular branches.
 
 
416
    def get_branch_transport(self, branch_format):
 
 
417
        """Get the transport for use by branch format in this BzrDir.
 
 
419
        Note that bzr dirs that do not support format strings will raise
 
 
420
        IncompatibleFormat if the branch format they are given has
 
 
421
        a format string, and vice versa.
 
 
423
        If branch_format is None, the transport is returned with no 
 
 
424
        checking. if it is not None, then the returned transport is
 
 
425
        guaranteed to point to an existing directory ready for use.
 
 
427
        raise NotImplementedError(self.get_branch_transport)
 
 
429
    def get_repository_transport(self, repository_format):
 
 
430
        """Get the transport for use by repository format in this BzrDir.
 
 
432
        Note that bzr dirs that do not support format strings will raise
 
 
433
        IncompatibleFormat if the repository format they are given has
 
 
434
        a format string, and vice versa.
 
 
436
        If repository_format is None, the transport is returned with no 
 
 
437
        checking. if it is not None, then the returned transport is
 
 
438
        guaranteed to point to an existing directory ready for use.
 
 
440
        raise NotImplementedError(self.get_repository_transport)
 
 
442
    def get_workingtree_transport(self, tree_format):
 
 
443
        """Get the transport for use by workingtree format in this BzrDir.
 
 
445
        Note that bzr dirs that do not support format strings will raise
 
 
446
        IncompatibleFormat if the workingtree format they are given has
 
 
447
        a format string, and vice versa.
 
 
449
        If workingtree_format is None, the transport is returned with no 
 
 
450
        checking. if it is not None, then the returned transport is
 
 
451
        guaranteed to point to an existing directory ready for use.
 
 
453
        raise NotImplementedError(self.get_workingtree_transport)
 
 
455
    def __init__(self, _transport, _format):
 
 
456
        """Initialize a Bzr control dir object.
 
 
458
        Only really common logic should reside here, concrete classes should be
 
 
459
        made with varying behaviours.
 
 
461
        :param _format: the format that is creating this BzrDir instance.
 
 
462
        :param _transport: the transport this dir is based at.
 
 
464
        self._format = _format
 
 
465
        self.transport = _transport.clone('.bzr')
 
 
466
        self.root_transport = _transport
 
 
468
    def is_control_filename(self, filename):
 
 
469
        """True if filename is the name of a path which is reserved for bzrdir's.
 
 
471
        :param filename: A filename within the root transport of this bzrdir.
 
 
473
        This is true IF and ONLY IF the filename is part of the namespace reserved
 
 
474
        for bzr control dirs. Currently this is the '.bzr' directory in the root
 
 
475
        of the root_transport. it is expected that plugins will need to extend
 
 
476
        this in the future - for instance to make bzr talk with svn working
 
 
479
        # this might be better on the BzrDirFormat class because it refers to 
 
 
480
        # all the possible bzrdir disk formats. 
 
 
481
        # This method is tested via the workingtree is_control_filename tests- 
 
 
482
        # it was extracted from WorkingTree.is_control_filename. If the methods
 
 
483
        # contract is extended beyond the current trivial  implementation please
 
 
484
        # add new tests for it to the appropriate place.
 
 
485
        return filename == '.bzr' or filename.startswith('.bzr/')
 
 
487
    def needs_format_conversion(self, format=None):
 
 
488
        """Return true if this bzrdir needs convert_format run on it.
 
 
490
        For instance, if the repository format is out of date but the 
 
 
491
        branch and working tree are not, this should return True.
 
 
493
        :param format: Optional parameter indicating a specific desired
 
 
494
                       format we plan to arrive at.
 
 
496
        raise NotImplementedError(self.needs_format_conversion)
 
 
499
    def open_unsupported(base):
 
 
500
        """Open a branch which is not supported."""
 
 
501
        return BzrDir.open(base, _unsupported=True)
 
 
504
    def open(base, _unsupported=False):
 
 
505
        """Open an existing bzrdir, rooted at 'base' (url)
 
 
507
        _unsupported is a private parameter to the BzrDir class.
 
 
509
        t = get_transport(base)
 
 
510
        return BzrDir.open_from_transport(t, _unsupported=_unsupported)
 
 
513
    def open_from_transport(transport, _unsupported=False):
 
 
514
        """Open a bzrdir within a particular directory.
 
 
516
        :param transport: Transport containing the bzrdir.
 
 
517
        :param _unsupported: private.
 
 
519
        format = BzrDirFormat.find_format(transport)
 
 
520
        BzrDir._check_supported(format, _unsupported)
 
 
521
        return format.open(transport, _found=True)
 
 
523
    def open_branch(self, unsupported=False):
 
 
524
        """Open the branch object at this BzrDir if one is present.
 
 
526
        If unsupported is True, then no longer supported branch formats can
 
 
529
        TODO: static convenience version of this?
 
 
531
        raise NotImplementedError(self.open_branch)
 
 
534
    def open_containing(url):
 
 
535
        """Open an existing branch which contains url.
 
 
537
        :param url: url to search from.
 
 
538
        See open_containing_from_transport for more detail.
 
 
540
        return BzrDir.open_containing_from_transport(get_transport(url))
 
 
543
    def open_containing_from_transport(a_transport):
 
 
544
        """Open an existing branch which contains a_transport.base
 
 
546
        This probes for a branch at a_transport, and searches upwards from there.
 
 
548
        Basically we keep looking up until we find the control directory or
 
 
549
        run into the root.  If there isn't one, raises NotBranchError.
 
 
550
        If there is one and it is either an unrecognised format or an unsupported 
 
 
551
        format, UnknownFormatError or UnsupportedFormatError are raised.
 
 
552
        If there is one, it is returned, along with the unused portion of url.
 
 
554
        :return: The BzrDir that contains the path, and a Unicode path 
 
 
555
                for the rest of the URL.
 
 
557
        # this gets the normalised url back. I.e. '.' -> the full path.
 
 
558
        url = a_transport.base
 
 
561
                result = BzrDir.open_from_transport(a_transport)
 
 
562
                return result, urlutils.unescape(a_transport.relpath(url))
 
 
563
            except errors.NotBranchError, e:
 
 
565
            new_t = a_transport.clone('..')
 
 
566
            if new_t.base == a_transport.base:
 
 
567
                # reached the root, whatever that may be
 
 
568
                raise errors.NotBranchError(path=url)
 
 
572
    def open_containing_tree_or_branch(klass, location):
 
 
573
        """Return the branch and working tree contained by a location.
 
 
575
        Returns (tree, branch, relpath).
 
 
576
        If there is no tree at containing the location, tree will be None.
 
 
577
        If there is no branch containing the location, an exception will be
 
 
579
        relpath is the portion of the path that is contained by the branch.
 
 
581
        bzrdir, relpath = klass.open_containing(location)
 
 
583
            tree = bzrdir.open_workingtree()
 
 
584
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
 
586
            branch = bzrdir.open_branch()
 
 
589
        return tree, branch, relpath
 
 
591
    def open_repository(self, _unsupported=False):
 
 
592
        """Open the repository object at this BzrDir if one is present.
 
 
594
        This will not follow the Branch object pointer - its strictly a direct
 
 
595
        open facility. Most client code should use open_branch().repository to
 
 
598
        _unsupported is a private parameter, not part of the api.
 
 
599
        TODO: static convenience version of this?
 
 
601
        raise NotImplementedError(self.open_repository)
 
 
603
    def open_workingtree(self, _unsupported=False):
 
 
604
        """Open the workingtree object at this BzrDir if one is present.
 
 
606
        TODO: static convenience version of this?
 
 
608
        raise NotImplementedError(self.open_workingtree)
 
 
610
    def has_branch(self):
 
 
611
        """Tell if this bzrdir contains a branch.
 
 
613
        Note: if you're going to open the branch, you should just go ahead
 
 
614
        and try, and not ask permission first.  (This method just opens the 
 
 
615
        branch and discards it, and that's somewhat expensive.) 
 
 
620
        except errors.NotBranchError:
 
 
623
    def has_workingtree(self):
 
 
624
        """Tell if this bzrdir contains a working tree.
 
 
626
        This will still raise an exception if the bzrdir has a workingtree that
 
 
627
        is remote & inaccessible.
 
 
629
        Note: if you're going to open the working tree, you should just go ahead
 
 
630
        and try, and not ask permission first.  (This method just opens the 
 
 
631
        workingtree and discards it, and that's somewhat expensive.) 
 
 
634
            self.open_workingtree()
 
 
636
        except errors.NoWorkingTree:
 
 
639
    def cloning_metadir(self, basis=None):
 
 
640
        """Produce a metadir suitable for cloning with"""
 
 
641
        def related_repository(bzrdir):
 
 
643
                branch = bzrdir.open_branch()
 
 
644
                return branch.repository
 
 
645
            except errors.NotBranchError:
 
 
647
                return bzrdir.open_repository()
 
 
648
        result_format = self._format.__class__()
 
 
651
                source_repository = related_repository(self)
 
 
652
            except errors.NoRepositoryPresent:
 
 
655
                source_repository = related_repository(self)
 
 
656
            result_format.repository_format = source_repository._format
 
 
657
        except errors.NoRepositoryPresent:
 
 
661
    def sprout(self, url, revision_id=None, basis=None, force_new_repo=False):
 
 
662
        """Create a copy of this bzrdir prepared for use as a new line of
 
 
665
        If urls last component does not exist, it will be created.
 
 
667
        Attributes related to the identity of the source branch like
 
 
668
        branch nickname will be cleaned, a working tree is created
 
 
669
        whether one existed before or not; and a local branch is always
 
 
672
        if revision_id is not None, then the clone operation may tune
 
 
673
            itself to download less data.
 
 
676
        cloning_format = self.cloning_metadir(basis)
 
 
677
        result = cloning_format.initialize(url)
 
 
678
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
 
 
680
            source_branch = self.open_branch()
 
 
681
            source_repository = source_branch.repository
 
 
682
        except errors.NotBranchError:
 
 
685
                source_repository = self.open_repository()
 
 
686
            except errors.NoRepositoryPresent:
 
 
687
                # copy the entire basis one if there is one
 
 
688
                # but there is no repository.
 
 
689
                source_repository = basis_repo
 
 
694
                result_repo = result.find_repository()
 
 
695
            except errors.NoRepositoryPresent:
 
 
697
        if source_repository is None and result_repo is not None:
 
 
699
        elif source_repository is None and result_repo is None:
 
 
700
            # no repo available, make a new one
 
 
701
            result.create_repository()
 
 
702
        elif source_repository is not None and result_repo is None:
 
 
703
            # have source, and want to make a new target repo
 
 
704
            # we don't clone the repo because that preserves attributes
 
 
705
            # like is_shared(), and we have not yet implemented a 
 
 
706
            # repository sprout().
 
 
707
            result_repo = result.create_repository()
 
 
708
        if result_repo is not None:
 
 
709
            # fetch needed content into target.
 
 
711
                # XXX FIXME RBC 20060214 need tests for this when the basis
 
 
713
                result_repo.fetch(basis_repo, revision_id=revision_id)
 
 
714
            if source_repository is not None:
 
 
715
                result_repo.fetch(source_repository, revision_id=revision_id)
 
 
716
        if source_branch is not None:
 
 
717
            source_branch.sprout(result, revision_id=revision_id)
 
 
719
            result.create_branch()
 
 
720
        # TODO: jam 20060426 we probably need a test in here in the
 
 
721
        #       case that the newly sprouted branch is a remote one
 
 
722
        if result_repo is None or result_repo.make_working_trees():
 
 
723
            wt = result.create_workingtree()
 
 
724
            if wt.inventory.root is None:
 
 
726
                    wt.set_root_id(self.open_workingtree.get_root_id())
 
 
727
                except errors.NoWorkingTree:
 
 
732
class BzrDirPreSplitOut(BzrDir):
 
 
733
    """A common class for the all-in-one formats."""
 
 
735
    def __init__(self, _transport, _format):
 
 
736
        """See BzrDir.__init__."""
 
 
737
        super(BzrDirPreSplitOut, self).__init__(_transport, _format)
 
 
738
        assert self._format._lock_class == lockable_files.TransportLock
 
 
739
        assert self._format._lock_file_name == 'branch-lock'
 
 
740
        self._control_files = lockable_files.LockableFiles(
 
 
741
                                            self.get_branch_transport(None),
 
 
742
                                            self._format._lock_file_name,
 
 
743
                                            self._format._lock_class)
 
 
745
    def break_lock(self):
 
 
746
        """Pre-splitout bzrdirs do not suffer from stale locks."""
 
 
747
        raise NotImplementedError(self.break_lock)
 
 
749
    def clone(self, url, revision_id=None, basis=None, force_new_repo=False):
 
 
750
        """See BzrDir.clone()."""
 
 
751
        from bzrlib.workingtree import WorkingTreeFormat2
 
 
753
        result = self._format._initialize_for_clone(url)
 
 
754
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
 
 
755
        self.open_repository().clone(result, revision_id=revision_id, basis=basis_repo)
 
 
756
        from_branch = self.open_branch()
 
 
757
        from_branch.clone(result, revision_id=revision_id)
 
 
759
            self.open_workingtree().clone(result, basis=basis_tree)
 
 
760
        except errors.NotLocalUrl:
 
 
761
            # make a new one, this format always has to have one.
 
 
763
                WorkingTreeFormat2().initialize(result)
 
 
764
            except errors.NotLocalUrl:
 
 
765
                # but we cannot do it for remote trees.
 
 
766
                to_branch = result.open_branch()
 
 
767
                WorkingTreeFormat2().stub_initialize_remote(to_branch.control_files)
 
 
770
    def create_branch(self):
 
 
771
        """See BzrDir.create_branch."""
 
 
772
        return self.open_branch()
 
 
774
    def create_repository(self, shared=False):
 
 
775
        """See BzrDir.create_repository."""
 
 
777
            raise errors.IncompatibleFormat('shared repository', self._format)
 
 
778
        return self.open_repository()
 
 
780
    def create_workingtree(self, revision_id=None):
 
 
781
        """See BzrDir.create_workingtree."""
 
 
782
        # this looks buggy but is not -really-
 
 
783
        # clone and sprout will have set the revision_id
 
 
784
        # and that will have set it for us, its only
 
 
785
        # specific uses of create_workingtree in isolation
 
 
786
        # that can do wonky stuff here, and that only
 
 
787
        # happens for creating checkouts, which cannot be 
 
 
788
        # done on this format anyway. So - acceptable wart.
 
 
789
        result = self.open_workingtree()
 
 
790
        if revision_id is not None:
 
 
791
            if revision_id == _mod_revision.NULL_REVISION:
 
 
792
                result.set_parent_ids([])
 
 
794
                result.set_parent_ids([revision_id])
 
 
797
    def destroy_workingtree(self):
 
 
798
        """See BzrDir.destroy_workingtree."""
 
 
799
        raise errors.UnsupportedOperation(self.destroy_workingtree, self)
 
 
801
    def destroy_workingtree_metadata(self):
 
 
802
        """See BzrDir.destroy_workingtree_metadata."""
 
 
803
        raise errors.UnsupportedOperation(self.destroy_workingtree_metadata, 
 
 
806
    def get_branch_transport(self, branch_format):
 
 
807
        """See BzrDir.get_branch_transport()."""
 
 
808
        if branch_format is None:
 
 
809
            return self.transport
 
 
811
            branch_format.get_format_string()
 
 
812
        except NotImplementedError:
 
 
813
            return self.transport
 
 
814
        raise errors.IncompatibleFormat(branch_format, self._format)
 
 
816
    def get_repository_transport(self, repository_format):
 
 
817
        """See BzrDir.get_repository_transport()."""
 
 
818
        if repository_format is None:
 
 
819
            return self.transport
 
 
821
            repository_format.get_format_string()
 
 
822
        except NotImplementedError:
 
 
823
            return self.transport
 
 
824
        raise errors.IncompatibleFormat(repository_format, self._format)
 
 
826
    def get_workingtree_transport(self, workingtree_format):
 
 
827
        """See BzrDir.get_workingtree_transport()."""
 
 
828
        if workingtree_format is None:
 
 
829
            return self.transport
 
 
831
            workingtree_format.get_format_string()
 
 
832
        except NotImplementedError:
 
 
833
            return self.transport
 
 
834
        raise errors.IncompatibleFormat(workingtree_format, self._format)
 
 
836
    def needs_format_conversion(self, format=None):
 
 
837
        """See BzrDir.needs_format_conversion()."""
 
 
838
        # if the format is not the same as the system default,
 
 
839
        # an upgrade is needed.
 
 
841
            format = BzrDirFormat.get_default_format()
 
 
842
        return not isinstance(self._format, format.__class__)
 
 
844
    def open_branch(self, unsupported=False):
 
 
845
        """See BzrDir.open_branch."""
 
 
846
        from bzrlib.branch import BzrBranchFormat4
 
 
847
        format = BzrBranchFormat4()
 
 
848
        self._check_supported(format, unsupported)
 
 
849
        return format.open(self, _found=True)
 
 
851
    def sprout(self, url, revision_id=None, basis=None, force_new_repo=False):
 
 
852
        """See BzrDir.sprout()."""
 
 
853
        from bzrlib.workingtree import WorkingTreeFormat2
 
 
855
        result = self._format._initialize_for_clone(url)
 
 
856
        basis_repo, basis_branch, basis_tree = self._get_basis_components(basis)
 
 
858
            self.open_repository().clone(result, revision_id=revision_id, basis=basis_repo)
 
 
859
        except errors.NoRepositoryPresent:
 
 
862
            self.open_branch().sprout(result, revision_id=revision_id)
 
 
863
        except errors.NotBranchError:
 
 
865
        # we always want a working tree
 
 
866
        WorkingTreeFormat2().initialize(result)
 
 
870
class BzrDir4(BzrDirPreSplitOut):
 
 
871
    """A .bzr version 4 control object.
 
 
873
    This is a deprecated format and may be removed after sept 2006.
 
 
876
    def create_repository(self, shared=False):
 
 
877
        """See BzrDir.create_repository."""
 
 
878
        return self._format.repository_format.initialize(self, shared)
 
 
880
    def needs_format_conversion(self, format=None):
 
 
881
        """Format 4 dirs are always in need of conversion."""
 
 
884
    def open_repository(self):
 
 
885
        """See BzrDir.open_repository."""
 
 
886
        from bzrlib.repository import RepositoryFormat4
 
 
887
        return RepositoryFormat4().open(self, _found=True)
 
 
890
class BzrDir5(BzrDirPreSplitOut):
 
 
891
    """A .bzr version 5 control object.
 
 
893
    This is a deprecated format and may be removed after sept 2006.
 
 
896
    def open_repository(self):
 
 
897
        """See BzrDir.open_repository."""
 
 
898
        from bzrlib.repository import RepositoryFormat5
 
 
899
        return RepositoryFormat5().open(self, _found=True)
 
 
901
    def open_workingtree(self, _unsupported=False):
 
 
902
        """See BzrDir.create_workingtree."""
 
 
903
        from bzrlib.workingtree import WorkingTreeFormat2
 
 
904
        return WorkingTreeFormat2().open(self, _found=True)
 
 
907
class BzrDir6(BzrDirPreSplitOut):
 
 
908
    """A .bzr version 6 control object.
 
 
910
    This is a deprecated format and may be removed after sept 2006.
 
 
913
    def open_repository(self):
 
 
914
        """See BzrDir.open_repository."""
 
 
915
        from bzrlib.repository import RepositoryFormat6
 
 
916
        return RepositoryFormat6().open(self, _found=True)
 
 
918
    def open_workingtree(self, _unsupported=False):
 
 
919
        """See BzrDir.create_workingtree."""
 
 
920
        from bzrlib.workingtree import WorkingTreeFormat2
 
 
921
        return WorkingTreeFormat2().open(self, _found=True)
 
 
924
class BzrDirMeta1(BzrDir):
 
 
925
    """A .bzr meta version 1 control object.
 
 
927
    This is the first control object where the 
 
 
928
    individual aspects are really split out: there are separate repository,
 
 
929
    workingtree and branch subdirectories and any subset of the three can be
 
 
930
    present within a BzrDir.
 
 
933
    def can_convert_format(self):
 
 
934
        """See BzrDir.can_convert_format()."""
 
 
937
    def create_branch(self):
 
 
938
        """See BzrDir.create_branch."""
 
 
939
        from bzrlib.branch import BranchFormat
 
 
940
        return BranchFormat.get_default_format().initialize(self)
 
 
942
    def create_repository(self, shared=False):
 
 
943
        """See BzrDir.create_repository."""
 
 
944
        return self._format.repository_format.initialize(self, shared)
 
 
946
    def create_workingtree(self, revision_id=None):
 
 
947
        """See BzrDir.create_workingtree."""
 
 
948
        from bzrlib.workingtree import WorkingTreeFormat
 
 
949
        return WorkingTreeFormat.get_default_format().initialize(self, revision_id)
 
 
951
    def destroy_workingtree(self):
 
 
952
        """See BzrDir.destroy_workingtree."""
 
 
953
        wt = self.open_workingtree()
 
 
954
        repository = wt.branch.repository
 
 
955
        empty = repository.revision_tree(_mod_revision.NULL_REVISION)
 
 
956
        wt.revert([], old_tree=empty)
 
 
957
        self.destroy_workingtree_metadata()
 
 
959
    def destroy_workingtree_metadata(self):
 
 
960
        self.transport.delete_tree('checkout')
 
 
962
    def _get_mkdir_mode(self):
 
 
963
        """Figure out the mode to use when creating a bzrdir subdir."""
 
 
964
        temp_control = lockable_files.LockableFiles(self.transport, '',
 
 
965
                                     lockable_files.TransportLock)
 
 
966
        return temp_control._dir_mode
 
 
968
    def get_branch_reference(self):
 
 
969
        """See BzrDir.get_branch_reference()."""
 
 
970
        from bzrlib.branch import BranchFormat
 
 
971
        format = BranchFormat.find_format(self)
 
 
972
        return format.get_reference(self)
 
 
974
    def get_branch_transport(self, branch_format):
 
 
975
        """See BzrDir.get_branch_transport()."""
 
 
976
        if branch_format is None:
 
 
977
            return self.transport.clone('branch')
 
 
979
            branch_format.get_format_string()
 
 
980
        except NotImplementedError:
 
 
981
            raise errors.IncompatibleFormat(branch_format, self._format)
 
 
983
            self.transport.mkdir('branch', mode=self._get_mkdir_mode())
 
 
984
        except errors.FileExists:
 
 
986
        return self.transport.clone('branch')
 
 
988
    def get_repository_transport(self, repository_format):
 
 
989
        """See BzrDir.get_repository_transport()."""
 
 
990
        if repository_format is None:
 
 
991
            return self.transport.clone('repository')
 
 
993
            repository_format.get_format_string()
 
 
994
        except NotImplementedError:
 
 
995
            raise errors.IncompatibleFormat(repository_format, self._format)
 
 
997
            self.transport.mkdir('repository', mode=self._get_mkdir_mode())
 
 
998
        except errors.FileExists:
 
 
1000
        return self.transport.clone('repository')
 
 
1002
    def get_workingtree_transport(self, workingtree_format):
 
 
1003
        """See BzrDir.get_workingtree_transport()."""
 
 
1004
        if workingtree_format is None:
 
 
1005
            return self.transport.clone('checkout')
 
 
1007
            workingtree_format.get_format_string()
 
 
1008
        except NotImplementedError:
 
 
1009
            raise errors.IncompatibleFormat(workingtree_format, self._format)
 
 
1011
            self.transport.mkdir('checkout', mode=self._get_mkdir_mode())
 
 
1012
        except errors.FileExists:
 
 
1014
        return self.transport.clone('checkout')
 
 
1016
    def needs_format_conversion(self, format=None):
 
 
1017
        """See BzrDir.needs_format_conversion()."""
 
 
1019
            format = BzrDirFormat.get_default_format()
 
 
1020
        if not isinstance(self._format, format.__class__):
 
 
1021
            # it is not a meta dir format, conversion is needed.
 
 
1023
        # we might want to push this down to the repository?
 
 
1025
            if not isinstance(self.open_repository()._format,
 
 
1026
                              format.repository_format.__class__):
 
 
1027
                # the repository needs an upgrade.
 
 
1029
        except errors.NoRepositoryPresent:
 
 
1031
        # currently there are no other possible conversions for meta1 formats.
 
 
1034
    def open_branch(self, unsupported=False):
 
 
1035
        """See BzrDir.open_branch."""
 
 
1036
        from bzrlib.branch import BranchFormat
 
 
1037
        format = BranchFormat.find_format(self)
 
 
1038
        self._check_supported(format, unsupported)
 
 
1039
        return format.open(self, _found=True)
 
 
1041
    def open_repository(self, unsupported=False):
 
 
1042
        """See BzrDir.open_repository."""
 
 
1043
        from bzrlib.repository import RepositoryFormat
 
 
1044
        format = RepositoryFormat.find_format(self)
 
 
1045
        self._check_supported(format, unsupported)
 
 
1046
        return format.open(self, _found=True)
 
 
1048
    def open_workingtree(self, unsupported=False):
 
 
1049
        """See BzrDir.open_workingtree."""
 
 
1050
        from bzrlib.workingtree import WorkingTreeFormat
 
 
1051
        format = WorkingTreeFormat.find_format(self)
 
 
1052
        self._check_supported(format, unsupported)
 
 
1053
        return format.open(self, _found=True)
 
 
1056
class BzrDirFormat(object):
 
 
1057
    """An encapsulation of the initialization and open routines for a format.
 
 
1059
    Formats provide three things:
 
 
1060
     * An initialization routine,
 
 
1064
    Formats are placed in an dict by their format string for reference 
 
 
1065
    during bzrdir opening. These should be subclasses of BzrDirFormat
 
 
1068
    Once a format is deprecated, just deprecate the initialize and open
 
 
1069
    methods on the format class. Do not deprecate the object, as the 
 
 
1070
    object will be created every system load.
 
 
1073
    _default_format = None
 
 
1074
    """The default format used for new .bzr dirs."""
 
 
1077
    """The known formats."""
 
 
1079
    _control_formats = []
 
 
1080
    """The registered control formats - .bzr, ....
 
 
1082
    This is a list of BzrDirFormat objects.
 
 
1085
    _lock_file_name = 'branch-lock'
 
 
1087
    # _lock_class must be set in subclasses to the lock type, typ.
 
 
1088
    # TransportLock or LockDir
 
 
1091
    def find_format(klass, transport):
 
 
1092
        """Return the format present at transport."""
 
 
1093
        for format in klass._control_formats:
 
 
1095
                return format.probe_transport(transport)
 
 
1096
            except errors.NotBranchError:
 
 
1097
                # this format does not find a control dir here.
 
 
1099
        raise errors.NotBranchError(path=transport.base)
 
 
1102
    def probe_transport(klass, transport):
 
 
1103
        """Return the .bzrdir style format present in a directory."""
 
 
1105
            format_string = transport.get(".bzr/branch-format").read()
 
 
1106
        except errors.NoSuchFile:
 
 
1107
            raise errors.NotBranchError(path=transport.base)
 
 
1110
            return klass._formats[format_string]
 
 
1112
            raise errors.UnknownFormatError(format=format_string)
 
 
1115
    def get_default_format(klass):
 
 
1116
        """Return the current default format."""
 
 
1117
        return klass._default_format
 
 
1119
    def get_format_string(self):
 
 
1120
        """Return the ASCII format string that identifies this format."""
 
 
1121
        raise NotImplementedError(self.get_format_string)
 
 
1123
    def get_format_description(self):
 
 
1124
        """Return the short description for this format."""
 
 
1125
        raise NotImplementedError(self.get_format_description)
 
 
1127
    def get_converter(self, format=None):
 
 
1128
        """Return the converter to use to convert bzrdirs needing converts.
 
 
1130
        This returns a bzrlib.bzrdir.Converter object.
 
 
1132
        This should return the best upgrader to step this format towards the
 
 
1133
        current default format. In the case of plugins we can/should provide
 
 
1134
        some means for them to extend the range of returnable converters.
 
 
1136
        :param format: Optional format to override the default format of the 
 
 
1139
        raise NotImplementedError(self.get_converter)
 
 
1141
    def initialize(self, url):
 
 
1142
        """Create a bzr control dir at this url and return an opened copy.
 
 
1144
        Subclasses should typically override initialize_on_transport
 
 
1145
        instead of this method.
 
 
1147
        return self.initialize_on_transport(get_transport(url))
 
 
1149
    def initialize_on_transport(self, transport):
 
 
1150
        """Initialize a new bzrdir in the base directory of a Transport."""
 
 
1151
        # Since we don't have a .bzr directory, inherit the
 
 
1152
        # mode from the root directory
 
 
1153
        temp_control = lockable_files.LockableFiles(transport,
 
 
1154
                            '', lockable_files.TransportLock)
 
 
1155
        temp_control._transport.mkdir('.bzr',
 
 
1156
                                      # FIXME: RBC 20060121 don't peek under
 
 
1158
                                      mode=temp_control._dir_mode)
 
 
1159
        file_mode = temp_control._file_mode
 
 
1161
        mutter('created control directory in ' + transport.base)
 
 
1162
        control = transport.clone('.bzr')
 
 
1163
        utf8_files = [('README', 
 
 
1164
                       "This is a Bazaar-NG control directory.\n"
 
 
1165
                       "Do not change any files in this directory.\n"),
 
 
1166
                      ('branch-format', self.get_format_string()),
 
 
1168
        # NB: no need to escape relative paths that are url safe.
 
 
1169
        control_files = lockable_files.LockableFiles(control,
 
 
1170
                            self._lock_file_name, self._lock_class)
 
 
1171
        control_files.create_lock()
 
 
1172
        control_files.lock_write()
 
 
1174
            for file, content in utf8_files:
 
 
1175
                control_files.put_utf8(file, content)
 
 
1177
            control_files.unlock()
 
 
1178
        return self.open(transport, _found=True)
 
 
1180
    def is_supported(self):
 
 
1181
        """Is this format supported?
 
 
1183
        Supported formats must be initializable and openable.
 
 
1184
        Unsupported formats may not support initialization or committing or 
 
 
1185
        some other features depending on the reason for not being supported.
 
 
1189
    def same_model(self, target_format):
 
 
1190
        return (self.repository_format.rich_root_data == 
 
 
1191
            target_format.rich_root_data)
 
 
1194
    def known_formats(klass):
 
 
1195
        """Return all the known formats.
 
 
1197
        Concrete formats should override _known_formats.
 
 
1199
        # There is double indirection here to make sure that control 
 
 
1200
        # formats used by more than one dir format will only be probed 
 
 
1201
        # once. This can otherwise be quite expensive for remote connections.
 
 
1203
        for format in klass._control_formats:
 
 
1204
            result.update(format._known_formats())
 
 
1208
    def _known_formats(klass):
 
 
1209
        """Return the known format instances for this control format."""
 
 
1210
        return set(klass._formats.values())
 
 
1212
    def open(self, transport, _found=False):
 
 
1213
        """Return an instance of this format for the dir transport points at.
 
 
1215
        _found is a private parameter, do not use it.
 
 
1218
            found_format = BzrDirFormat.find_format(transport)
 
 
1219
            if not isinstance(found_format, self.__class__):
 
 
1220
                raise AssertionError("%s was asked to open %s, but it seems to need "
 
 
1222
                        % (self, transport, found_format))
 
 
1223
        return self._open(transport)
 
 
1225
    def _open(self, transport):
 
 
1226
        """Template method helper for opening BzrDirectories.
 
 
1228
        This performs the actual open and any additional logic or parameter
 
 
1231
        raise NotImplementedError(self._open)
 
 
1234
    def register_format(klass, format):
 
 
1235
        klass._formats[format.get_format_string()] = format
 
 
1238
    def register_control_format(klass, format):
 
 
1239
        """Register a format that does not use '.bzrdir' for its control dir.
 
 
1241
        TODO: This should be pulled up into a 'ControlDirFormat' base class
 
 
1242
        which BzrDirFormat can inherit from, and renamed to register_format 
 
 
1243
        there. It has been done without that for now for simplicity of
 
 
1246
        klass._control_formats.append(format)
 
 
1249
    @symbol_versioning.deprecated_method(symbol_versioning.zero_fourteen)
 
 
1250
    def set_default_format(klass, format):
 
 
1251
        klass._set_default_format(format)
 
 
1254
    def _set_default_format(klass, format):
 
 
1255
        """Set default format (for testing behavior of defaults only)"""
 
 
1256
        klass._default_format = format
 
 
1259
        return self.get_format_string()[:-1]
 
 
1262
    def unregister_format(klass, format):
 
 
1263
        assert klass._formats[format.get_format_string()] is format
 
 
1264
        del klass._formats[format.get_format_string()]
 
 
1267
    def unregister_control_format(klass, format):
 
 
1268
        klass._control_formats.remove(format)
 
 
1271
# register BzrDirFormat as a control format
 
 
1272
BzrDirFormat.register_control_format(BzrDirFormat)
 
 
1275
class BzrDirFormat4(BzrDirFormat):
 
 
1276
    """Bzr dir format 4.
 
 
1278
    This format is a combined format for working tree, branch and repository.
 
 
1280
     - Format 1 working trees [always]
 
 
1281
     - Format 4 branches [always]
 
 
1282
     - Format 4 repositories [always]
 
 
1284
    This format is deprecated: it indexes texts using a text it which is
 
 
1285
    removed in format 5; write support for this format has been removed.
 
 
1288
    _lock_class = lockable_files.TransportLock
 
 
1290
    def get_format_string(self):
 
 
1291
        """See BzrDirFormat.get_format_string()."""
 
 
1292
        return "Bazaar-NG branch, format 0.0.4\n"
 
 
1294
    def get_format_description(self):
 
 
1295
        """See BzrDirFormat.get_format_description()."""
 
 
1296
        return "All-in-one format 4"
 
 
1298
    def get_converter(self, format=None):
 
 
1299
        """See BzrDirFormat.get_converter()."""
 
 
1300
        # there is one and only one upgrade path here.
 
 
1301
        return ConvertBzrDir4To5()
 
 
1303
    def initialize_on_transport(self, transport):
 
 
1304
        """Format 4 branches cannot be created."""
 
 
1305
        raise errors.UninitializableFormat(self)
 
 
1307
    def is_supported(self):
 
 
1308
        """Format 4 is not supported.
 
 
1310
        It is not supported because the model changed from 4 to 5 and the
 
 
1311
        conversion logic is expensive - so doing it on the fly was not 
 
 
1316
    def _open(self, transport):
 
 
1317
        """See BzrDirFormat._open."""
 
 
1318
        return BzrDir4(transport, self)
 
 
1320
    def __return_repository_format(self):
 
 
1321
        """Circular import protection."""
 
 
1322
        from bzrlib.repository import RepositoryFormat4
 
 
1323
        return RepositoryFormat4()
 
 
1324
    repository_format = property(__return_repository_format)
 
 
1327
class BzrDirFormat5(BzrDirFormat):
 
 
1328
    """Bzr control format 5.
 
 
1330
    This format is a combined format for working tree, branch and repository.
 
 
1332
     - Format 2 working trees [always] 
 
 
1333
     - Format 4 branches [always] 
 
 
1334
     - Format 5 repositories [always]
 
 
1335
       Unhashed stores in the repository.
 
 
1338
    _lock_class = lockable_files.TransportLock
 
 
1340
    def get_format_string(self):
 
 
1341
        """See BzrDirFormat.get_format_string()."""
 
 
1342
        return "Bazaar-NG branch, format 5\n"
 
 
1344
    def get_format_description(self):
 
 
1345
        """See BzrDirFormat.get_format_description()."""
 
 
1346
        return "All-in-one format 5"
 
 
1348
    def get_converter(self, format=None):
 
 
1349
        """See BzrDirFormat.get_converter()."""
 
 
1350
        # there is one and only one upgrade path here.
 
 
1351
        return ConvertBzrDir5To6()
 
 
1353
    def _initialize_for_clone(self, url):
 
 
1354
        return self.initialize_on_transport(get_transport(url), _cloning=True)
 
 
1356
    def initialize_on_transport(self, transport, _cloning=False):
 
 
1357
        """Format 5 dirs always have working tree, branch and repository.
 
 
1359
        Except when they are being cloned.
 
 
1361
        from bzrlib.branch import BzrBranchFormat4
 
 
1362
        from bzrlib.repository import RepositoryFormat5
 
 
1363
        from bzrlib.workingtree import WorkingTreeFormat2
 
 
1364
        result = (super(BzrDirFormat5, self).initialize_on_transport(transport))
 
 
1365
        RepositoryFormat5().initialize(result, _internal=True)
 
 
1367
            branch = BzrBranchFormat4().initialize(result)
 
 
1369
                WorkingTreeFormat2().initialize(result)
 
 
1370
            except errors.NotLocalUrl:
 
 
1371
                # Even though we can't access the working tree, we need to
 
 
1372
                # create its control files.
 
 
1373
                WorkingTreeFormat2().stub_initialize_remote(branch.control_files)
 
 
1376
    def _open(self, transport):
 
 
1377
        """See BzrDirFormat._open."""
 
 
1378
        return BzrDir5(transport, self)
 
 
1380
    def __return_repository_format(self):
 
 
1381
        """Circular import protection."""
 
 
1382
        from bzrlib.repository import RepositoryFormat5
 
 
1383
        return RepositoryFormat5()
 
 
1384
    repository_format = property(__return_repository_format)
 
 
1387
class BzrDirFormat6(BzrDirFormat):
 
 
1388
    """Bzr control format 6.
 
 
1390
    This format is a combined format for working tree, branch and repository.
 
 
1392
     - Format 2 working trees [always] 
 
 
1393
     - Format 4 branches [always] 
 
 
1394
     - Format 6 repositories [always]
 
 
1397
    _lock_class = lockable_files.TransportLock
 
 
1399
    def get_format_string(self):
 
 
1400
        """See BzrDirFormat.get_format_string()."""
 
 
1401
        return "Bazaar-NG branch, format 6\n"
 
 
1403
    def get_format_description(self):
 
 
1404
        """See BzrDirFormat.get_format_description()."""
 
 
1405
        return "All-in-one format 6"
 
 
1407
    def get_converter(self, format=None):
 
 
1408
        """See BzrDirFormat.get_converter()."""
 
 
1409
        # there is one and only one upgrade path here.
 
 
1410
        return ConvertBzrDir6ToMeta()
 
 
1412
    def _initialize_for_clone(self, url):
 
 
1413
        return self.initialize_on_transport(get_transport(url), _cloning=True)
 
 
1415
    def initialize_on_transport(self, transport, _cloning=False):
 
 
1416
        """Format 6 dirs always have working tree, branch and repository.
 
 
1418
        Except when they are being cloned.
 
 
1420
        from bzrlib.branch import BzrBranchFormat4
 
 
1421
        from bzrlib.repository import RepositoryFormat6
 
 
1422
        from bzrlib.workingtree import WorkingTreeFormat2
 
 
1423
        result = super(BzrDirFormat6, self).initialize_on_transport(transport)
 
 
1424
        RepositoryFormat6().initialize(result, _internal=True)
 
 
1426
            branch = BzrBranchFormat4().initialize(result)
 
 
1428
                WorkingTreeFormat2().initialize(result)
 
 
1429
            except errors.NotLocalUrl:
 
 
1430
                # Even though we can't access the working tree, we need to
 
 
1431
                # create its control files.
 
 
1432
                WorkingTreeFormat2().stub_initialize_remote(branch.control_files)
 
 
1435
    def _open(self, transport):
 
 
1436
        """See BzrDirFormat._open."""
 
 
1437
        return BzrDir6(transport, self)
 
 
1439
    def __return_repository_format(self):
 
 
1440
        """Circular import protection."""
 
 
1441
        from bzrlib.repository import RepositoryFormat6
 
 
1442
        return RepositoryFormat6()
 
 
1443
    repository_format = property(__return_repository_format)
 
 
1446
class BzrDirMetaFormat1(BzrDirFormat):
 
 
1447
    """Bzr meta control format 1
 
 
1449
    This is the first format with split out working tree, branch and repository
 
 
1452
     - Format 3 working trees [optional]
 
 
1453
     - Format 5 branches [optional]
 
 
1454
     - Format 7 repositories [optional]
 
 
1457
    _lock_class = lockdir.LockDir
 
 
1459
    def get_converter(self, format=None):
 
 
1460
        """See BzrDirFormat.get_converter()."""
 
 
1462
            format = BzrDirFormat.get_default_format()
 
 
1463
        if not isinstance(self, format.__class__):
 
 
1464
            # converting away from metadir is not implemented
 
 
1465
            raise NotImplementedError(self.get_converter)
 
 
1466
        return ConvertMetaToMeta(format)
 
 
1468
    def get_format_string(self):
 
 
1469
        """See BzrDirFormat.get_format_string()."""
 
 
1470
        return "Bazaar-NG meta directory, format 1\n"
 
 
1472
    def get_format_description(self):
 
 
1473
        """See BzrDirFormat.get_format_description()."""
 
 
1474
        return "Meta directory format 1"
 
 
1476
    def _open(self, transport):
 
 
1477
        """See BzrDirFormat._open."""
 
 
1478
        return BzrDirMeta1(transport, self)
 
 
1480
    def __return_repository_format(self):
 
 
1481
        """Circular import protection."""
 
 
1482
        if getattr(self, '_repository_format', None):
 
 
1483
            return self._repository_format
 
 
1484
        from bzrlib.repository import RepositoryFormat
 
 
1485
        return RepositoryFormat.get_default_format()
 
 
1487
    def __set_repository_format(self, value):
 
 
1488
        """Allow changint the repository format for metadir formats."""
 
 
1489
        self._repository_format = value
 
 
1491
    repository_format = property(__return_repository_format, __set_repository_format)
 
 
1494
BzrDirFormat.register_format(BzrDirFormat4())
 
 
1495
BzrDirFormat.register_format(BzrDirFormat5())
 
 
1496
BzrDirFormat.register_format(BzrDirFormat6())
 
 
1497
__default_format = BzrDirMetaFormat1()
 
 
1498
BzrDirFormat.register_format(__default_format)
 
 
1499
BzrDirFormat._default_format = __default_format
 
 
1502
class BzrDirTestProviderAdapter(object):
 
 
1503
    """A tool to generate a suite testing multiple bzrdir formats at once.
 
 
1505
    This is done by copying the test once for each transport and injecting
 
 
1506
    the transport_server, transport_readonly_server, and bzrdir_format
 
 
1507
    classes into each copy. Each copy is also given a new id() to make it
 
 
1511
    def __init__(self, vfs_factory, transport_server, transport_readonly_server,
 
 
1513
        """Create an object to adapt tests.
 
 
1515
        :param vfs_server: A factory to create a Transport Server which has
 
 
1516
            all the VFS methods working, and is writable.
 
 
1518
        self._vfs_factory = vfs_factory
 
 
1519
        self._transport_server = transport_server
 
 
1520
        self._transport_readonly_server = transport_readonly_server
 
 
1521
        self._formats = formats
 
 
1523
    def adapt(self, test):
 
 
1524
        result = unittest.TestSuite()
 
 
1525
        for format in self._formats:
 
 
1526
            new_test = deepcopy(test)
 
 
1527
            new_test.vfs_transport_factory = self._vfs_factory
 
 
1528
            new_test.transport_server = self._transport_server
 
 
1529
            new_test.transport_readonly_server = self._transport_readonly_server
 
 
1530
            new_test.bzrdir_format = format
 
 
1531
            def make_new_test_id():
 
 
1532
                new_id = "%s(%s)" % (new_test.id(), format.__class__.__name__)
 
 
1533
                return lambda: new_id
 
 
1534
            new_test.id = make_new_test_id()
 
 
1535
            result.addTest(new_test)
 
 
1539
class Converter(object):
 
 
1540
    """Converts a disk format object from one format to another."""
 
 
1542
    def convert(self, to_convert, pb):
 
 
1543
        """Perform the conversion of to_convert, giving feedback via pb.
 
 
1545
        :param to_convert: The disk object to convert.
 
 
1546
        :param pb: a progress bar to use for progress information.
 
 
1549
    def step(self, message):
 
 
1550
        """Update the pb by a step."""
 
 
1552
        self.pb.update(message, self.count, self.total)
 
 
1555
class ConvertBzrDir4To5(Converter):
 
 
1556
    """Converts format 4 bzr dirs to format 5."""
 
 
1559
        super(ConvertBzrDir4To5, self).__init__()
 
 
1560
        self.converted_revs = set()
 
 
1561
        self.absent_revisions = set()
 
 
1565
    def convert(self, to_convert, pb):
 
 
1566
        """See Converter.convert()."""
 
 
1567
        self.bzrdir = to_convert
 
 
1569
        self.pb.note('starting upgrade from format 4 to 5')
 
 
1570
        if isinstance(self.bzrdir.transport, LocalTransport):
 
 
1571
            self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
 
 
1572
        self._convert_to_weaves()
 
 
1573
        return BzrDir.open(self.bzrdir.root_transport.base)
 
 
1575
    def _convert_to_weaves(self):
 
 
1576
        self.pb.note('note: upgrade may be faster if all store files are ungzipped first')
 
 
1579
            stat = self.bzrdir.transport.stat('weaves')
 
 
1580
            if not S_ISDIR(stat.st_mode):
 
 
1581
                self.bzrdir.transport.delete('weaves')
 
 
1582
                self.bzrdir.transport.mkdir('weaves')
 
 
1583
        except errors.NoSuchFile:
 
 
1584
            self.bzrdir.transport.mkdir('weaves')
 
 
1585
        # deliberately not a WeaveFile as we want to build it up slowly.
 
 
1586
        self.inv_weave = Weave('inventory')
 
 
1587
        # holds in-memory weaves for all files
 
 
1588
        self.text_weaves = {}
 
 
1589
        self.bzrdir.transport.delete('branch-format')
 
 
1590
        self.branch = self.bzrdir.open_branch()
 
 
1591
        self._convert_working_inv()
 
 
1592
        rev_history = self.branch.revision_history()
 
 
1593
        # to_read is a stack holding the revisions we still need to process;
 
 
1594
        # appending to it adds new highest-priority revisions
 
 
1595
        self.known_revisions = set(rev_history)
 
 
1596
        self.to_read = rev_history[-1:]
 
 
1598
            rev_id = self.to_read.pop()
 
 
1599
            if (rev_id not in self.revisions
 
 
1600
                and rev_id not in self.absent_revisions):
 
 
1601
                self._load_one_rev(rev_id)
 
 
1603
        to_import = self._make_order()
 
 
1604
        for i, rev_id in enumerate(to_import):
 
 
1605
            self.pb.update('converting revision', i, len(to_import))
 
 
1606
            self._convert_one_rev(rev_id)
 
 
1608
        self._write_all_weaves()
 
 
1609
        self._write_all_revs()
 
 
1610
        self.pb.note('upgraded to weaves:')
 
 
1611
        self.pb.note('  %6d revisions and inventories', len(self.revisions))
 
 
1612
        self.pb.note('  %6d revisions not present', len(self.absent_revisions))
 
 
1613
        self.pb.note('  %6d texts', self.text_count)
 
 
1614
        self._cleanup_spare_files_after_format4()
 
 
1615
        self.branch.control_files.put_utf8('branch-format', BzrDirFormat5().get_format_string())
 
 
1617
    def _cleanup_spare_files_after_format4(self):
 
 
1618
        # FIXME working tree upgrade foo.
 
 
1619
        for n in 'merged-patches', 'pending-merged-patches':
 
 
1621
                ## assert os.path.getsize(p) == 0
 
 
1622
                self.bzrdir.transport.delete(n)
 
 
1623
            except errors.NoSuchFile:
 
 
1625
        self.bzrdir.transport.delete_tree('inventory-store')
 
 
1626
        self.bzrdir.transport.delete_tree('text-store')
 
 
1628
    def _convert_working_inv(self):
 
 
1629
        inv = xml4.serializer_v4.read_inventory(
 
 
1630
                    self.branch.control_files.get('inventory'))
 
 
1631
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
 
 
1632
        # FIXME inventory is a working tree change.
 
 
1633
        self.branch.control_files.put('inventory', StringIO(new_inv_xml))
 
 
1635
    def _write_all_weaves(self):
 
 
1636
        controlweaves = WeaveStore(self.bzrdir.transport, prefixed=False)
 
 
1637
        weave_transport = self.bzrdir.transport.clone('weaves')
 
 
1638
        weaves = WeaveStore(weave_transport, prefixed=False)
 
 
1639
        transaction = WriteTransaction()
 
 
1643
            for file_id, file_weave in self.text_weaves.items():
 
 
1644
                self.pb.update('writing weave', i, len(self.text_weaves))
 
 
1645
                weaves._put_weave(file_id, file_weave, transaction)
 
 
1647
            self.pb.update('inventory', 0, 1)
 
 
1648
            controlweaves._put_weave('inventory', self.inv_weave, transaction)
 
 
1649
            self.pb.update('inventory', 1, 1)
 
 
1653
    def _write_all_revs(self):
 
 
1654
        """Write all revisions out in new form."""
 
 
1655
        self.bzrdir.transport.delete_tree('revision-store')
 
 
1656
        self.bzrdir.transport.mkdir('revision-store')
 
 
1657
        revision_transport = self.bzrdir.transport.clone('revision-store')
 
 
1659
        _revision_store = TextRevisionStore(TextStore(revision_transport,
 
 
1663
            transaction = WriteTransaction()
 
 
1664
            for i, rev_id in enumerate(self.converted_revs):
 
 
1665
                self.pb.update('write revision', i, len(self.converted_revs))
 
 
1666
                _revision_store.add_revision(self.revisions[rev_id], transaction)
 
 
1670
    def _load_one_rev(self, rev_id):
 
 
1671
        """Load a revision object into memory.
 
 
1673
        Any parents not either loaded or abandoned get queued to be
 
 
1675
        self.pb.update('loading revision',
 
 
1676
                       len(self.revisions),
 
 
1677
                       len(self.known_revisions))
 
 
1678
        if not self.branch.repository.has_revision(rev_id):
 
 
1680
            self.pb.note('revision {%s} not present in branch; '
 
 
1681
                         'will be converted as a ghost',
 
 
1683
            self.absent_revisions.add(rev_id)
 
 
1685
            rev = self.branch.repository._revision_store.get_revision(rev_id,
 
 
1686
                self.branch.repository.get_transaction())
 
 
1687
            for parent_id in rev.parent_ids:
 
 
1688
                self.known_revisions.add(parent_id)
 
 
1689
                self.to_read.append(parent_id)
 
 
1690
            self.revisions[rev_id] = rev
 
 
1692
    def _load_old_inventory(self, rev_id):
 
 
1693
        assert rev_id not in self.converted_revs
 
 
1694
        old_inv_xml = self.branch.repository.inventory_store.get(rev_id).read()
 
 
1695
        inv = xml4.serializer_v4.read_inventory_from_string(old_inv_xml)
 
 
1696
        inv.revision_id = rev_id
 
 
1697
        rev = self.revisions[rev_id]
 
 
1698
        if rev.inventory_sha1:
 
 
1699
            assert rev.inventory_sha1 == sha_string(old_inv_xml), \
 
 
1700
                'inventory sha mismatch for {%s}' % rev_id
 
 
1703
    def _load_updated_inventory(self, rev_id):
 
 
1704
        assert rev_id in self.converted_revs
 
 
1705
        inv_xml = self.inv_weave.get_text(rev_id)
 
 
1706
        inv = xml5.serializer_v5.read_inventory_from_string(inv_xml)
 
 
1709
    def _convert_one_rev(self, rev_id):
 
 
1710
        """Convert revision and all referenced objects to new format."""
 
 
1711
        rev = self.revisions[rev_id]
 
 
1712
        inv = self._load_old_inventory(rev_id)
 
 
1713
        present_parents = [p for p in rev.parent_ids
 
 
1714
                           if p not in self.absent_revisions]
 
 
1715
        self._convert_revision_contents(rev, inv, present_parents)
 
 
1716
        self._store_new_weave(rev, inv, present_parents)
 
 
1717
        self.converted_revs.add(rev_id)
 
 
1719
    def _store_new_weave(self, rev, inv, present_parents):
 
 
1720
        # the XML is now updated with text versions
 
 
1722
            entries = inv.iter_entries()
 
 
1724
            for path, ie in entries:
 
 
1725
                assert getattr(ie, 'revision', None) is not None, \
 
 
1726
                    'no revision on {%s} in {%s}' % \
 
 
1727
                    (file_id, rev.revision_id)
 
 
1728
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
 
 
1729
        new_inv_sha1 = sha_string(new_inv_xml)
 
 
1730
        self.inv_weave.add_lines(rev.revision_id, 
 
 
1732
                                 new_inv_xml.splitlines(True))
 
 
1733
        rev.inventory_sha1 = new_inv_sha1
 
 
1735
    def _convert_revision_contents(self, rev, inv, present_parents):
 
 
1736
        """Convert all the files within a revision.
 
 
1738
        Also upgrade the inventory to refer to the text revision ids."""
 
 
1739
        rev_id = rev.revision_id
 
 
1740
        mutter('converting texts of revision {%s}',
 
 
1742
        parent_invs = map(self._load_updated_inventory, present_parents)
 
 
1743
        entries = inv.iter_entries()
 
 
1745
        for path, ie in entries:
 
 
1746
            self._convert_file_version(rev, ie, parent_invs)
 
 
1748
    def _convert_file_version(self, rev, ie, parent_invs):
 
 
1749
        """Convert one version of one file.
 
 
1751
        The file needs to be added into the weave if it is a merge
 
 
1752
        of >=2 parents or if it's changed from its parent.
 
 
1754
        file_id = ie.file_id
 
 
1755
        rev_id = rev.revision_id
 
 
1756
        w = self.text_weaves.get(file_id)
 
 
1759
            self.text_weaves[file_id] = w
 
 
1760
        text_changed = False
 
 
1761
        previous_entries = ie.find_previous_heads(parent_invs,
 
 
1765
        for old_revision in previous_entries:
 
 
1766
                # if this fails, its a ghost ?
 
 
1767
                assert old_revision in self.converted_revs, \
 
 
1768
                    "Revision {%s} not in converted_revs" % old_revision
 
 
1769
        self.snapshot_ie(previous_entries, ie, w, rev_id)
 
 
1771
        assert getattr(ie, 'revision', None) is not None
 
 
1773
    def snapshot_ie(self, previous_revisions, ie, w, rev_id):
 
 
1774
        # TODO: convert this logic, which is ~= snapshot to
 
 
1775
        # a call to:. This needs the path figured out. rather than a work_tree
 
 
1776
        # a v4 revision_tree can be given, or something that looks enough like
 
 
1777
        # one to give the file content to the entry if it needs it.
 
 
1778
        # and we need something that looks like a weave store for snapshot to 
 
 
1780
        #ie.snapshot(rev, PATH, previous_revisions, REVISION_TREE, InMemoryWeaveStore(self.text_weaves))
 
 
1781
        if len(previous_revisions) == 1:
 
 
1782
            previous_ie = previous_revisions.values()[0]
 
 
1783
            if ie._unchanged(previous_ie):
 
 
1784
                ie.revision = previous_ie.revision
 
 
1787
            text = self.branch.repository.text_store.get(ie.text_id)
 
 
1788
            file_lines = text.readlines()
 
 
1789
            assert sha_strings(file_lines) == ie.text_sha1
 
 
1790
            assert sum(map(len, file_lines)) == ie.text_size
 
 
1791
            w.add_lines(rev_id, previous_revisions, file_lines)
 
 
1792
            self.text_count += 1
 
 
1794
            w.add_lines(rev_id, previous_revisions, [])
 
 
1795
        ie.revision = rev_id
 
 
1797
    def _make_order(self):
 
 
1798
        """Return a suitable order for importing revisions.
 
 
1800
        The order must be such that an revision is imported after all
 
 
1801
        its (present) parents.
 
 
1803
        todo = set(self.revisions.keys())
 
 
1804
        done = self.absent_revisions.copy()
 
 
1807
            # scan through looking for a revision whose parents
 
 
1809
            for rev_id in sorted(list(todo)):
 
 
1810
                rev = self.revisions[rev_id]
 
 
1811
                parent_ids = set(rev.parent_ids)
 
 
1812
                if parent_ids.issubset(done):
 
 
1813
                    # can take this one now
 
 
1814
                    order.append(rev_id)
 
 
1820
class ConvertBzrDir5To6(Converter):
 
 
1821
    """Converts format 5 bzr dirs to format 6."""
 
 
1823
    def convert(self, to_convert, pb):
 
 
1824
        """See Converter.convert()."""
 
 
1825
        self.bzrdir = to_convert
 
 
1827
        self.pb.note('starting upgrade from format 5 to 6')
 
 
1828
        self._convert_to_prefixed()
 
 
1829
        return BzrDir.open(self.bzrdir.root_transport.base)
 
 
1831
    def _convert_to_prefixed(self):
 
 
1832
        from bzrlib.store import TransportStore
 
 
1833
        self.bzrdir.transport.delete('branch-format')
 
 
1834
        for store_name in ["weaves", "revision-store"]:
 
 
1835
            self.pb.note("adding prefixes to %s" % store_name)
 
 
1836
            store_transport = self.bzrdir.transport.clone(store_name)
 
 
1837
            store = TransportStore(store_transport, prefixed=True)
 
 
1838
            for urlfilename in store_transport.list_dir('.'):
 
 
1839
                filename = urlutils.unescape(urlfilename)
 
 
1840
                if (filename.endswith(".weave") or
 
 
1841
                    filename.endswith(".gz") or
 
 
1842
                    filename.endswith(".sig")):
 
 
1843
                    file_id = os.path.splitext(filename)[0]
 
 
1846
                prefix_dir = store.hash_prefix(file_id)
 
 
1847
                # FIXME keep track of the dirs made RBC 20060121
 
 
1849
                    store_transport.move(filename, prefix_dir + '/' + filename)
 
 
1850
                except errors.NoSuchFile: # catches missing dirs strangely enough
 
 
1851
                    store_transport.mkdir(prefix_dir)
 
 
1852
                    store_transport.move(filename, prefix_dir + '/' + filename)
 
 
1853
        self.bzrdir._control_files.put_utf8('branch-format', BzrDirFormat6().get_format_string())
 
 
1856
class ConvertBzrDir6ToMeta(Converter):
 
 
1857
    """Converts format 6 bzr dirs to metadirs."""
 
 
1859
    def convert(self, to_convert, pb):
 
 
1860
        """See Converter.convert()."""
 
 
1861
        from bzrlib.branch import BzrBranchFormat5
 
 
1862
        self.bzrdir = to_convert
 
 
1865
        self.total = 20 # the steps we know about
 
 
1866
        self.garbage_inventories = []
 
 
1868
        self.pb.note('starting upgrade from format 6 to metadir')
 
 
1869
        self.bzrdir._control_files.put_utf8('branch-format', "Converting to format 6")
 
 
1870
        # its faster to move specific files around than to open and use the apis...
 
 
1871
        # first off, nuke ancestry.weave, it was never used.
 
 
1873
            self.step('Removing ancestry.weave')
 
 
1874
            self.bzrdir.transport.delete('ancestry.weave')
 
 
1875
        except errors.NoSuchFile:
 
 
1877
        # find out whats there
 
 
1878
        self.step('Finding branch files')
 
 
1879
        last_revision = self.bzrdir.open_branch().last_revision()
 
 
1880
        bzrcontents = self.bzrdir.transport.list_dir('.')
 
 
1881
        for name in bzrcontents:
 
 
1882
            if name.startswith('basis-inventory.'):
 
 
1883
                self.garbage_inventories.append(name)
 
 
1884
        # create new directories for repository, working tree and branch
 
 
1885
        self.dir_mode = self.bzrdir._control_files._dir_mode
 
 
1886
        self.file_mode = self.bzrdir._control_files._file_mode
 
 
1887
        repository_names = [('inventory.weave', True),
 
 
1888
                            ('revision-store', True),
 
 
1890
        self.step('Upgrading repository  ')
 
 
1891
        self.bzrdir.transport.mkdir('repository', mode=self.dir_mode)
 
 
1892
        self.make_lock('repository')
 
 
1893
        # we hard code the formats here because we are converting into
 
 
1894
        # the meta format. The meta format upgrader can take this to a 
 
 
1895
        # future format within each component.
 
 
1896
        self.put_format('repository', _mod_repository.RepositoryFormat7())
 
 
1897
        for entry in repository_names:
 
 
1898
            self.move_entry('repository', entry)
 
 
1900
        self.step('Upgrading branch      ')
 
 
1901
        self.bzrdir.transport.mkdir('branch', mode=self.dir_mode)
 
 
1902
        self.make_lock('branch')
 
 
1903
        self.put_format('branch', BzrBranchFormat5())
 
 
1904
        branch_files = [('revision-history', True),
 
 
1905
                        ('branch-name', True),
 
 
1907
        for entry in branch_files:
 
 
1908
            self.move_entry('branch', entry)
 
 
1910
        checkout_files = [('pending-merges', True),
 
 
1911
                          ('inventory', True),
 
 
1912
                          ('stat-cache', False)]
 
 
1913
        # If a mandatory checkout file is not present, the branch does not have
 
 
1914
        # a functional checkout. Do not create a checkout in the converted
 
 
1916
        for name, mandatory in checkout_files:
 
 
1917
            if mandatory and name not in bzrcontents:
 
 
1918
                has_checkout = False
 
 
1922
        if not has_checkout:
 
 
1923
            self.pb.note('No working tree.')
 
 
1924
            # If some checkout files are there, we may as well get rid of them.
 
 
1925
            for name, mandatory in checkout_files:
 
 
1926
                if name in bzrcontents:
 
 
1927
                    self.bzrdir.transport.delete(name)
 
 
1929
            from bzrlib.workingtree import WorkingTreeFormat3
 
 
1930
            self.step('Upgrading working tree')
 
 
1931
            self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
 
 
1932
            self.make_lock('checkout')
 
 
1934
                'checkout', WorkingTreeFormat3())
 
 
1935
            self.bzrdir.transport.delete_multi(
 
 
1936
                self.garbage_inventories, self.pb)
 
 
1937
            for entry in checkout_files:
 
 
1938
                self.move_entry('checkout', entry)
 
 
1939
            if last_revision is not None:
 
 
1940
                self.bzrdir._control_files.put_utf8(
 
 
1941
                    'checkout/last-revision', last_revision)
 
 
1942
        self.bzrdir._control_files.put_utf8(
 
 
1943
            'branch-format', BzrDirMetaFormat1().get_format_string())
 
 
1944
        return BzrDir.open(self.bzrdir.root_transport.base)
 
 
1946
    def make_lock(self, name):
 
 
1947
        """Make a lock for the new control dir name."""
 
 
1948
        self.step('Make %s lock' % name)
 
 
1949
        ld = lockdir.LockDir(self.bzrdir.transport,
 
 
1951
                             file_modebits=self.file_mode,
 
 
1952
                             dir_modebits=self.dir_mode)
 
 
1955
    def move_entry(self, new_dir, entry):
 
 
1956
        """Move then entry name into new_dir."""
 
 
1958
        mandatory = entry[1]
 
 
1959
        self.step('Moving %s' % name)
 
 
1961
            self.bzrdir.transport.move(name, '%s/%s' % (new_dir, name))
 
 
1962
        except errors.NoSuchFile:
 
 
1966
    def put_format(self, dirname, format):
 
 
1967
        self.bzrdir._control_files.put_utf8('%s/format' % dirname, format.get_format_string())
 
 
1970
class ConvertMetaToMeta(Converter):
 
 
1971
    """Converts the components of metadirs."""
 
 
1973
    def __init__(self, target_format):
 
 
1974
        """Create a metadir to metadir converter.
 
 
1976
        :param target_format: The final metadir format that is desired.
 
 
1978
        self.target_format = target_format
 
 
1980
    def convert(self, to_convert, pb):
 
 
1981
        """See Converter.convert()."""
 
 
1982
        self.bzrdir = to_convert
 
 
1986
        self.step('checking repository format')
 
 
1988
            repo = self.bzrdir.open_repository()
 
 
1989
        except errors.NoRepositoryPresent:
 
 
1992
            if not isinstance(repo._format, self.target_format.repository_format.__class__):
 
 
1993
                from bzrlib.repository import CopyConverter
 
 
1994
                self.pb.note('starting repository conversion')
 
 
1995
                converter = CopyConverter(self.target_format.repository_format)
 
 
1996
                converter.convert(repo, pb)
 
 
2000
# This is not in remote.py because it's small, and needs to be registered.
 
 
2001
# Putting it in remote.py creates a circular import problem.
 
 
2002
# we can make it a lazy object if the control formats is turned into something
 
 
2004
class RemoteBzrDirFormat(BzrDirMetaFormat1):
 
 
2005
    """Format representing bzrdirs accessed via a smart server"""
 
 
2007
    def get_format_description(self):
 
 
2008
        return 'bzr remote bzrdir'
 
 
2011
    def probe_transport(klass, transport):
 
 
2012
        """Return a RemoteBzrDirFormat object if it looks possible."""
 
 
2014
            transport.get_smart_client()
 
 
2015
        except (NotImplementedError, AttributeError,
 
 
2016
                errors.TransportNotPossible):
 
 
2017
            # no smart server, so not a branch for this format type.
 
 
2018
            raise errors.NotBranchError(path=transport.base)
 
 
2022
    def initialize_on_transport(self, transport):
 
 
2023
        # hand off the request to the smart server
 
 
2024
        medium = transport.get_smart_medium()
 
 
2025
        client = SmartClient(medium)
 
 
2026
        path = client.remote_path_from_transport(transport)
 
 
2027
        response = SmartClient(medium).call('BzrDirFormat.initialize', path)
 
 
2028
        assert response[0] in ('ok', ), 'unexpected response code %s' % (response,)
 
 
2029
        return remote.RemoteBzrDir(transport)
 
 
2031
    def _open(self, transport):
 
 
2032
        return remote.RemoteBzrDir(transport)
 
 
2034
    def __eq__(self, other):
 
 
2035
        if not isinstance(other, RemoteBzrDirFormat):
 
 
2037
        return self.get_format_description() == other.get_format_description()
 
 
2040
# We can't use register_control_format because it adds it at a lower priority
 
 
2041
# than the existing branches, whereas this should take priority.
 
 
2042
BzrDirFormat._control_formats.insert(0, RemoteBzrDirFormat)
 
 
2045
class BzrDirFormatInfo(object):
 
 
2047
    def __init__(self, native, deprecated):
 
 
2048
        self.deprecated = deprecated
 
 
2049
        self.native = native
 
 
2052
class BzrDirFormatRegistry(registry.Registry):
 
 
2053
    """Registry of user-selectable BzrDir subformats.
 
 
2055
    Differs from BzrDirFormat._control_formats in that it provides sub-formats,
 
 
2056
    e.g. BzrDirMeta1 with weave repository.  Also, it's more user-oriented.
 
 
2059
    def register_metadir(self, key, repo, help, native=True, deprecated=False):
 
 
2060
        """Register a metadir subformat.
 
 
2062
        repo is the repository format name as a string.
 
 
2064
        # This should be expanded to support setting WorkingTree and Branch
 
 
2065
        # formats, once BzrDirMetaFormat1 supports that.
 
 
2067
            import bzrlib.repository
 
 
2068
            repo_format = getattr(bzrlib.repository, repo)
 
 
2069
            bd = BzrDirMetaFormat1()
 
 
2070
            bd.repository_format = repo_format()
 
 
2072
        self.register(key, helper, help, native, deprecated)
 
 
2074
    def register(self, key, factory, help, native=True, deprecated=False):
 
 
2075
        """Register a BzrDirFormat factory.
 
 
2077
        The factory must be a callable that takes one parameter: the key.
 
 
2078
        It must produce an instance of the BzrDirFormat when called.
 
 
2080
        This function mainly exists to prevent the info object from being
 
 
2083
        registry.Registry.register(self, key, factory, help, 
 
 
2084
            BzrDirFormatInfo(native, deprecated))
 
 
2086
    def register_lazy(self, key, module_name, member_name, help, native=True,
 
 
2088
        registry.Registry.register_lazy(self, key, module_name, member_name, 
 
 
2089
            help, BzrDirFormatInfo(native, deprecated))
 
 
2091
    def set_default(self, key):
 
 
2092
        """Set the 'default' key to be a clone of the supplied key.
 
 
2094
        This method must be called once and only once.
 
 
2096
        registry.Registry.register(self, 'default', self.get(key), 
 
 
2097
            self.get_help(key), info=self.get_info(key))
 
 
2099
    def set_default_repository(self, key):
 
 
2100
        """Set the FormatRegistry default and Repository default.
 
 
2102
        This is a transitional method while Repository.set_default_format
 
 
2105
        if 'default' in self:
 
 
2106
            self.remove('default')
 
 
2107
        self.set_default(key)
 
 
2108
        format = self.get('default')()
 
 
2109
        assert isinstance(format, BzrDirMetaFormat1)
 
 
2111
    def make_bzrdir(self, key):
 
 
2112
        return self.get(key)()
 
 
2114
    def help_topic(self, topic):
 
 
2115
        output = textwrap.dedent("""\
 
 
2116
            Bazaar directory formats
 
 
2117
            ------------------------
 
 
2119
            These formats can be used for creating branches, working trees, and
 
 
2123
        default_help = self.get_help('default')
 
 
2125
        for key in self.keys():
 
 
2126
            if key == 'default':
 
 
2128
            help = self.get_help(key)
 
 
2129
            if help == default_help:
 
 
2130
                default_realkey = key
 
 
2132
                help_pairs.append((key, help))
 
 
2134
        def wrapped(key, help, info):
 
 
2136
                help = '(native) ' + help
 
 
2137
            return '  %s:\n%s\n\n' % (key, 
 
 
2138
                    textwrap.fill(help, initial_indent='    ', 
 
 
2139
                    subsequent_indent='    '))
 
 
2140
        output += wrapped('%s/default' % default_realkey, default_help,
 
 
2141
                          self.get_info('default'))
 
 
2142
        deprecated_pairs = []
 
 
2143
        for key, help in help_pairs:
 
 
2144
            info = self.get_info(key)
 
 
2146
                deprecated_pairs.append((key, help))
 
 
2148
                output += wrapped(key, help, info)
 
 
2149
        if len(deprecated_pairs) > 0:
 
 
2150
            output += "Deprecated formats\n------------------\n\n"
 
 
2151
            for key, help in deprecated_pairs:
 
 
2152
                info = self.get_info(key)
 
 
2153
                output += wrapped(key, help, info)
 
 
2158
format_registry = BzrDirFormatRegistry()
 
 
2159
format_registry.register('weave', BzrDirFormat6,
 
 
2160
    'Pre-0.8 format.  Slower than knit and does not'
 
 
2161
    ' support checkouts or shared repositories.', deprecated=True)
 
 
2162
format_registry.register_metadir('knit', 'RepositoryFormatKnit1',
 
 
2163
    'Format using knits.  Recommended.')
 
 
2164
format_registry.set_default('knit')
 
 
2165
format_registry.register_metadir('metaweave', 'RepositoryFormat7',
 
 
2166
    'Transitional format in 0.8.  Slower than knit.',
 
 
2168
format_registry.register_metadir('experimental-knit2', 'RepositoryFormatKnit2',
 
 
2169
    'Experimental successor to knit.  Use at your own risk.')