~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

Merge pt1 hooks branch.

Show diffs side-by-side

added added

removed removed

Lines of Context:
25
25
objects returned.
26
26
"""
27
27
 
 
28
# TODO: Move old formats into a plugin to make this file smaller.
 
29
 
 
30
import os
28
31
import sys
 
32
import warnings
29
33
 
30
34
from bzrlib.lazy_import import lazy_import
31
35
lazy_import(globals(), """
 
36
from stat import S_ISDIR
 
37
 
32
38
import bzrlib
33
39
from bzrlib import (
34
 
    branch as _mod_branch,
35
 
    cleanup,
 
40
    branch,
 
41
    config,
 
42
    controldir,
36
43
    errors,
37
 
    fetch,
38
44
    graph,
39
45
    lockable_files,
40
46
    lockdir,
46
52
    transport as _mod_transport,
47
53
    ui,
48
54
    urlutils,
 
55
    versionedfile,
49
56
    win32utils,
50
 
    workingtree_3,
 
57
    workingtree,
51
58
    workingtree_4,
52
 
    )
53
 
from bzrlib.repofmt import knitpack_repo
 
59
    xml4,
 
60
    xml5,
 
61
    )
 
62
from bzrlib.osutils import (
 
63
    sha_string,
 
64
    )
 
65
from bzrlib.push import (
 
66
    PushResult,
 
67
    )
 
68
from bzrlib.repofmt import pack_repo
 
69
from bzrlib.smart.client import _SmartClient
 
70
from bzrlib.store.versioned import VersionedFileStore
 
71
from bzrlib.transactions import WriteTransaction
54
72
from bzrlib.transport import (
55
73
    do_catching_redirections,
56
74
    local,
57
75
    )
58
 
from bzrlib.i18n import gettext
 
76
from bzrlib.weave import (
 
77
    WeaveFile,
 
78
    Weave,
 
79
    )
59
80
""")
60
81
 
61
82
from bzrlib.trace import (
62
83
    mutter,
63
84
    note,
 
85
    warning,
64
86
    )
65
87
 
66
88
from bzrlib import (
67
 
    config,
68
 
    controldir,
69
89
    hooks,
70
90
    registry,
 
91
    symbol_versioning,
71
92
    )
72
93
from bzrlib.symbol_versioning import (
73
94
    deprecated_in,
124
145
            # No repo, no problem.
125
146
            pass
126
147
 
 
148
    @staticmethod
 
149
    def _check_supported(format, allow_unsupported,
 
150
        recommend_upgrade=True,
 
151
        basedir=None):
 
152
        """Give an error or warning on old formats.
 
153
 
 
154
        :param format: may be any kind of format - workingtree, branch,
 
155
        or repository.
 
156
 
 
157
        :param allow_unsupported: If true, allow opening
 
158
        formats that are strongly deprecated, and which may
 
159
        have limited functionality.
 
160
 
 
161
        :param recommend_upgrade: If true (default), warn
 
162
        the user through the ui object that they may wish
 
163
        to upgrade the object.
 
164
        """
 
165
        # TODO: perhaps move this into a base Format class; it's not BzrDir
 
166
        # specific. mbp 20070323
 
167
        if not allow_unsupported and not format.is_supported():
 
168
            # see open_downlevel to open legacy branches.
 
169
            raise errors.UnsupportedFormatError(format=format)
 
170
        if recommend_upgrade \
 
171
            and getattr(format, 'upgrade_recommended', False):
 
172
            ui.ui_factory.recommend_upgrade(
 
173
                format.get_format_description(),
 
174
                basedir)
 
175
 
127
176
    def clone_on_transport(self, transport, revision_id=None,
128
177
        force_new_repo=False, preserve_stacking=False, stacked_on=None,
129
178
        create_prefix=False, use_existing_dir=True, no_tree=False):
240
289
        This is intended primarily as a building block for more sophisticated
241
290
        functionality, like finding trees under a directory, or finding
242
291
        branches that use a given repository.
243
 
 
244
292
        :param evaluate: An optional callable that yields recurse, value,
245
293
            where recurse controls whether this bzrdir is recursed into
246
294
            and value is the value to yield.  By default, all bzrdirs
390
438
        policy = self.determine_repository_policy(force_new_repo)
391
439
        return policy.acquire_repository()[0]
392
440
 
393
 
    def _find_source_repo(self, add_cleanup, source_branch):
394
 
        """Find the source branch and repo for a sprout operation.
395
 
        
396
 
        This is helper intended for use by _sprout.
397
 
 
398
 
        :returns: (source_branch, source_repository).  Either or both may be
399
 
            None.  If not None, they will be read-locked (and their unlock(s)
400
 
            scheduled via the add_cleanup param).
401
 
        """
402
 
        if source_branch is not None:
403
 
            add_cleanup(source_branch.lock_read().unlock)
404
 
            return source_branch, source_branch.repository
405
 
        try:
406
 
            source_branch = self.open_branch()
407
 
            source_repository = source_branch.repository
408
 
        except errors.NotBranchError:
409
 
            source_branch = None
410
 
            try:
411
 
                source_repository = self.open_repository()
412
 
            except errors.NoRepositoryPresent:
413
 
                source_repository = None
414
 
            else:
415
 
                add_cleanup(source_repository.lock_read().unlock)
416
 
        else:
417
 
            add_cleanup(source_branch.lock_read().unlock)
418
 
        return source_branch, source_repository
419
 
 
420
 
    def sprout(self, url, revision_id=None, force_new_repo=False,
421
 
               recurse='down', possible_transports=None,
422
 
               accelerator_tree=None, hardlink=False, stacked=False,
423
 
               source_branch=None, create_tree_if_local=True):
424
 
        """Create a copy of this controldir prepared for use as a new line of
425
 
        development.
426
 
 
427
 
        If url's last component does not exist, it will be created.
428
 
 
429
 
        Attributes related to the identity of the source branch like
430
 
        branch nickname will be cleaned, a working tree is created
431
 
        whether one existed before or not; and a local branch is always
432
 
        created.
433
 
 
434
 
        if revision_id is not None, then the clone operation may tune
435
 
            itself to download less data.
436
 
 
437
 
        :param accelerator_tree: A tree which can be used for retrieving file
438
 
            contents more quickly than the revision tree, i.e. a workingtree.
439
 
            The revision tree will be used for cases where accelerator_tree's
440
 
            content is different.
441
 
        :param hardlink: If true, hard-link files from accelerator_tree,
442
 
            where possible.
443
 
        :param stacked: If true, create a stacked branch referring to the
444
 
            location of this control directory.
445
 
        :param create_tree_if_local: If true, a working-tree will be created
446
 
            when working locally.
447
 
        """
448
 
        operation = cleanup.OperationWithCleanups(self._sprout)
449
 
        return operation.run(url, revision_id=revision_id,
450
 
            force_new_repo=force_new_repo, recurse=recurse,
451
 
            possible_transports=possible_transports,
452
 
            accelerator_tree=accelerator_tree, hardlink=hardlink,
453
 
            stacked=stacked, source_branch=source_branch,
454
 
            create_tree_if_local=create_tree_if_local)
455
 
 
456
 
    def _sprout(self, op, url, revision_id=None, force_new_repo=False,
457
 
               recurse='down', possible_transports=None,
458
 
               accelerator_tree=None, hardlink=False, stacked=False,
459
 
               source_branch=None, create_tree_if_local=True):
460
 
        add_cleanup = op.add_cleanup
461
 
        fetch_spec_factory = fetch.FetchSpecFactory()
462
 
        if revision_id is not None:
463
 
            fetch_spec_factory.add_revision_ids([revision_id])
464
 
            fetch_spec_factory.source_branch_stop_revision_id = revision_id
465
 
        target_transport = _mod_transport.get_transport(url,
466
 
            possible_transports)
467
 
        target_transport.ensure_base()
468
 
        cloning_format = self.cloning_metadir(stacked)
469
 
        # Create/update the result branch
470
 
        result = cloning_format.initialize_on_transport(target_transport)
471
 
        source_branch, source_repository = self._find_source_repo(
472
 
            add_cleanup, source_branch)
473
 
        fetch_spec_factory.source_branch = source_branch
474
 
        # if a stacked branch wasn't requested, we don't create one
475
 
        # even if the origin was stacked
476
 
        if stacked and source_branch is not None:
477
 
            stacked_branch_url = self.root_transport.base
478
 
        else:
479
 
            stacked_branch_url = None
480
 
        repository_policy = result.determine_repository_policy(
481
 
            force_new_repo, stacked_branch_url, require_stacking=stacked)
482
 
        result_repo, is_new_repo = repository_policy.acquire_repository()
483
 
        add_cleanup(result_repo.lock_write().unlock)
484
 
        fetch_spec_factory.source_repo = source_repository
485
 
        fetch_spec_factory.target_repo = result_repo
486
 
        if stacked or (len(result_repo._fallback_repositories) != 0):
487
 
            target_repo_kind = fetch.TargetRepoKinds.STACKED
488
 
        elif is_new_repo:
489
 
            target_repo_kind = fetch.TargetRepoKinds.EMPTY
490
 
        else:
491
 
            target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
492
 
        fetch_spec_factory.target_repo_kind = target_repo_kind
493
 
        if source_repository is not None:
494
 
            fetch_spec = fetch_spec_factory.make_fetch_spec()
495
 
            result_repo.fetch(source_repository, fetch_spec=fetch_spec)
496
 
 
497
 
        if source_branch is None:
498
 
            # this is for sprouting a controldir without a branch; is that
499
 
            # actually useful?
500
 
            # Not especially, but it's part of the contract.
501
 
            result_branch = result.create_branch()
502
 
        else:
503
 
            result_branch = source_branch.sprout(result,
504
 
                revision_id=revision_id, repository_policy=repository_policy,
505
 
                repository=result_repo)
506
 
        mutter("created new branch %r" % (result_branch,))
507
 
 
508
 
        # Create/update the result working tree
509
 
        if (create_tree_if_local and
510
 
            isinstance(target_transport, local.LocalTransport) and
511
 
            (result_repo is None or result_repo.make_working_trees())):
512
 
            wt = result.create_workingtree(accelerator_tree=accelerator_tree,
513
 
                hardlink=hardlink, from_branch=result_branch)
514
 
            wt.lock_write()
515
 
            try:
516
 
                if wt.path2id('') is None:
517
 
                    try:
518
 
                        wt.set_root_id(self.open_workingtree.get_root_id())
519
 
                    except errors.NoWorkingTree:
520
 
                        pass
521
 
            finally:
522
 
                wt.unlock()
523
 
        else:
524
 
            wt = None
525
 
        if recurse == 'down':
526
 
            basis = None
527
 
            if wt is not None:
528
 
                basis = wt.basis_tree()
529
 
            elif result_branch is not None:
530
 
                basis = result_branch.basis_tree()
531
 
            elif source_branch is not None:
532
 
                basis = source_branch.basis_tree()
533
 
            if basis is not None:
534
 
                add_cleanup(basis.lock_read().unlock)
535
 
                subtrees = basis.iter_references()
536
 
            else:
537
 
                subtrees = []
538
 
            for path, file_id in subtrees:
539
 
                target = urlutils.join(url, urlutils.escape(path))
540
 
                sublocation = source_branch.reference_parent(file_id, path)
541
 
                sublocation.bzrdir.sprout(target,
542
 
                    basis.get_reference_revision(file_id, path),
543
 
                    force_new_repo=force_new_repo, recurse=recurse,
544
 
                    stacked=stacked)
545
 
        return result
546
 
 
547
441
    @staticmethod
548
442
    def create_branch_convenience(base, force_new_repo=False,
549
443
                                  force_new_tree=None, format=None,
633
527
            old_path = self.root_transport.abspath('.bzr')
634
528
            backup_dir = self._available_backup_name('backup.bzr')
635
529
            new_path = self.root_transport.abspath(backup_dir)
636
 
            ui.ui_factory.note(gettext('making backup of {0}\n  to {1}').format(
637
 
                urlutils.unescape_for_display(old_path, 'utf-8'),
638
 
                urlutils.unescape_for_display(new_path, 'utf-8')))
 
530
            ui.ui_factory.note('making backup of %s\n  to %s'
 
531
                               % (old_path, new_path,))
639
532
            self.root_transport.copy_tree('.bzr', backup_dir)
640
533
            return (old_path, new_path)
641
534
        finally:
656
549
            try:
657
550
                to_path = '.bzr.retired.%d' % i
658
551
                self.root_transport.rename('.bzr', to_path)
659
 
                note(gettext("renamed {0} to {1}").format(
660
 
                    self.root_transport.abspath('.bzr'), to_path))
 
552
                note("renamed %s to %s"
 
553
                    % (self.root_transport.abspath('.bzr'), to_path))
661
554
                return
662
555
            except (errors.TransportError, IOError, errors.PathError):
663
556
                i += 1
848
741
            redirected_transport = transport._redirected_to(e.source, e.target)
849
742
            if redirected_transport is None:
850
743
                raise errors.NotBranchError(base)
851
 
            note(gettext('{0} is{1} redirected to {2}').format(
852
 
                 transport.base, e.permanently, redirected_transport.base))
 
744
            note('%s is%s redirected to %s',
 
745
                 transport.base, e.permanently, redirected_transport.base)
853
746
            return redirected_transport
854
747
 
855
748
        try:
859
752
        except errors.TooManyRedirections:
860
753
            raise errors.NotBranchError(base)
861
754
 
862
 
        format.check_support_status(_unsupported)
 
755
        BzrDir._check_supported(format, _unsupported)
863
756
        return format.open(transport, _found=True)
864
757
 
865
758
    @staticmethod
867
760
        """Open an existing branch which contains url.
868
761
 
869
762
        :param url: url to search from.
870
 
 
871
763
        See open_containing_from_transport for more detail.
872
764
        """
873
765
        transport = _mod_transport.get_transport(url, possible_transports)
1038
930
            format = controldir.ControlDirFormat.get_default_format()
1039
931
        return format.initialize_on_transport(t)
1040
932
 
1041
 
    def get_branch_transport(self, branch_format, name=None):
1042
 
        """Get the transport for use by branch format in this BzrDir.
1043
 
 
1044
 
        Note that bzr dirs that do not support format strings will raise
1045
 
        IncompatibleFormat if the branch format they are given has
1046
 
        a format string, and vice versa.
1047
 
 
1048
 
        If branch_format is None, the transport is returned with no
1049
 
        checking. If it is not None, then the returned transport is
1050
 
        guaranteed to point to an existing directory ready for use.
1051
 
        """
1052
 
        raise NotImplementedError(self.get_branch_transport)
1053
 
 
1054
 
    def get_repository_transport(self, repository_format):
1055
 
        """Get the transport for use by repository format in this BzrDir.
1056
 
 
1057
 
        Note that bzr dirs that do not support format strings will raise
1058
 
        IncompatibleFormat if the repository format they are given has
1059
 
        a format string, and vice versa.
1060
 
 
1061
 
        If repository_format is None, the transport is returned with no
1062
 
        checking. If it is not None, then the returned transport is
1063
 
        guaranteed to point to an existing directory ready for use.
1064
 
        """
1065
 
        raise NotImplementedError(self.get_repository_transport)
1066
 
 
1067
 
    def get_workingtree_transport(self, tree_format):
1068
 
        """Get the transport for use by workingtree format in this BzrDir.
1069
 
 
1070
 
        Note that bzr dirs that do not support format strings will raise
1071
 
        IncompatibleFormat if the workingtree format they are given has a
1072
 
        format string, and vice versa.
1073
 
 
1074
 
        If workingtree_format is None, the transport is returned with no
1075
 
        checking. If it is not None, then the returned transport is
1076
 
        guaranteed to point to an existing directory ready for use.
1077
 
        """
1078
 
        raise NotImplementedError(self.get_workingtree_transport)
1079
 
 
1080
933
 
1081
934
class BzrDirHooks(hooks.Hooks):
1082
935
    """Hooks for BzrDir operations."""
1083
936
 
1084
937
    def __init__(self):
1085
938
        """Create the default hooks."""
1086
 
        hooks.Hooks.__init__(self, "bzrlib.bzrdir", "BzrDir.hooks")
1087
 
        self.add_hook('pre_open',
 
939
        hooks.Hooks.__init__(self)
 
940
        self.create_hook(hooks.HookPoint('pre_open',
1088
941
            "Invoked before attempting to open a BzrDir with the transport "
1089
 
            "that the open will use.", (1, 14))
1090
 
        self.add_hook('post_repo_init',
 
942
            "that the open will use.", (1, 14), None))
 
943
        self.create_hook(hooks.HookPoint('post_repo_init',
1091
944
            "Invoked after a repository has been initialized. "
1092
945
            "post_repo_init is called with a "
1093
946
            "bzrlib.bzrdir.RepoInitHookParams.",
1094
 
            (2, 2))
 
947
            (2, 2), None))
1095
948
 
1096
949
# install the default hooks
1097
950
BzrDir.hooks = BzrDirHooks()
1098
951
 
1099
952
 
1100
953
class RepoInitHookParams(object):
1101
 
    """Object holding parameters passed to `*_repo_init` hooks.
 
954
    """Object holding parameters passed to *_repo_init hooks.
1102
955
 
1103
956
    There are 4 fields that hooks may wish to access:
1104
957
 
1133
986
                self.bzrdir)
1134
987
 
1135
988
 
 
989
class BzrDirPreSplitOut(BzrDir):
 
990
    """A common class for the all-in-one formats."""
 
991
 
 
992
    def __init__(self, _transport, _format):
 
993
        """See BzrDir.__init__."""
 
994
        super(BzrDirPreSplitOut, self).__init__(_transport, _format)
 
995
        self._control_files = lockable_files.LockableFiles(
 
996
                                            self.get_branch_transport(None),
 
997
                                            self._format._lock_file_name,
 
998
                                            self._format._lock_class)
 
999
 
 
1000
    def break_lock(self):
 
1001
        """Pre-splitout bzrdirs do not suffer from stale locks."""
 
1002
        raise NotImplementedError(self.break_lock)
 
1003
 
 
1004
    def cloning_metadir(self, require_stacking=False):
 
1005
        """Produce a metadir suitable for cloning with."""
 
1006
        if require_stacking:
 
1007
            return controldir.format_registry.make_bzrdir('1.6')
 
1008
        return self._format.__class__()
 
1009
 
 
1010
    def clone(self, url, revision_id=None, force_new_repo=False,
 
1011
              preserve_stacking=False):
 
1012
        """See BzrDir.clone().
 
1013
 
 
1014
        force_new_repo has no effect, since this family of formats always
 
1015
        require a new repository.
 
1016
        preserve_stacking has no effect, since no source branch using this
 
1017
        family of formats can be stacked, so there is no stacking to preserve.
 
1018
        """
 
1019
        self._make_tail(url)
 
1020
        result = self._format._initialize_for_clone(url)
 
1021
        self.open_repository().clone(result, revision_id=revision_id)
 
1022
        from_branch = self.open_branch()
 
1023
        from_branch.clone(result, revision_id=revision_id)
 
1024
        try:
 
1025
            tree = self.open_workingtree()
 
1026
        except errors.NotLocalUrl:
 
1027
            # make a new one, this format always has to have one.
 
1028
            result._init_workingtree()
 
1029
        else:
 
1030
            tree.clone(result)
 
1031
        return result
 
1032
 
 
1033
    def create_branch(self, name=None, repository=None):
 
1034
        """See BzrDir.create_branch."""
 
1035
        if repository is not None:
 
1036
            raise NotImplementedError(
 
1037
                "create_branch(repository=<not None>) on %r" % (self,))
 
1038
        return self._format.get_branch_format().initialize(self, name=name)
 
1039
 
 
1040
    def destroy_branch(self, name=None):
 
1041
        """See BzrDir.destroy_branch."""
 
1042
        raise errors.UnsupportedOperation(self.destroy_branch, self)
 
1043
 
 
1044
    def create_repository(self, shared=False):
 
1045
        """See BzrDir.create_repository."""
 
1046
        if shared:
 
1047
            raise errors.IncompatibleFormat('shared repository', self._format)
 
1048
        return self.open_repository()
 
1049
 
 
1050
    def destroy_repository(self):
 
1051
        """See BzrDir.destroy_repository."""
 
1052
        raise errors.UnsupportedOperation(self.destroy_repository, self)
 
1053
 
 
1054
    def create_workingtree(self, revision_id=None, from_branch=None,
 
1055
                           accelerator_tree=None, hardlink=False):
 
1056
        """See BzrDir.create_workingtree."""
 
1057
        # The workingtree is sometimes created when the bzrdir is created,
 
1058
        # but not when cloning.
 
1059
 
 
1060
        # this looks buggy but is not -really-
 
1061
        # because this format creates the workingtree when the bzrdir is
 
1062
        # created
 
1063
        # clone and sprout will have set the revision_id
 
1064
        # and that will have set it for us, its only
 
1065
        # specific uses of create_workingtree in isolation
 
1066
        # that can do wonky stuff here, and that only
 
1067
        # happens for creating checkouts, which cannot be
 
1068
        # done on this format anyway. So - acceptable wart.
 
1069
        if hardlink:
 
1070
            warning("can't support hardlinked working trees in %r"
 
1071
                % (self,))
 
1072
        try:
 
1073
            result = self.open_workingtree(recommend_upgrade=False)
 
1074
        except errors.NoSuchFile:
 
1075
            result = self._init_workingtree()
 
1076
        if revision_id is not None:
 
1077
            if revision_id == _mod_revision.NULL_REVISION:
 
1078
                result.set_parent_ids([])
 
1079
            else:
 
1080
                result.set_parent_ids([revision_id])
 
1081
        return result
 
1082
 
 
1083
    def _init_workingtree(self):
 
1084
        from bzrlib.workingtree import WorkingTreeFormat2
 
1085
        try:
 
1086
            return WorkingTreeFormat2().initialize(self)
 
1087
        except errors.NotLocalUrl:
 
1088
            # Even though we can't access the working tree, we need to
 
1089
            # create its control files.
 
1090
            return WorkingTreeFormat2()._stub_initialize_on_transport(
 
1091
                self.transport, self._control_files._file_mode)
 
1092
 
 
1093
    def destroy_workingtree(self):
 
1094
        """See BzrDir.destroy_workingtree."""
 
1095
        raise errors.UnsupportedOperation(self.destroy_workingtree, self)
 
1096
 
 
1097
    def destroy_workingtree_metadata(self):
 
1098
        """See BzrDir.destroy_workingtree_metadata."""
 
1099
        raise errors.UnsupportedOperation(self.destroy_workingtree_metadata,
 
1100
                                          self)
 
1101
 
 
1102
    def get_branch_transport(self, branch_format, name=None):
 
1103
        """See BzrDir.get_branch_transport()."""
 
1104
        if name is not None:
 
1105
            raise errors.NoColocatedBranchSupport(self)
 
1106
        if branch_format is None:
 
1107
            return self.transport
 
1108
        try:
 
1109
            branch_format.get_format_string()
 
1110
        except NotImplementedError:
 
1111
            return self.transport
 
1112
        raise errors.IncompatibleFormat(branch_format, self._format)
 
1113
 
 
1114
    def get_repository_transport(self, repository_format):
 
1115
        """See BzrDir.get_repository_transport()."""
 
1116
        if repository_format is None:
 
1117
            return self.transport
 
1118
        try:
 
1119
            repository_format.get_format_string()
 
1120
        except NotImplementedError:
 
1121
            return self.transport
 
1122
        raise errors.IncompatibleFormat(repository_format, self._format)
 
1123
 
 
1124
    def get_workingtree_transport(self, workingtree_format):
 
1125
        """See BzrDir.get_workingtree_transport()."""
 
1126
        if workingtree_format is None:
 
1127
            return self.transport
 
1128
        try:
 
1129
            workingtree_format.get_format_string()
 
1130
        except NotImplementedError:
 
1131
            return self.transport
 
1132
        raise errors.IncompatibleFormat(workingtree_format, self._format)
 
1133
 
 
1134
    def needs_format_conversion(self, format=None):
 
1135
        """See BzrDir.needs_format_conversion()."""
 
1136
        # if the format is not the same as the system default,
 
1137
        # an upgrade is needed.
 
1138
        if format is None:
 
1139
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
 
1140
                % 'needs_format_conversion(format=None)')
 
1141
            format = BzrDirFormat.get_default_format()
 
1142
        return not isinstance(self._format, format.__class__)
 
1143
 
 
1144
    def open_branch(self, name=None, unsupported=False,
 
1145
                    ignore_fallbacks=False):
 
1146
        """See BzrDir.open_branch."""
 
1147
        from bzrlib.branch import BzrBranchFormat4
 
1148
        format = BzrBranchFormat4()
 
1149
        self._check_supported(format, unsupported)
 
1150
        return format.open(self, name, _found=True)
 
1151
 
 
1152
    def sprout(self, url, revision_id=None, force_new_repo=False,
 
1153
               possible_transports=None, accelerator_tree=None,
 
1154
               hardlink=False, stacked=False, create_tree_if_local=True,
 
1155
               source_branch=None):
 
1156
        """See BzrDir.sprout()."""
 
1157
        if source_branch is not None:
 
1158
            my_branch = self.open_branch()
 
1159
            if source_branch.base != my_branch.base:
 
1160
                raise AssertionError(
 
1161
                    "source branch %r is not within %r with branch %r" %
 
1162
                    (source_branch, self, my_branch))
 
1163
        if stacked:
 
1164
            raise errors.UnstackableBranchFormat(
 
1165
                self._format, self.root_transport.base)
 
1166
        if not create_tree_if_local:
 
1167
            raise errors.MustHaveWorkingTree(
 
1168
                self._format, self.root_transport.base)
 
1169
        from bzrlib.workingtree import WorkingTreeFormat2
 
1170
        self._make_tail(url)
 
1171
        result = self._format._initialize_for_clone(url)
 
1172
        try:
 
1173
            self.open_repository().clone(result, revision_id=revision_id)
 
1174
        except errors.NoRepositoryPresent:
 
1175
            pass
 
1176
        try:
 
1177
            self.open_branch().sprout(result, revision_id=revision_id)
 
1178
        except errors.NotBranchError:
 
1179
            pass
 
1180
 
 
1181
        # we always want a working tree
 
1182
        WorkingTreeFormat2().initialize(result,
 
1183
                                        accelerator_tree=accelerator_tree,
 
1184
                                        hardlink=hardlink)
 
1185
        return result
 
1186
 
 
1187
 
 
1188
class BzrDir4(BzrDirPreSplitOut):
 
1189
    """A .bzr version 4 control object.
 
1190
 
 
1191
    This is a deprecated format and may be removed after sept 2006.
 
1192
    """
 
1193
 
 
1194
    def create_repository(self, shared=False):
 
1195
        """See BzrDir.create_repository."""
 
1196
        return self._format.repository_format.initialize(self, shared)
 
1197
 
 
1198
    def needs_format_conversion(self, format=None):
 
1199
        """Format 4 dirs are always in need of conversion."""
 
1200
        if format is None:
 
1201
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
 
1202
                % 'needs_format_conversion(format=None)')
 
1203
        return True
 
1204
 
 
1205
    def open_repository(self):
 
1206
        """See BzrDir.open_repository."""
 
1207
        from bzrlib.repofmt.weaverepo import RepositoryFormat4
 
1208
        return RepositoryFormat4().open(self, _found=True)
 
1209
 
 
1210
 
 
1211
class BzrDir5(BzrDirPreSplitOut):
 
1212
    """A .bzr version 5 control object.
 
1213
 
 
1214
    This is a deprecated format and may be removed after sept 2006.
 
1215
    """
 
1216
 
 
1217
    def has_workingtree(self):
 
1218
        """See BzrDir.has_workingtree."""
 
1219
        return True
 
1220
    
 
1221
    def open_repository(self):
 
1222
        """See BzrDir.open_repository."""
 
1223
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
 
1224
        return RepositoryFormat5().open(self, _found=True)
 
1225
 
 
1226
    def open_workingtree(self, _unsupported=False,
 
1227
            recommend_upgrade=True):
 
1228
        """See BzrDir.create_workingtree."""
 
1229
        from bzrlib.workingtree import WorkingTreeFormat2
 
1230
        wt_format = WorkingTreeFormat2()
 
1231
        # we don't warn here about upgrades; that ought to be handled for the
 
1232
        # bzrdir as a whole
 
1233
        return wt_format.open(self, _found=True)
 
1234
 
 
1235
 
 
1236
class BzrDir6(BzrDirPreSplitOut):
 
1237
    """A .bzr version 6 control object.
 
1238
 
 
1239
    This is a deprecated format and may be removed after sept 2006.
 
1240
    """
 
1241
 
 
1242
    def has_workingtree(self):
 
1243
        """See BzrDir.has_workingtree."""
 
1244
        return True
 
1245
    
 
1246
    def open_repository(self):
 
1247
        """See BzrDir.open_repository."""
 
1248
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
 
1249
        return RepositoryFormat6().open(self, _found=True)
 
1250
 
 
1251
    def open_workingtree(self, _unsupported=False,
 
1252
        recommend_upgrade=True):
 
1253
        """See BzrDir.create_workingtree."""
 
1254
        # we don't warn here about upgrades; that ought to be handled for the
 
1255
        # bzrdir as a whole
 
1256
        from bzrlib.workingtree import WorkingTreeFormat2
 
1257
        return WorkingTreeFormat2().open(self, _found=True)
 
1258
 
 
1259
 
1136
1260
class BzrDirMeta1(BzrDir):
1137
1261
    """A .bzr meta version 1 control object.
1138
1262
 
1146
1270
        """See BzrDir.can_convert_format()."""
1147
1271
        return True
1148
1272
 
1149
 
    def create_branch(self, name=None, repository=None,
1150
 
            append_revisions_only=None):
 
1273
    def create_branch(self, name=None, repository=None):
1151
1274
        """See BzrDir.create_branch."""
1152
1275
        return self._format.get_branch_format().initialize(self, name=name,
1153
 
                repository=repository,
1154
 
                append_revisions_only=append_revisions_only)
 
1276
                repository=repository)
1155
1277
 
1156
1278
    def destroy_branch(self, name=None):
1157
1279
        """See BzrDir.create_branch."""
1257
1379
    def has_workingtree(self):
1258
1380
        """Tell if this bzrdir contains a working tree.
1259
1381
 
 
1382
        This will still raise an exception if the bzrdir has a workingtree that
 
1383
        is remote & inaccessible.
 
1384
 
1260
1385
        Note: if you're going to open the working tree, you should just go
1261
1386
        ahead and try, and not ask permission first.
1262
1387
        """
1263
1388
        from bzrlib.workingtree import WorkingTreeFormat
1264
1389
        try:
1265
 
            WorkingTreeFormat.find_format_string(self)
 
1390
            WorkingTreeFormat.find_format(self)
1266
1391
        except errors.NoWorkingTree:
1267
1392
            return False
1268
1393
        return True
1269
1394
 
1270
 
    def needs_format_conversion(self, format):
 
1395
    def needs_format_conversion(self, format=None):
1271
1396
        """See BzrDir.needs_format_conversion()."""
 
1397
        if format is None:
 
1398
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
 
1399
                % 'needs_format_conversion(format=None)')
 
1400
        if format is None:
 
1401
            format = BzrDirFormat.get_default_format()
1272
1402
        if not isinstance(self._format, format.__class__):
1273
1403
            # it is not a meta dir format, conversion is needed.
1274
1404
            return True
1299
1429
                    ignore_fallbacks=False):
1300
1430
        """See BzrDir.open_branch."""
1301
1431
        format = self.find_branch_format(name=name)
1302
 
        format.check_support_status(unsupported)
 
1432
        self._check_supported(format, unsupported)
1303
1433
        return format.open(self, name=name,
1304
1434
            _found=True, ignore_fallbacks=ignore_fallbacks)
1305
1435
 
1307
1437
        """See BzrDir.open_repository."""
1308
1438
        from bzrlib.repository import RepositoryFormat
1309
1439
        format = RepositoryFormat.find_format(self)
1310
 
        format.check_support_status(unsupported)
 
1440
        self._check_supported(format, unsupported)
1311
1441
        return format.open(self, _found=True)
1312
1442
 
1313
1443
    def open_workingtree(self, unsupported=False,
1315
1445
        """See BzrDir.open_workingtree."""
1316
1446
        from bzrlib.workingtree import WorkingTreeFormat
1317
1447
        format = WorkingTreeFormat.find_format(self)
1318
 
        format.check_support_status(unsupported, recommend_upgrade,
 
1448
        self._check_supported(format, unsupported,
 
1449
            recommend_upgrade,
1319
1450
            basedir=self.root_transport.base)
1320
1451
        return format.open(self, _found=True)
1321
1452
 
1326
1457
class BzrProber(controldir.Prober):
1327
1458
    """Prober for formats that use a .bzr/ control directory."""
1328
1459
 
1329
 
    formats = registry.FormatRegistry(controldir.network_format_registry)
 
1460
    _formats = {}
1330
1461
    """The known .bzr formats."""
1331
1462
 
1332
1463
    @classmethod
1333
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1334
1464
    def register_bzrdir_format(klass, format):
1335
 
        klass.formats.register(format.get_format_string(), format)
 
1465
        klass._formats[format.get_format_string()] = format
1336
1466
 
1337
1467
    @classmethod
1338
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1339
1468
    def unregister_bzrdir_format(klass, format):
1340
 
        klass.formats.remove(format.get_format_string())
 
1469
        del klass._formats[format.get_format_string()]
1341
1470
 
1342
1471
    @classmethod
1343
1472
    def probe_transport(klass, transport):
1347
1476
        except errors.NoSuchFile:
1348
1477
            raise errors.NotBranchError(path=transport.base)
1349
1478
        try:
1350
 
            return klass.formats.get(format_string)
 
1479
            return klass._formats[format_string]
1351
1480
        except KeyError:
1352
1481
            raise errors.UnknownFormatError(format=format_string, kind='bzrdir')
1353
1482
 
1354
 
    @classmethod
1355
 
    def known_formats(cls):
1356
 
        result = set()
1357
 
        for name, format in cls.formats.iteritems():
1358
 
            if callable(format):
1359
 
                format = format()
1360
 
            result.add(format)
1361
 
        return result
1362
 
 
1363
1483
 
1364
1484
controldir.ControlDirFormat.register_prober(BzrProber)
1365
1485
 
1389
1509
                    raise errors.NotBranchError(path=transport.base)
1390
1510
                if server_version != '2':
1391
1511
                    raise errors.NotBranchError(path=transport.base)
1392
 
            from bzrlib.remote import RemoteBzrDirFormat
1393
1512
            return RemoteBzrDirFormat()
1394
1513
 
1395
 
    @classmethod
1396
 
    def known_formats(cls):
1397
 
        from bzrlib.remote import RemoteBzrDirFormat
1398
 
        return set([RemoteBzrDirFormat()])
1399
 
 
1400
1514
 
1401
1515
class BzrDirFormat(controldir.ControlDirFormat):
1402
1516
    """ControlDirFormat base class for .bzr/ directories.
1415
1529
    # _lock_class must be set in subclasses to the lock type, typ.
1416
1530
    # TransportLock or LockDir
1417
1531
 
1418
 
    @classmethod
1419
 
    def get_format_string(cls):
 
1532
    def get_format_string(self):
1420
1533
        """Return the ASCII format string that identifies this format."""
1421
 
        raise NotImplementedError(cls.get_format_string)
 
1534
        raise NotImplementedError(self.get_format_string)
1422
1535
 
1423
1536
    def initialize_on_transport(self, transport):
1424
1537
        """Initialize a new bzrdir in the base directory of a Transport."""
1434
1547
            # metadir1
1435
1548
            if type(self) != BzrDirMetaFormat1:
1436
1549
                return self._initialize_on_transport_vfs(transport)
1437
 
            from bzrlib.remote import RemoteBzrDirFormat
1438
1550
            remote_format = RemoteBzrDirFormat()
1439
1551
            self._supply_sub_formats_to(remote_format)
1440
1552
            return remote_format.initialize_on_transport(transport)
1478
1590
            except errors.NoSmartMedium:
1479
1591
                pass
1480
1592
            else:
1481
 
                from bzrlib.remote import RemoteBzrDirFormat
1482
1593
                # TODO: lookup the local format from a server hint.
1483
1594
                remote_dir_format = RemoteBzrDirFormat()
1484
1595
                remote_dir_format._network_name = self.network_name()
1599
1710
        """
1600
1711
        raise NotImplementedError(self._open)
1601
1712
 
 
1713
    @classmethod
 
1714
    def register_format(klass, format):
 
1715
        BzrProber.register_bzrdir_format(format)
 
1716
        # bzr native formats have a network name of their format string.
 
1717
        controldir.network_format_registry.register(format.get_format_string(), format.__class__)
 
1718
        controldir.ControlDirFormat.register_format(format)
 
1719
 
1602
1720
    def _supply_sub_formats_to(self, other_format):
1603
1721
        """Give other_format the same values for sub formats as this has.
1604
1722
 
1611
1729
        :return: None.
1612
1730
        """
1613
1731
 
 
1732
    @classmethod
 
1733
    def unregister_format(klass, format):
 
1734
        BzrProber.unregister_bzrdir_format(format)
 
1735
        controldir.ControlDirFormat.unregister_format(format)
 
1736
        controldir.network_format_registry.remove(format.get_format_string())
 
1737
 
 
1738
 
 
1739
class BzrDirFormat4(BzrDirFormat):
 
1740
    """Bzr dir format 4.
 
1741
 
 
1742
    This format is a combined format for working tree, branch and repository.
 
1743
    It has:
 
1744
     - Format 1 working trees [always]
 
1745
     - Format 4 branches [always]
 
1746
     - Format 4 repositories [always]
 
1747
 
 
1748
    This format is deprecated: it indexes texts using a text it which is
 
1749
    removed in format 5; write support for this format has been removed.
 
1750
    """
 
1751
 
 
1752
    _lock_class = lockable_files.TransportLock
 
1753
 
 
1754
    def get_format_string(self):
 
1755
        """See BzrDirFormat.get_format_string()."""
 
1756
        return "Bazaar-NG branch, format 0.0.4\n"
 
1757
 
 
1758
    def get_format_description(self):
 
1759
        """See BzrDirFormat.get_format_description()."""
 
1760
        return "All-in-one format 4"
 
1761
 
 
1762
    def get_converter(self, format=None):
 
1763
        """See BzrDirFormat.get_converter()."""
 
1764
        # there is one and only one upgrade path here.
 
1765
        return ConvertBzrDir4To5()
 
1766
 
 
1767
    def initialize_on_transport(self, transport):
 
1768
        """Format 4 branches cannot be created."""
 
1769
        raise errors.UninitializableFormat(self)
 
1770
 
 
1771
    def is_supported(self):
 
1772
        """Format 4 is not supported.
 
1773
 
 
1774
        It is not supported because the model changed from 4 to 5 and the
 
1775
        conversion logic is expensive - so doing it on the fly was not
 
1776
        feasible.
 
1777
        """
 
1778
        return False
 
1779
 
 
1780
    def network_name(self):
 
1781
        return self.get_format_string()
 
1782
 
 
1783
    def _open(self, transport):
 
1784
        """See BzrDirFormat._open."""
 
1785
        return BzrDir4(transport, self)
 
1786
 
 
1787
    def __return_repository_format(self):
 
1788
        """Circular import protection."""
 
1789
        from bzrlib.repofmt.weaverepo import RepositoryFormat4
 
1790
        return RepositoryFormat4()
 
1791
    repository_format = property(__return_repository_format)
 
1792
 
 
1793
 
 
1794
class BzrDirFormatAllInOne(BzrDirFormat):
 
1795
    """Common class for formats before meta-dirs."""
 
1796
 
 
1797
    def initialize_on_transport_ex(self, transport, use_existing_dir=False,
 
1798
        create_prefix=False, force_new_repo=False, stacked_on=None,
 
1799
        stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
 
1800
        shared_repo=False):
 
1801
        """See BzrDirFormat.initialize_on_transport_ex."""
 
1802
        require_stacking = (stacked_on is not None)
 
1803
        # Format 5 cannot stack, but we've been asked to - actually init
 
1804
        # a Meta1Dir
 
1805
        if require_stacking:
 
1806
            format = BzrDirMetaFormat1()
 
1807
            return format.initialize_on_transport_ex(transport,
 
1808
                use_existing_dir=use_existing_dir, create_prefix=create_prefix,
 
1809
                force_new_repo=force_new_repo, stacked_on=stacked_on,
 
1810
                stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
 
1811
                make_working_trees=make_working_trees, shared_repo=shared_repo)
 
1812
        return BzrDirFormat.initialize_on_transport_ex(self, transport,
 
1813
            use_existing_dir=use_existing_dir, create_prefix=create_prefix,
 
1814
            force_new_repo=force_new_repo, stacked_on=stacked_on,
 
1815
            stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
 
1816
            make_working_trees=make_working_trees, shared_repo=shared_repo)
 
1817
 
 
1818
 
 
1819
class BzrDirFormat5(BzrDirFormatAllInOne):
 
1820
    """Bzr control format 5.
 
1821
 
 
1822
    This format is a combined format for working tree, branch and repository.
 
1823
    It has:
 
1824
     - Format 2 working trees [always]
 
1825
     - Format 4 branches [always]
 
1826
     - Format 5 repositories [always]
 
1827
       Unhashed stores in the repository.
 
1828
    """
 
1829
 
 
1830
    _lock_class = lockable_files.TransportLock
 
1831
 
 
1832
    def get_format_string(self):
 
1833
        """See BzrDirFormat.get_format_string()."""
 
1834
        return "Bazaar-NG branch, format 5\n"
 
1835
 
 
1836
    def get_branch_format(self):
 
1837
        from bzrlib import branch
 
1838
        return branch.BzrBranchFormat4()
 
1839
 
 
1840
    def get_format_description(self):
 
1841
        """See BzrDirFormat.get_format_description()."""
 
1842
        return "All-in-one format 5"
 
1843
 
 
1844
    def get_converter(self, format=None):
 
1845
        """See BzrDirFormat.get_converter()."""
 
1846
        # there is one and only one upgrade path here.
 
1847
        return ConvertBzrDir5To6()
 
1848
 
 
1849
    def _initialize_for_clone(self, url):
 
1850
        return self.initialize_on_transport(
 
1851
            _mod_transport.get_transport(url), _cloning=True)
 
1852
 
 
1853
    def initialize_on_transport(self, transport, _cloning=False):
 
1854
        """Format 5 dirs always have working tree, branch and repository.
 
1855
 
 
1856
        Except when they are being cloned.
 
1857
        """
 
1858
        from bzrlib.branch import BzrBranchFormat4
 
1859
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
 
1860
        result = (super(BzrDirFormat5, self).initialize_on_transport(transport))
 
1861
        RepositoryFormat5().initialize(result, _internal=True)
 
1862
        if not _cloning:
 
1863
            branch = BzrBranchFormat4().initialize(result)
 
1864
            result._init_workingtree()
 
1865
        return result
 
1866
 
 
1867
    def network_name(self):
 
1868
        return self.get_format_string()
 
1869
 
 
1870
    def _open(self, transport):
 
1871
        """See BzrDirFormat._open."""
 
1872
        return BzrDir5(transport, self)
 
1873
 
 
1874
    def __return_repository_format(self):
 
1875
        """Circular import protection."""
 
1876
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
 
1877
        return RepositoryFormat5()
 
1878
    repository_format = property(__return_repository_format)
 
1879
 
 
1880
 
 
1881
class BzrDirFormat6(BzrDirFormatAllInOne):
 
1882
    """Bzr control format 6.
 
1883
 
 
1884
    This format is a combined format for working tree, branch and repository.
 
1885
    It has:
 
1886
     - Format 2 working trees [always]
 
1887
     - Format 4 branches [always]
 
1888
     - Format 6 repositories [always]
 
1889
    """
 
1890
 
 
1891
    _lock_class = lockable_files.TransportLock
 
1892
 
 
1893
    def get_format_string(self):
 
1894
        """See BzrDirFormat.get_format_string()."""
 
1895
        return "Bazaar-NG branch, format 6\n"
 
1896
 
 
1897
    def get_format_description(self):
 
1898
        """See BzrDirFormat.get_format_description()."""
 
1899
        return "All-in-one format 6"
 
1900
 
 
1901
    def get_branch_format(self):
 
1902
        from bzrlib import branch
 
1903
        return branch.BzrBranchFormat4()
 
1904
 
 
1905
    def get_converter(self, format=None):
 
1906
        """See BzrDirFormat.get_converter()."""
 
1907
        # there is one and only one upgrade path here.
 
1908
        return ConvertBzrDir6ToMeta()
 
1909
 
 
1910
    def _initialize_for_clone(self, url):
 
1911
        return self.initialize_on_transport(
 
1912
            _mod_transport.get_transport(url), _cloning=True)
 
1913
 
 
1914
    def initialize_on_transport(self, transport, _cloning=False):
 
1915
        """Format 6 dirs always have working tree, branch and repository.
 
1916
 
 
1917
        Except when they are being cloned.
 
1918
        """
 
1919
        from bzrlib.branch import BzrBranchFormat4
 
1920
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
 
1921
        result = super(BzrDirFormat6, self).initialize_on_transport(transport)
 
1922
        RepositoryFormat6().initialize(result, _internal=True)
 
1923
        if not _cloning:
 
1924
            branch = BzrBranchFormat4().initialize(result)
 
1925
            result._init_workingtree()
 
1926
        return result
 
1927
 
 
1928
    def network_name(self):
 
1929
        return self.get_format_string()
 
1930
 
 
1931
    def _open(self, transport):
 
1932
        """See BzrDirFormat._open."""
 
1933
        return BzrDir6(transport, self)
 
1934
 
 
1935
    def __return_repository_format(self):
 
1936
        """Circular import protection."""
 
1937
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
 
1938
        return RepositoryFormat6()
 
1939
    repository_format = property(__return_repository_format)
 
1940
 
1614
1941
 
1615
1942
class BzrDirMetaFormat1(BzrDirFormat):
1616
1943
    """Bzr meta control format 1
1617
1944
 
1618
1945
    This is the first format with split out working tree, branch and repository
1619
1946
    disk storage.
1620
 
 
1621
1947
    It has:
1622
 
 
1623
 
    - Format 3 working trees [optional]
1624
 
    - Format 5 branches [optional]
1625
 
    - Format 7 repositories [optional]
 
1948
     - Format 3 working trees [optional]
 
1949
     - Format 5 branches [optional]
 
1950
     - Format 7 repositories [optional]
1626
1951
    """
1627
1952
 
1628
1953
    _lock_class = lockdir.LockDir
1629
1954
 
1630
 
    fixed_components = False
1631
 
 
1632
1955
    def __init__(self):
1633
1956
        self._workingtree_format = None
1634
1957
        self._branch_format = None
1648
1971
 
1649
1972
    def get_branch_format(self):
1650
1973
        if self._branch_format is None:
1651
 
            from bzrlib.branch import format_registry as branch_format_registry
1652
 
            self._branch_format = branch_format_registry.get_default()
 
1974
            from bzrlib.branch import BranchFormat
 
1975
            self._branch_format = BranchFormat.get_default_format()
1653
1976
        return self._branch_format
1654
1977
 
1655
1978
    def set_branch_format(self, format):
1710
2033
                    # stack_on is inaccessible, JFDI.
1711
2034
                    # TODO: bad monkey, hard-coded formats...
1712
2035
                    if self.repository_format.rich_root_data:
1713
 
                        new_repo_format = knitpack_repo.RepositoryFormatKnitPack5RichRoot()
 
2036
                        new_repo_format = pack_repo.RepositoryFormatKnitPack5RichRoot()
1714
2037
                    else:
1715
 
                        new_repo_format = knitpack_repo.RepositoryFormatKnitPack5()
 
2038
                        new_repo_format = pack_repo.RepositoryFormatKnitPack5()
1716
2039
            else:
1717
2040
                # If the target already supports stacking, then we know the
1718
2041
                # project is already able to use stacking, so auto-upgrade
1724
2047
                    new_repo_format = None
1725
2048
            if new_repo_format is not None:
1726
2049
                self.repository_format = new_repo_format
1727
 
                note(gettext('Source repository format does not support stacking,'
1728
 
                     ' using format:\n  %s'),
 
2050
                note('Source repository format does not support stacking,'
 
2051
                     ' using format:\n  %s',
1729
2052
                     new_repo_format.get_format_description())
1730
2053
 
1731
2054
        if not self.get_branch_format().supports_stacking():
1735
2058
            if target_branch is None:
1736
2059
                if do_upgrade:
1737
2060
                    # TODO: bad monkey, hard-coded formats...
1738
 
                    from bzrlib.branch import BzrBranchFormat7
1739
 
                    new_branch_format = BzrBranchFormat7()
 
2061
                    new_branch_format = branch.BzrBranchFormat7()
1740
2062
            else:
1741
2063
                new_branch_format = target_branch._format
1742
2064
                if not new_branch_format.supports_stacking():
1744
2066
            if new_branch_format is not None:
1745
2067
                # Does support stacking, use its format.
1746
2068
                self.set_branch_format(new_branch_format)
1747
 
                note(gettext('Source branch format does not support stacking,'
1748
 
                     ' using format:\n  %s'),
 
2069
                note('Source branch format does not support stacking,'
 
2070
                     ' using format:\n  %s',
1749
2071
                     new_branch_format.get_format_description())
1750
2072
 
1751
2073
    def get_converter(self, format=None):
1757
2079
            raise NotImplementedError(self.get_converter)
1758
2080
        return ConvertMetaToMeta(format)
1759
2081
 
1760
 
    @classmethod
1761
 
    def get_format_string(cls):
 
2082
    def get_format_string(self):
1762
2083
        """See BzrDirFormat.get_format_string()."""
1763
2084
        return "Bazaar-NG meta directory, format 1\n"
1764
2085
 
1812
2133
 
1813
2134
    def __get_workingtree_format(self):
1814
2135
        if self._workingtree_format is None:
1815
 
            from bzrlib.workingtree import (
1816
 
                format_registry as wt_format_registry,
1817
 
                )
1818
 
            self._workingtree_format = wt_format_registry.get_default()
 
2136
            from bzrlib.workingtree import WorkingTreeFormat
 
2137
            self._workingtree_format = WorkingTreeFormat.get_default_format()
1819
2138
        return self._workingtree_format
1820
2139
 
1821
2140
    def __set_workingtree_format(self, wt_format):
1826
2145
 
1827
2146
 
1828
2147
# Register bzr formats
1829
 
BzrProber.formats.register(BzrDirMetaFormat1.get_format_string(),
1830
 
    BzrDirMetaFormat1)
1831
 
controldir.ControlDirFormat._default_format = BzrDirMetaFormat1()
1832
 
 
1833
 
 
1834
 
class ConvertMetaToMeta(controldir.Converter):
 
2148
BzrDirFormat.register_format(BzrDirFormat4())
 
2149
BzrDirFormat.register_format(BzrDirFormat5())
 
2150
BzrDirFormat.register_format(BzrDirFormat6())
 
2151
__default_format = BzrDirMetaFormat1()
 
2152
BzrDirFormat.register_format(__default_format)
 
2153
controldir.ControlDirFormat._default_format = __default_format
 
2154
 
 
2155
 
 
2156
class Converter(object):
 
2157
    """Converts a disk format object from one format to another."""
 
2158
 
 
2159
    def convert(self, to_convert, pb):
 
2160
        """Perform the conversion of to_convert, giving feedback via pb.
 
2161
 
 
2162
        :param to_convert: The disk object to convert.
 
2163
        :param pb: a progress bar to use for progress information.
 
2164
        """
 
2165
 
 
2166
    def step(self, message):
 
2167
        """Update the pb by a step."""
 
2168
        self.count +=1
 
2169
        self.pb.update(message, self.count, self.total)
 
2170
 
 
2171
 
 
2172
class ConvertBzrDir4To5(Converter):
 
2173
    """Converts format 4 bzr dirs to format 5."""
 
2174
 
 
2175
    def __init__(self):
 
2176
        super(ConvertBzrDir4To5, self).__init__()
 
2177
        self.converted_revs = set()
 
2178
        self.absent_revisions = set()
 
2179
        self.text_count = 0
 
2180
        self.revisions = {}
 
2181
 
 
2182
    def convert(self, to_convert, pb):
 
2183
        """See Converter.convert()."""
 
2184
        self.bzrdir = to_convert
 
2185
        if pb is not None:
 
2186
            warnings.warn("pb parameter to convert() is deprecated")
 
2187
        self.pb = ui.ui_factory.nested_progress_bar()
 
2188
        try:
 
2189
            ui.ui_factory.note('starting upgrade from format 4 to 5')
 
2190
            if isinstance(self.bzrdir.transport, local.LocalTransport):
 
2191
                self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
 
2192
            self._convert_to_weaves()
 
2193
            return BzrDir.open(self.bzrdir.user_url)
 
2194
        finally:
 
2195
            self.pb.finished()
 
2196
 
 
2197
    def _convert_to_weaves(self):
 
2198
        ui.ui_factory.note('note: upgrade may be faster if all store files are ungzipped first')
 
2199
        try:
 
2200
            # TODO permissions
 
2201
            stat = self.bzrdir.transport.stat('weaves')
 
2202
            if not S_ISDIR(stat.st_mode):
 
2203
                self.bzrdir.transport.delete('weaves')
 
2204
                self.bzrdir.transport.mkdir('weaves')
 
2205
        except errors.NoSuchFile:
 
2206
            self.bzrdir.transport.mkdir('weaves')
 
2207
        # deliberately not a WeaveFile as we want to build it up slowly.
 
2208
        self.inv_weave = Weave('inventory')
 
2209
        # holds in-memory weaves for all files
 
2210
        self.text_weaves = {}
 
2211
        self.bzrdir.transport.delete('branch-format')
 
2212
        self.branch = self.bzrdir.open_branch()
 
2213
        self._convert_working_inv()
 
2214
        rev_history = self.branch.revision_history()
 
2215
        # to_read is a stack holding the revisions we still need to process;
 
2216
        # appending to it adds new highest-priority revisions
 
2217
        self.known_revisions = set(rev_history)
 
2218
        self.to_read = rev_history[-1:]
 
2219
        while self.to_read:
 
2220
            rev_id = self.to_read.pop()
 
2221
            if (rev_id not in self.revisions
 
2222
                and rev_id not in self.absent_revisions):
 
2223
                self._load_one_rev(rev_id)
 
2224
        self.pb.clear()
 
2225
        to_import = self._make_order()
 
2226
        for i, rev_id in enumerate(to_import):
 
2227
            self.pb.update('converting revision', i, len(to_import))
 
2228
            self._convert_one_rev(rev_id)
 
2229
        self.pb.clear()
 
2230
        self._write_all_weaves()
 
2231
        self._write_all_revs()
 
2232
        ui.ui_factory.note('upgraded to weaves:')
 
2233
        ui.ui_factory.note('  %6d revisions and inventories' % len(self.revisions))
 
2234
        ui.ui_factory.note('  %6d revisions not present' % len(self.absent_revisions))
 
2235
        ui.ui_factory.note('  %6d texts' % self.text_count)
 
2236
        self._cleanup_spare_files_after_format4()
 
2237
        self.branch._transport.put_bytes(
 
2238
            'branch-format',
 
2239
            BzrDirFormat5().get_format_string(),
 
2240
            mode=self.bzrdir._get_file_mode())
 
2241
 
 
2242
    def _cleanup_spare_files_after_format4(self):
 
2243
        # FIXME working tree upgrade foo.
 
2244
        for n in 'merged-patches', 'pending-merged-patches':
 
2245
            try:
 
2246
                ## assert os.path.getsize(p) == 0
 
2247
                self.bzrdir.transport.delete(n)
 
2248
            except errors.NoSuchFile:
 
2249
                pass
 
2250
        self.bzrdir.transport.delete_tree('inventory-store')
 
2251
        self.bzrdir.transport.delete_tree('text-store')
 
2252
 
 
2253
    def _convert_working_inv(self):
 
2254
        inv = xml4.serializer_v4.read_inventory(
 
2255
                self.branch._transport.get('inventory'))
 
2256
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv, working=True)
 
2257
        self.branch._transport.put_bytes('inventory', new_inv_xml,
 
2258
            mode=self.bzrdir._get_file_mode())
 
2259
 
 
2260
    def _write_all_weaves(self):
 
2261
        controlweaves = VersionedFileStore(self.bzrdir.transport, prefixed=False,
 
2262
                                           versionedfile_class=WeaveFile)
 
2263
        weave_transport = self.bzrdir.transport.clone('weaves')
 
2264
        weaves = VersionedFileStore(weave_transport, prefixed=False,
 
2265
                            versionedfile_class=WeaveFile)
 
2266
        transaction = WriteTransaction()
 
2267
 
 
2268
        try:
 
2269
            i = 0
 
2270
            for file_id, file_weave in self.text_weaves.items():
 
2271
                self.pb.update('writing weave', i, len(self.text_weaves))
 
2272
                weaves._put_weave(file_id, file_weave, transaction)
 
2273
                i += 1
 
2274
            self.pb.update('inventory', 0, 1)
 
2275
            controlweaves._put_weave('inventory', self.inv_weave, transaction)
 
2276
            self.pb.update('inventory', 1, 1)
 
2277
        finally:
 
2278
            self.pb.clear()
 
2279
 
 
2280
    def _write_all_revs(self):
 
2281
        """Write all revisions out in new form."""
 
2282
        self.bzrdir.transport.delete_tree('revision-store')
 
2283
        self.bzrdir.transport.mkdir('revision-store')
 
2284
        revision_transport = self.bzrdir.transport.clone('revision-store')
 
2285
        # TODO permissions
 
2286
        from bzrlib.xml5 import serializer_v5
 
2287
        from bzrlib.repofmt.weaverepo import RevisionTextStore
 
2288
        revision_store = RevisionTextStore(revision_transport,
 
2289
            serializer_v5, False, versionedfile.PrefixMapper(),
 
2290
            lambda:True, lambda:True)
 
2291
        try:
 
2292
            for i, rev_id in enumerate(self.converted_revs):
 
2293
                self.pb.update('write revision', i, len(self.converted_revs))
 
2294
                text = serializer_v5.write_revision_to_string(
 
2295
                    self.revisions[rev_id])
 
2296
                key = (rev_id,)
 
2297
                revision_store.add_lines(key, None, osutils.split_lines(text))
 
2298
        finally:
 
2299
            self.pb.clear()
 
2300
 
 
2301
    def _load_one_rev(self, rev_id):
 
2302
        """Load a revision object into memory.
 
2303
 
 
2304
        Any parents not either loaded or abandoned get queued to be
 
2305
        loaded."""
 
2306
        self.pb.update('loading revision',
 
2307
                       len(self.revisions),
 
2308
                       len(self.known_revisions))
 
2309
        if not self.branch.repository.has_revision(rev_id):
 
2310
            self.pb.clear()
 
2311
            ui.ui_factory.note('revision {%s} not present in branch; '
 
2312
                         'will be converted as a ghost' %
 
2313
                         rev_id)
 
2314
            self.absent_revisions.add(rev_id)
 
2315
        else:
 
2316
            rev = self.branch.repository.get_revision(rev_id)
 
2317
            for parent_id in rev.parent_ids:
 
2318
                self.known_revisions.add(parent_id)
 
2319
                self.to_read.append(parent_id)
 
2320
            self.revisions[rev_id] = rev
 
2321
 
 
2322
    def _load_old_inventory(self, rev_id):
 
2323
        f = self.branch.repository.inventory_store.get(rev_id)
 
2324
        try:
 
2325
            old_inv_xml = f.read()
 
2326
        finally:
 
2327
            f.close()
 
2328
        inv = xml4.serializer_v4.read_inventory_from_string(old_inv_xml)
 
2329
        inv.revision_id = rev_id
 
2330
        rev = self.revisions[rev_id]
 
2331
        return inv
 
2332
 
 
2333
    def _load_updated_inventory(self, rev_id):
 
2334
        inv_xml = self.inv_weave.get_text(rev_id)
 
2335
        inv = xml5.serializer_v5.read_inventory_from_string(inv_xml, rev_id)
 
2336
        return inv
 
2337
 
 
2338
    def _convert_one_rev(self, rev_id):
 
2339
        """Convert revision and all referenced objects to new format."""
 
2340
        rev = self.revisions[rev_id]
 
2341
        inv = self._load_old_inventory(rev_id)
 
2342
        present_parents = [p for p in rev.parent_ids
 
2343
                           if p not in self.absent_revisions]
 
2344
        self._convert_revision_contents(rev, inv, present_parents)
 
2345
        self._store_new_inv(rev, inv, present_parents)
 
2346
        self.converted_revs.add(rev_id)
 
2347
 
 
2348
    def _store_new_inv(self, rev, inv, present_parents):
 
2349
        new_inv_xml = xml5.serializer_v5.write_inventory_to_string(inv)
 
2350
        new_inv_sha1 = sha_string(new_inv_xml)
 
2351
        self.inv_weave.add_lines(rev.revision_id,
 
2352
                                 present_parents,
 
2353
                                 new_inv_xml.splitlines(True))
 
2354
        rev.inventory_sha1 = new_inv_sha1
 
2355
 
 
2356
    def _convert_revision_contents(self, rev, inv, present_parents):
 
2357
        """Convert all the files within a revision.
 
2358
 
 
2359
        Also upgrade the inventory to refer to the text revision ids."""
 
2360
        rev_id = rev.revision_id
 
2361
        mutter('converting texts of revision {%s}',
 
2362
               rev_id)
 
2363
        parent_invs = map(self._load_updated_inventory, present_parents)
 
2364
        entries = inv.iter_entries()
 
2365
        entries.next()
 
2366
        for path, ie in entries:
 
2367
            self._convert_file_version(rev, ie, parent_invs)
 
2368
 
 
2369
    def _convert_file_version(self, rev, ie, parent_invs):
 
2370
        """Convert one version of one file.
 
2371
 
 
2372
        The file needs to be added into the weave if it is a merge
 
2373
        of >=2 parents or if it's changed from its parent.
 
2374
        """
 
2375
        file_id = ie.file_id
 
2376
        rev_id = rev.revision_id
 
2377
        w = self.text_weaves.get(file_id)
 
2378
        if w is None:
 
2379
            w = Weave(file_id)
 
2380
            self.text_weaves[file_id] = w
 
2381
        text_changed = False
 
2382
        parent_candiate_entries = ie.parent_candidates(parent_invs)
 
2383
        heads = graph.Graph(self).heads(parent_candiate_entries.keys())
 
2384
        # XXX: Note that this is unordered - and this is tolerable because
 
2385
        # the previous code was also unordered.
 
2386
        previous_entries = dict((head, parent_candiate_entries[head]) for head
 
2387
            in heads)
 
2388
        self.snapshot_ie(previous_entries, ie, w, rev_id)
 
2389
 
 
2390
    def get_parent_map(self, revision_ids):
 
2391
        """See graph.StackedParentsProvider.get_parent_map"""
 
2392
        return dict((revision_id, self.revisions[revision_id])
 
2393
                    for revision_id in revision_ids
 
2394
                     if revision_id in self.revisions)
 
2395
 
 
2396
    def snapshot_ie(self, previous_revisions, ie, w, rev_id):
 
2397
        # TODO: convert this logic, which is ~= snapshot to
 
2398
        # a call to:. This needs the path figured out. rather than a work_tree
 
2399
        # a v4 revision_tree can be given, or something that looks enough like
 
2400
        # one to give the file content to the entry if it needs it.
 
2401
        # and we need something that looks like a weave store for snapshot to
 
2402
        # save against.
 
2403
        #ie.snapshot(rev, PATH, previous_revisions, REVISION_TREE, InMemoryWeaveStore(self.text_weaves))
 
2404
        if len(previous_revisions) == 1:
 
2405
            previous_ie = previous_revisions.values()[0]
 
2406
            if ie._unchanged(previous_ie):
 
2407
                ie.revision = previous_ie.revision
 
2408
                return
 
2409
        if ie.has_text():
 
2410
            f = self.branch.repository._text_store.get(ie.text_id)
 
2411
            try:
 
2412
                file_lines = f.readlines()
 
2413
            finally:
 
2414
                f.close()
 
2415
            w.add_lines(rev_id, previous_revisions, file_lines)
 
2416
            self.text_count += 1
 
2417
        else:
 
2418
            w.add_lines(rev_id, previous_revisions, [])
 
2419
        ie.revision = rev_id
 
2420
 
 
2421
    def _make_order(self):
 
2422
        """Return a suitable order for importing revisions.
 
2423
 
 
2424
        The order must be such that an revision is imported after all
 
2425
        its (present) parents.
 
2426
        """
 
2427
        todo = set(self.revisions.keys())
 
2428
        done = self.absent_revisions.copy()
 
2429
        order = []
 
2430
        while todo:
 
2431
            # scan through looking for a revision whose parents
 
2432
            # are all done
 
2433
            for rev_id in sorted(list(todo)):
 
2434
                rev = self.revisions[rev_id]
 
2435
                parent_ids = set(rev.parent_ids)
 
2436
                if parent_ids.issubset(done):
 
2437
                    # can take this one now
 
2438
                    order.append(rev_id)
 
2439
                    todo.remove(rev_id)
 
2440
                    done.add(rev_id)
 
2441
        return order
 
2442
 
 
2443
 
 
2444
class ConvertBzrDir5To6(Converter):
 
2445
    """Converts format 5 bzr dirs to format 6."""
 
2446
 
 
2447
    def convert(self, to_convert, pb):
 
2448
        """See Converter.convert()."""
 
2449
        self.bzrdir = to_convert
 
2450
        pb = ui.ui_factory.nested_progress_bar()
 
2451
        try:
 
2452
            ui.ui_factory.note('starting upgrade from format 5 to 6')
 
2453
            self._convert_to_prefixed()
 
2454
            return BzrDir.open(self.bzrdir.user_url)
 
2455
        finally:
 
2456
            pb.finished()
 
2457
 
 
2458
    def _convert_to_prefixed(self):
 
2459
        from bzrlib.store import TransportStore
 
2460
        self.bzrdir.transport.delete('branch-format')
 
2461
        for store_name in ["weaves", "revision-store"]:
 
2462
            ui.ui_factory.note("adding prefixes to %s" % store_name)
 
2463
            store_transport = self.bzrdir.transport.clone(store_name)
 
2464
            store = TransportStore(store_transport, prefixed=True)
 
2465
            for urlfilename in store_transport.list_dir('.'):
 
2466
                filename = urlutils.unescape(urlfilename)
 
2467
                if (filename.endswith(".weave") or
 
2468
                    filename.endswith(".gz") or
 
2469
                    filename.endswith(".sig")):
 
2470
                    file_id, suffix = os.path.splitext(filename)
 
2471
                else:
 
2472
                    file_id = filename
 
2473
                    suffix = ''
 
2474
                new_name = store._mapper.map((file_id,)) + suffix
 
2475
                # FIXME keep track of the dirs made RBC 20060121
 
2476
                try:
 
2477
                    store_transport.move(filename, new_name)
 
2478
                except errors.NoSuchFile: # catches missing dirs strangely enough
 
2479
                    store_transport.mkdir(osutils.dirname(new_name))
 
2480
                    store_transport.move(filename, new_name)
 
2481
        self.bzrdir.transport.put_bytes(
 
2482
            'branch-format',
 
2483
            BzrDirFormat6().get_format_string(),
 
2484
            mode=self.bzrdir._get_file_mode())
 
2485
 
 
2486
 
 
2487
class ConvertBzrDir6ToMeta(Converter):
 
2488
    """Converts format 6 bzr dirs to metadirs."""
 
2489
 
 
2490
    def convert(self, to_convert, pb):
 
2491
        """See Converter.convert()."""
 
2492
        from bzrlib.repofmt.weaverepo import RepositoryFormat7
 
2493
        from bzrlib.branch import BzrBranchFormat5
 
2494
        self.bzrdir = to_convert
 
2495
        self.pb = ui.ui_factory.nested_progress_bar()
 
2496
        self.count = 0
 
2497
        self.total = 20 # the steps we know about
 
2498
        self.garbage_inventories = []
 
2499
        self.dir_mode = self.bzrdir._get_dir_mode()
 
2500
        self.file_mode = self.bzrdir._get_file_mode()
 
2501
 
 
2502
        ui.ui_factory.note('starting upgrade from format 6 to metadir')
 
2503
        self.bzrdir.transport.put_bytes(
 
2504
                'branch-format',
 
2505
                "Converting to format 6",
 
2506
                mode=self.file_mode)
 
2507
        # its faster to move specific files around than to open and use the apis...
 
2508
        # first off, nuke ancestry.weave, it was never used.
 
2509
        try:
 
2510
            self.step('Removing ancestry.weave')
 
2511
            self.bzrdir.transport.delete('ancestry.weave')
 
2512
        except errors.NoSuchFile:
 
2513
            pass
 
2514
        # find out whats there
 
2515
        self.step('Finding branch files')
 
2516
        last_revision = self.bzrdir.open_branch().last_revision()
 
2517
        bzrcontents = self.bzrdir.transport.list_dir('.')
 
2518
        for name in bzrcontents:
 
2519
            if name.startswith('basis-inventory.'):
 
2520
                self.garbage_inventories.append(name)
 
2521
        # create new directories for repository, working tree and branch
 
2522
        repository_names = [('inventory.weave', True),
 
2523
                            ('revision-store', True),
 
2524
                            ('weaves', True)]
 
2525
        self.step('Upgrading repository  ')
 
2526
        self.bzrdir.transport.mkdir('repository', mode=self.dir_mode)
 
2527
        self.make_lock('repository')
 
2528
        # we hard code the formats here because we are converting into
 
2529
        # the meta format. The meta format upgrader can take this to a
 
2530
        # future format within each component.
 
2531
        self.put_format('repository', RepositoryFormat7())
 
2532
        for entry in repository_names:
 
2533
            self.move_entry('repository', entry)
 
2534
 
 
2535
        self.step('Upgrading branch      ')
 
2536
        self.bzrdir.transport.mkdir('branch', mode=self.dir_mode)
 
2537
        self.make_lock('branch')
 
2538
        self.put_format('branch', BzrBranchFormat5())
 
2539
        branch_files = [('revision-history', True),
 
2540
                        ('branch-name', True),
 
2541
                        ('parent', False)]
 
2542
        for entry in branch_files:
 
2543
            self.move_entry('branch', entry)
 
2544
 
 
2545
        checkout_files = [('pending-merges', True),
 
2546
                          ('inventory', True),
 
2547
                          ('stat-cache', False)]
 
2548
        # If a mandatory checkout file is not present, the branch does not have
 
2549
        # a functional checkout. Do not create a checkout in the converted
 
2550
        # branch.
 
2551
        for name, mandatory in checkout_files:
 
2552
            if mandatory and name not in bzrcontents:
 
2553
                has_checkout = False
 
2554
                break
 
2555
        else:
 
2556
            has_checkout = True
 
2557
        if not has_checkout:
 
2558
            ui.ui_factory.note('No working tree.')
 
2559
            # If some checkout files are there, we may as well get rid of them.
 
2560
            for name, mandatory in checkout_files:
 
2561
                if name in bzrcontents:
 
2562
                    self.bzrdir.transport.delete(name)
 
2563
        else:
 
2564
            from bzrlib.workingtree import WorkingTreeFormat3
 
2565
            self.step('Upgrading working tree')
 
2566
            self.bzrdir.transport.mkdir('checkout', mode=self.dir_mode)
 
2567
            self.make_lock('checkout')
 
2568
            self.put_format(
 
2569
                'checkout', WorkingTreeFormat3())
 
2570
            self.bzrdir.transport.delete_multi(
 
2571
                self.garbage_inventories, self.pb)
 
2572
            for entry in checkout_files:
 
2573
                self.move_entry('checkout', entry)
 
2574
            if last_revision is not None:
 
2575
                self.bzrdir.transport.put_bytes(
 
2576
                    'checkout/last-revision', last_revision)
 
2577
        self.bzrdir.transport.put_bytes(
 
2578
            'branch-format',
 
2579
            BzrDirMetaFormat1().get_format_string(),
 
2580
            mode=self.file_mode)
 
2581
        self.pb.finished()
 
2582
        return BzrDir.open(self.bzrdir.user_url)
 
2583
 
 
2584
    def make_lock(self, name):
 
2585
        """Make a lock for the new control dir name."""
 
2586
        self.step('Make %s lock' % name)
 
2587
        ld = lockdir.LockDir(self.bzrdir.transport,
 
2588
                             '%s/lock' % name,
 
2589
                             file_modebits=self.file_mode,
 
2590
                             dir_modebits=self.dir_mode)
 
2591
        ld.create()
 
2592
 
 
2593
    def move_entry(self, new_dir, entry):
 
2594
        """Move then entry name into new_dir."""
 
2595
        name = entry[0]
 
2596
        mandatory = entry[1]
 
2597
        self.step('Moving %s' % name)
 
2598
        try:
 
2599
            self.bzrdir.transport.move(name, '%s/%s' % (new_dir, name))
 
2600
        except errors.NoSuchFile:
 
2601
            if mandatory:
 
2602
                raise
 
2603
 
 
2604
    def put_format(self, dirname, format):
 
2605
        self.bzrdir.transport.put_bytes('%s/format' % dirname,
 
2606
            format.get_format_string(),
 
2607
            self.file_mode)
 
2608
 
 
2609
 
 
2610
class ConvertMetaToMeta(Converter):
1835
2611
    """Converts the components of metadirs."""
1836
2612
 
1837
2613
    def __init__(self, target_format):
1855
2631
        else:
1856
2632
            if not isinstance(repo._format, self.target_format.repository_format.__class__):
1857
2633
                from bzrlib.repository import CopyConverter
1858
 
                ui.ui_factory.note(gettext('starting repository conversion'))
 
2634
                ui.ui_factory.note('starting repository conversion')
1859
2635
                converter = CopyConverter(self.target_format.repository_format)
1860
2636
                converter.convert(repo, pb)
1861
2637
        for branch in self.bzrdir.list_branches():
1862
2638
            # TODO: conversions of Branch and Tree should be done by
1863
2639
            # InterXFormat lookups/some sort of registry.
1864
2640
            # Avoid circular imports
 
2641
            from bzrlib import branch as _mod_branch
1865
2642
            old = branch._format.__class__
1866
2643
            new = self.target_format.get_branch_format().__class__
1867
2644
            while old != new:
1890
2667
        else:
1891
2668
            # TODO: conversions of Branch and Tree should be done by
1892
2669
            # InterXFormat lookups
1893
 
            if (isinstance(tree, workingtree_3.WorkingTree3) and
 
2670
            if (isinstance(tree, workingtree.WorkingTree3) and
1894
2671
                not isinstance(tree, workingtree_4.DirStateWorkingTree) and
1895
2672
                isinstance(self.target_format.workingtree_format,
1896
2673
                    workingtree_4.DirStateWorkingTreeFormat)):
1909
2686
        return to_convert
1910
2687
 
1911
2688
 
 
2689
# This is not in remote.py because it's relatively small, and needs to be
 
2690
# registered. Putting it in remote.py creates a circular import problem.
 
2691
# we can make it a lazy object if the control formats is turned into something
 
2692
# like a registry.
 
2693
class RemoteBzrDirFormat(BzrDirMetaFormat1):
 
2694
    """Format representing bzrdirs accessed via a smart server"""
 
2695
 
 
2696
    supports_workingtrees = False
 
2697
 
 
2698
    def __init__(self):
 
2699
        BzrDirMetaFormat1.__init__(self)
 
2700
        # XXX: It's a bit ugly that the network name is here, because we'd
 
2701
        # like to believe that format objects are stateless or at least
 
2702
        # immutable,  However, we do at least avoid mutating the name after
 
2703
        # it's returned.  See <https://bugs.launchpad.net/bzr/+bug/504102>
 
2704
        self._network_name = None
 
2705
 
 
2706
    def __repr__(self):
 
2707
        return "%s(_network_name=%r)" % (self.__class__.__name__,
 
2708
            self._network_name)
 
2709
 
 
2710
    def get_format_description(self):
 
2711
        if self._network_name:
 
2712
            real_format = controldir.network_format_registry.get(self._network_name)
 
2713
            return 'Remote: ' + real_format.get_format_description()
 
2714
        return 'bzr remote bzrdir'
 
2715
 
 
2716
    def get_format_string(self):
 
2717
        raise NotImplementedError(self.get_format_string)
 
2718
 
 
2719
    def network_name(self):
 
2720
        if self._network_name:
 
2721
            return self._network_name
 
2722
        else:
 
2723
            raise AssertionError("No network name set.")
 
2724
 
 
2725
    def initialize_on_transport(self, transport):
 
2726
        try:
 
2727
            # hand off the request to the smart server
 
2728
            client_medium = transport.get_smart_medium()
 
2729
        except errors.NoSmartMedium:
 
2730
            # TODO: lookup the local format from a server hint.
 
2731
            local_dir_format = BzrDirMetaFormat1()
 
2732
            return local_dir_format.initialize_on_transport(transport)
 
2733
        client = _SmartClient(client_medium)
 
2734
        path = client.remote_path_from_transport(transport)
 
2735
        try:
 
2736
            response = client.call('BzrDirFormat.initialize', path)
 
2737
        except errors.ErrorFromSmartServer, err:
 
2738
            remote._translate_error(err, path=path)
 
2739
        if response[0] != 'ok':
 
2740
            raise errors.SmartProtocolError('unexpected response code %s' % (response,))
 
2741
        format = RemoteBzrDirFormat()
 
2742
        self._supply_sub_formats_to(format)
 
2743
        return remote.RemoteBzrDir(transport, format)
 
2744
 
 
2745
    def parse_NoneTrueFalse(self, arg):
 
2746
        if not arg:
 
2747
            return None
 
2748
        if arg == 'False':
 
2749
            return False
 
2750
        if arg == 'True':
 
2751
            return True
 
2752
        raise AssertionError("invalid arg %r" % arg)
 
2753
 
 
2754
    def _serialize_NoneTrueFalse(self, arg):
 
2755
        if arg is False:
 
2756
            return 'False'
 
2757
        if arg:
 
2758
            return 'True'
 
2759
        return ''
 
2760
 
 
2761
    def _serialize_NoneString(self, arg):
 
2762
        return arg or ''
 
2763
 
 
2764
    def initialize_on_transport_ex(self, transport, use_existing_dir=False,
 
2765
        create_prefix=False, force_new_repo=False, stacked_on=None,
 
2766
        stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
 
2767
        shared_repo=False):
 
2768
        try:
 
2769
            # hand off the request to the smart server
 
2770
            client_medium = transport.get_smart_medium()
 
2771
        except errors.NoSmartMedium:
 
2772
            do_vfs = True
 
2773
        else:
 
2774
            # Decline to open it if the server doesn't support our required
 
2775
            # version (3) so that the VFS-based transport will do it.
 
2776
            if client_medium.should_probe():
 
2777
                try:
 
2778
                    server_version = client_medium.protocol_version()
 
2779
                    if server_version != '2':
 
2780
                        do_vfs = True
 
2781
                    else:
 
2782
                        do_vfs = False
 
2783
                except errors.SmartProtocolError:
 
2784
                    # Apparently there's no usable smart server there, even though
 
2785
                    # the medium supports the smart protocol.
 
2786
                    do_vfs = True
 
2787
            else:
 
2788
                do_vfs = False
 
2789
        if not do_vfs:
 
2790
            client = _SmartClient(client_medium)
 
2791
            path = client.remote_path_from_transport(transport)
 
2792
            if client_medium._is_remote_before((1, 16)):
 
2793
                do_vfs = True
 
2794
        if do_vfs:
 
2795
            # TODO: lookup the local format from a server hint.
 
2796
            local_dir_format = BzrDirMetaFormat1()
 
2797
            self._supply_sub_formats_to(local_dir_format)
 
2798
            return local_dir_format.initialize_on_transport_ex(transport,
 
2799
                use_existing_dir=use_existing_dir, create_prefix=create_prefix,
 
2800
                force_new_repo=force_new_repo, stacked_on=stacked_on,
 
2801
                stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
 
2802
                make_working_trees=make_working_trees, shared_repo=shared_repo,
 
2803
                vfs_only=True)
 
2804
        return self._initialize_on_transport_ex_rpc(client, path, transport,
 
2805
            use_existing_dir, create_prefix, force_new_repo, stacked_on,
 
2806
            stack_on_pwd, repo_format_name, make_working_trees, shared_repo)
 
2807
 
 
2808
    def _initialize_on_transport_ex_rpc(self, client, path, transport,
 
2809
        use_existing_dir, create_prefix, force_new_repo, stacked_on,
 
2810
        stack_on_pwd, repo_format_name, make_working_trees, shared_repo):
 
2811
        args = []
 
2812
        args.append(self._serialize_NoneTrueFalse(use_existing_dir))
 
2813
        args.append(self._serialize_NoneTrueFalse(create_prefix))
 
2814
        args.append(self._serialize_NoneTrueFalse(force_new_repo))
 
2815
        args.append(self._serialize_NoneString(stacked_on))
 
2816
        # stack_on_pwd is often/usually our transport
 
2817
        if stack_on_pwd:
 
2818
            try:
 
2819
                stack_on_pwd = transport.relpath(stack_on_pwd)
 
2820
                if not stack_on_pwd:
 
2821
                    stack_on_pwd = '.'
 
2822
            except errors.PathNotChild:
 
2823
                pass
 
2824
        args.append(self._serialize_NoneString(stack_on_pwd))
 
2825
        args.append(self._serialize_NoneString(repo_format_name))
 
2826
        args.append(self._serialize_NoneTrueFalse(make_working_trees))
 
2827
        args.append(self._serialize_NoneTrueFalse(shared_repo))
 
2828
        request_network_name = self._network_name or \
 
2829
            BzrDirFormat.get_default_format().network_name()
 
2830
        try:
 
2831
            response = client.call('BzrDirFormat.initialize_ex_1.16',
 
2832
                request_network_name, path, *args)
 
2833
        except errors.UnknownSmartMethod:
 
2834
            client._medium._remember_remote_is_before((1,16))
 
2835
            local_dir_format = BzrDirMetaFormat1()
 
2836
            self._supply_sub_formats_to(local_dir_format)
 
2837
            return local_dir_format.initialize_on_transport_ex(transport,
 
2838
                use_existing_dir=use_existing_dir, create_prefix=create_prefix,
 
2839
                force_new_repo=force_new_repo, stacked_on=stacked_on,
 
2840
                stack_on_pwd=stack_on_pwd, repo_format_name=repo_format_name,
 
2841
                make_working_trees=make_working_trees, shared_repo=shared_repo,
 
2842
                vfs_only=True)
 
2843
        except errors.ErrorFromSmartServer, err:
 
2844
            remote._translate_error(err, path=path)
 
2845
        repo_path = response[0]
 
2846
        bzrdir_name = response[6]
 
2847
        require_stacking = response[7]
 
2848
        require_stacking = self.parse_NoneTrueFalse(require_stacking)
 
2849
        format = RemoteBzrDirFormat()
 
2850
        format._network_name = bzrdir_name
 
2851
        self._supply_sub_formats_to(format)
 
2852
        bzrdir = remote.RemoteBzrDir(transport, format, _client=client)
 
2853
        if repo_path:
 
2854
            repo_format = remote.response_tuple_to_repo_format(response[1:])
 
2855
            if repo_path == '.':
 
2856
                repo_path = ''
 
2857
            if repo_path:
 
2858
                repo_bzrdir_format = RemoteBzrDirFormat()
 
2859
                repo_bzrdir_format._network_name = response[5]
 
2860
                repo_bzr = remote.RemoteBzrDir(transport.clone(repo_path),
 
2861
                    repo_bzrdir_format)
 
2862
            else:
 
2863
                repo_bzr = bzrdir
 
2864
            final_stack = response[8] or None
 
2865
            final_stack_pwd = response[9] or None
 
2866
            if final_stack_pwd:
 
2867
                final_stack_pwd = urlutils.join(
 
2868
                    transport.base, final_stack_pwd)
 
2869
            remote_repo = remote.RemoteRepository(repo_bzr, repo_format)
 
2870
            if len(response) > 10:
 
2871
                # Updated server verb that locks remotely.
 
2872
                repo_lock_token = response[10] or None
 
2873
                remote_repo.lock_write(repo_lock_token, _skip_rpc=True)
 
2874
                if repo_lock_token:
 
2875
                    remote_repo.dont_leave_lock_in_place()
 
2876
            else:
 
2877
                remote_repo.lock_write()
 
2878
            policy = UseExistingRepository(remote_repo, final_stack,
 
2879
                final_stack_pwd, require_stacking)
 
2880
            policy.acquire_repository()
 
2881
        else:
 
2882
            remote_repo = None
 
2883
            policy = None
 
2884
        bzrdir._format.set_branch_format(self.get_branch_format())
 
2885
        if require_stacking:
 
2886
            # The repo has already been created, but we need to make sure that
 
2887
            # we'll make a stackable branch.
 
2888
            bzrdir._format.require_stacking(_skip_repo=True)
 
2889
        return remote_repo, bzrdir, require_stacking, policy
 
2890
 
 
2891
    def _open(self, transport):
 
2892
        return remote.RemoteBzrDir(transport, self)
 
2893
 
 
2894
    def __eq__(self, other):
 
2895
        if not isinstance(other, RemoteBzrDirFormat):
 
2896
            return False
 
2897
        return self.get_format_description() == other.get_format_description()
 
2898
 
 
2899
    def __return_repository_format(self):
 
2900
        # Always return a RemoteRepositoryFormat object, but if a specific bzr
 
2901
        # repository format has been asked for, tell the RemoteRepositoryFormat
 
2902
        # that it should use that for init() etc.
 
2903
        result = remote.RemoteRepositoryFormat()
 
2904
        custom_format = getattr(self, '_repository_format', None)
 
2905
        if custom_format:
 
2906
            if isinstance(custom_format, remote.RemoteRepositoryFormat):
 
2907
                return custom_format
 
2908
            else:
 
2909
                # We will use the custom format to create repositories over the
 
2910
                # wire; expose its details like rich_root_data for code to
 
2911
                # query
 
2912
                result._custom_format = custom_format
 
2913
        return result
 
2914
 
 
2915
    def get_branch_format(self):
 
2916
        result = BzrDirMetaFormat1.get_branch_format(self)
 
2917
        if not isinstance(result, remote.RemoteBranchFormat):
 
2918
            new_result = remote.RemoteBranchFormat()
 
2919
            new_result._custom_format = result
 
2920
            # cache the result
 
2921
            self.set_branch_format(new_result)
 
2922
            result = new_result
 
2923
        return result
 
2924
 
 
2925
    repository_format = property(__return_repository_format,
 
2926
        BzrDirMetaFormat1._set_repository_format) #.im_func)
 
2927
 
 
2928
 
1912
2929
controldir.ControlDirFormat.register_server_prober(RemoteBzrProber)
1913
2930
 
1914
2931
 
1996
3013
 
1997
3014
        Implementations may create a new repository or use a pre-exising
1998
3015
        repository.
1999
 
 
2000
3016
        :param make_working_trees: If creating a repository, set
2001
3017
            make_working_trees to this value (if non-None)
2002
3018
        :param shared: If creating a repository, make it shared if True
2011
3027
 
2012
3028
    def __init__(self, bzrdir, stack_on=None, stack_on_pwd=None,
2013
3029
                 require_stacking=False):
2014
 
        """Constructor.
2015
 
 
 
3030
        """
 
3031
        Constructor.
2016
3032
        :param bzrdir: The bzrdir to create the repository on.
2017
3033
        :param stack_on: A location to stack on
2018
3034
        :param stack_on_pwd: If stack_on is relative, the location it is
2034
3050
                                    possible_transports=[self._bzrdir.root_transport])
2035
3051
            if not self._require_stacking:
2036
3052
                # We have picked up automatic stacking somewhere.
2037
 
                note(gettext('Using default stacking branch {0} at {1}').format(
2038
 
                    self._stack_on, self._stack_on_pwd))
 
3053
                note('Using default stacking branch %s at %s', self._stack_on,
 
3054
                    self._stack_on_pwd)
2039
3055
        repository = self._bzrdir.create_repository(shared=shared)
2040
3056
        self._add_fallback(repository,
2041
3057
                           possible_transports=[self._bzrdir.transport])
2114
3130
    registry.register(key, helper, help, native, deprecated, hidden,
2115
3131
        experimental, alias)
2116
3132
 
 
3133
# The pre-0.8 formats have their repository format network name registered in
 
3134
# repository.py. MetaDir formats have their repository format network name
 
3135
# inferred from their disk format string.
 
3136
controldir.format_registry.register('weave', BzrDirFormat6,
 
3137
    'Pre-0.8 format.  Slower than knit and does not'
 
3138
    ' support checkouts or shared repositories.',
 
3139
    hidden=True,
 
3140
    deprecated=True)
 
3141
register_metadir(controldir.format_registry, 'metaweave',
 
3142
    'bzrlib.repofmt.weaverepo.RepositoryFormat7',
 
3143
    'Transitional format in 0.8.  Slower than knit.',
 
3144
    branch_format='bzrlib.branch.BzrBranchFormat5',
 
3145
    tree_format='bzrlib.workingtree.WorkingTreeFormat3',
 
3146
    hidden=True,
 
3147
    deprecated=True)
2117
3148
register_metadir(controldir.format_registry, 'knit',
2118
3149
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
2119
3150
    'Format using knits.  Recommended for interoperation with bzr <= 0.14.',
2120
3151
    branch_format='bzrlib.branch.BzrBranchFormat5',
2121
 
    tree_format='bzrlib.workingtree_3.WorkingTreeFormat3',
 
3152
    tree_format='bzrlib.workingtree.WorkingTreeFormat3',
2122
3153
    hidden=True,
2123
3154
    deprecated=True)
2124
3155
register_metadir(controldir.format_registry, 'dirstate',
2126
3157
    help='New in 0.15: Fast local operations. Compatible with bzr 0.8 and '
2127
3158
        'above when accessed over the network.',
2128
3159
    branch_format='bzrlib.branch.BzrBranchFormat5',
2129
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
 
3160
    # this uses bzrlib.workingtree.WorkingTreeFormat4 because importing
 
3161
    # directly from workingtree_4 triggers a circular import.
 
3162
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2130
3163
    hidden=True,
2131
3164
    deprecated=True)
2132
3165
register_metadir(controldir.format_registry, 'dirstate-tags',
2135
3168
        'network operations. Additionally adds support for tags.'
2136
3169
        ' Incompatible with bzr < 0.15.',
2137
3170
    branch_format='bzrlib.branch.BzrBranchFormat6',
2138
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
 
3171
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2139
3172
    hidden=True,
2140
3173
    deprecated=True)
2141
3174
register_metadir(controldir.format_registry, 'rich-root',
2143
3176
    help='New in 1.0.  Better handling of tree roots.  Incompatible with'
2144
3177
        ' bzr < 1.0.',
2145
3178
    branch_format='bzrlib.branch.BzrBranchFormat6',
2146
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
 
3179
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2147
3180
    hidden=True,
2148
3181
    deprecated=True)
2149
3182
register_metadir(controldir.format_registry, 'dirstate-with-subtree',
2152
3185
        'network operations. Additionally adds support for versioning nested '
2153
3186
        'bzr branches. Incompatible with bzr < 0.15.',
2154
3187
    branch_format='bzrlib.branch.BzrBranchFormat6',
2155
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
 
3188
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2156
3189
    experimental=True,
2157
3190
    hidden=True,
2158
3191
    )
2159
3192
register_metadir(controldir.format_registry, 'pack-0.92',
2160
 
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack1',
 
3193
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack1',
2161
3194
    help='New in 0.92: Pack-based format with data compatible with '
2162
3195
        'dirstate-tags format repositories. Interoperates with '
2163
3196
        'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
2164
3197
        ,
2165
3198
    branch_format='bzrlib.branch.BzrBranchFormat6',
2166
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
 
3199
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2167
3200
    )
2168
3201
register_metadir(controldir.format_registry, 'pack-0.92-subtree',
2169
 
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack3',
 
3202
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack3',
2170
3203
    help='New in 0.92: Pack-based format with data compatible with '
2171
3204
        'dirstate-with-subtree format repositories. Interoperates with '
2172
3205
        'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
2173
3206
        ,
2174
3207
    branch_format='bzrlib.branch.BzrBranchFormat6',
2175
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
 
3208
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2176
3209
    hidden=True,
2177
3210
    experimental=True,
2178
3211
    )
2179
3212
register_metadir(controldir.format_registry, 'rich-root-pack',
2180
 
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack4',
 
3213
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack4',
2181
3214
    help='New in 1.0: A variant of pack-0.92 that supports rich-root data '
2182
3215
         '(needed for bzr-svn and bzr-git).',
2183
3216
    branch_format='bzrlib.branch.BzrBranchFormat6',
2184
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
 
3217
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2185
3218
    hidden=True,
2186
3219
    )
2187
3220
register_metadir(controldir.format_registry, '1.6',
2188
 
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack5',
 
3221
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5',
2189
3222
    help='A format that allows a branch to indicate that there is another '
2190
3223
         '(stacked) repository that should be used to access data that is '
2191
3224
         'not present locally.',
2192
3225
    branch_format='bzrlib.branch.BzrBranchFormat7',
2193
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
 
3226
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2194
3227
    hidden=True,
2195
3228
    )
2196
3229
register_metadir(controldir.format_registry, '1.6.1-rich-root',
2197
 
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack5RichRoot',
 
3230
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5RichRoot',
2198
3231
    help='A variant of 1.6 that supports rich-root data '
2199
3232
         '(needed for bzr-svn and bzr-git).',
2200
3233
    branch_format='bzrlib.branch.BzrBranchFormat7',
2201
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
 
3234
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2202
3235
    hidden=True,
2203
3236
    )
2204
3237
register_metadir(controldir.format_registry, '1.9',
2205
 
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack6',
 
3238
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
2206
3239
    help='A repository format using B+tree indexes. These indexes '
2207
3240
         'are smaller in size, have smarter caching and provide faster '
2208
3241
         'performance for most operations.',
2209
3242
    branch_format='bzrlib.branch.BzrBranchFormat7',
2210
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
 
3243
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2211
3244
    hidden=True,
2212
3245
    )
2213
3246
register_metadir(controldir.format_registry, '1.9-rich-root',
2214
 
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack6RichRoot',
 
3247
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
2215
3248
    help='A variant of 1.9 that supports rich-root data '
2216
3249
         '(needed for bzr-svn and bzr-git).',
2217
3250
    branch_format='bzrlib.branch.BzrBranchFormat7',
2218
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
 
3251
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
2219
3252
    hidden=True,
2220
3253
    )
2221
3254
register_metadir(controldir.format_registry, '1.14',
2222
 
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack6',
 
3255
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
2223
3256
    help='A working-tree format that supports content filtering.',
2224
3257
    branch_format='bzrlib.branch.BzrBranchFormat7',
2225
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat5',
 
3258
    tree_format='bzrlib.workingtree.WorkingTreeFormat5',
2226
3259
    )
2227
3260
register_metadir(controldir.format_registry, '1.14-rich-root',
2228
 
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack6RichRoot',
 
3261
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
2229
3262
    help='A variant of 1.14 that supports rich-root data '
2230
3263
         '(needed for bzr-svn and bzr-git).',
2231
3264
    branch_format='bzrlib.branch.BzrBranchFormat7',
2232
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat5',
 
3265
    tree_format='bzrlib.workingtree.WorkingTreeFormat5',
2233
3266
    )
2234
3267
# The following un-numbered 'development' formats should always just be aliases.
2235
3268
register_metadir(controldir.format_registry, 'development-subtree',
2241
3274
        'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
2242
3275
        'before use.',
2243
3276
    branch_format='bzrlib.branch.BzrBranchFormat7',
2244
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat6',
 
3277
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
2245
3278
    experimental=True,
2246
3279
    hidden=True,
2247
3280
    alias=False, # Restore to being an alias when an actual development subtree format is added
2249
3282
                 # chk based subtree format.
2250
3283
    )
2251
3284
register_metadir(controldir.format_registry, 'development5-subtree',
2252
 
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatPackDevelopment2Subtree',
 
3285
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment2Subtree',
2253
3286
    help='Development format, subtree variant. Can convert data to and '
2254
3287
        'from pack-0.92-subtree (and anything compatible with '
2255
3288
        'pack-0.92-subtree) format repositories. Repositories and branches in '
2257
3290
        'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
2258
3291
        'before use.',
2259
3292
    branch_format='bzrlib.branch.BzrBranchFormat7',
2260
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat6',
 
3293
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
2261
3294
    experimental=True,
2262
3295
    hidden=True,
2263
3296
    alias=False,
2274
3307
        # 'storage in packs, 255-way hashed CHK inventory, bencode revision, group compress, '
2275
3308
        # 'rich roots. Supported by bzr 1.16 and later.',
2276
3309
    branch_format='bzrlib.branch.BzrBranchFormat7',
2277
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat6',
 
3310
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
2278
3311
    experimental=False,
2279
3312
    )
2280
3313
 
2283
3316
register_metadir(controldir.format_registry, 'default-rich-root',
2284
3317
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2a',
2285
3318
    branch_format='bzrlib.branch.BzrBranchFormat7',
2286
 
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat6',
 
3319
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
2287
3320
    alias=True,
2288
3321
    hidden=True,
2289
3322
    help='Same as 2a.')
2290
3323
 
2291
3324
# The current format that is made on 'bzr init'.
2292
 
format_name = config.GlobalStack().get('default_format')
2293
 
controldir.format_registry.set_default(format_name)
 
3325
format_name = config.GlobalConfig().get_user_option('default_format')
 
3326
if format_name is None:
 
3327
    controldir.format_registry.set_default('2a')
 
3328
else:
 
3329
    controldir.format_registry.set_default(format_name)
2294
3330
 
2295
3331
# XXX 2010-08-20 JRV: There is still a lot of code relying on
2296
3332
# bzrlib.bzrdir.format_registry existing. When BzrDir.create/BzrDir.open/etc