~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2010-08-21 17:09:54 UTC
  • mfrom: (5385.1.1 trivial-NEWS-fileencoding)
  • Revision ID: pqm@pqm.ubuntu.com-20100821170954-efrj80bvw56s5mzc
(parthm) Remove 'encoding' option from NEWS modeline as its an error in Vim
 7.3+ (Parth Malwankar)

Show diffs side-by-side

added added

removed removed

Lines of Context:
34
34
from bzrlib.lazy_import import lazy_import
35
35
lazy_import(globals(), """
36
36
from stat import S_ISDIR
 
37
import textwrap
37
38
 
38
39
import bzrlib
39
40
from bzrlib import (
40
41
    branch,
41
42
    config,
42
 
    controldir,
43
43
    errors,
44
44
    graph,
45
45
    lockable_files,
86
86
    registry,
87
87
    symbol_versioning,
88
88
    )
89
 
 
90
 
 
91
 
class BzrDir(controldir.ControlDir):
 
89
    
 
90
    
 
91
class ControlComponent(object):
 
92
    """Abstract base class for control directory components.
 
93
    
 
94
    This provides interfaces that are common across bzrdirs, 
 
95
    repositories, branches, and workingtree control directories.
 
96
    
 
97
    They all expose two urls and transports: the *user* URL is the 
 
98
    one that stops above the control directory (eg .bzr) and that 
 
99
    should normally be used in messages, and the *control* URL is
 
100
    under that in eg .bzr/checkout and is used to read the control
 
101
    files.
 
102
    
 
103
    This can be used as a mixin and is intended to fit with 
 
104
    foreign formats.
 
105
    """
 
106
    
 
107
    @property
 
108
    def control_transport(self):
 
109
        raise NotImplementedError
 
110
   
 
111
    @property
 
112
    def control_url(self):
 
113
        return self.control_transport.base
 
114
    
 
115
    @property
 
116
    def user_transport(self):
 
117
        raise NotImplementedError
 
118
        
 
119
    @property
 
120
    def user_url(self):
 
121
        return self.user_transport.base
 
122
    
 
123
 
 
124
class BzrDir(ControlComponent):
92
125
    """A .bzr control diretory.
93
126
 
94
127
    BzrDir instances let you create or open any of the things that can be
125
158
                    return
126
159
        thing_to_unlock.break_lock()
127
160
 
 
161
    def can_convert_format(self):
 
162
        """Return true if this bzrdir is one whose format we can convert from."""
 
163
        return True
 
164
 
128
165
    def check_conversion_target(self, target_format):
129
166
        """Check that a bzrdir as a whole can be converted to a new format."""
130
167
        # The only current restriction is that the repository content can be 
204
241
        """
205
242
        # Overview: put together a broad description of what we want to end up
206
243
        # with; then make as few api calls as possible to do it.
207
 
 
 
244
        
208
245
        # We may want to create a repo/branch/tree, if we do so what format
209
246
        # would we want for each:
210
247
        require_stacking = (stacked_on is not None)
211
248
        format = self.cloning_metadir(require_stacking)
212
 
 
 
249
        
213
250
        # Figure out what objects we want:
214
251
        try:
215
252
            local_repo = self.find_repository()
292
329
        t = get_transport(url)
293
330
        t.ensure_base()
294
331
 
 
332
    @classmethod
 
333
    def create(cls, base, format=None, possible_transports=None):
 
334
        """Create a new BzrDir at the url 'base'.
 
335
 
 
336
        :param format: If supplied, the format of branch to create.  If not
 
337
            supplied, the default is used.
 
338
        :param possible_transports: If supplied, a list of transports that
 
339
            can be reused to share a remote connection.
 
340
        """
 
341
        if cls is not BzrDir:
 
342
            raise AssertionError("BzrDir.create always creates the default"
 
343
                " format, not one of %r" % cls)
 
344
        t = get_transport(base, possible_transports)
 
345
        t.ensure_base()
 
346
        if format is None:
 
347
            format = BzrDirFormat.get_default_format()
 
348
        return format.initialize_on_transport(t)
 
349
 
295
350
    @staticmethod
296
351
    def find_bzrdirs(transport, evaluate=None, list_current=None):
297
352
        """Find bzrdirs recursively from current location.
333
388
                for subdir in sorted(subdirs, reverse=True):
334
389
                    pending.append(current_transport.clone(subdir))
335
390
 
 
391
    def list_branches(self):
 
392
        """Return a sequence of all branches local to this control directory.
 
393
 
 
394
        """
 
395
        try:
 
396
            return [self.open_branch()]
 
397
        except (errors.NotBranchError, errors.NoRepositoryPresent):
 
398
            return []
 
399
 
336
400
    @staticmethod
337
401
    def find_branches(transport):
338
402
        """Find all branches under a transport.
361
425
                ret.extend(branches)
362
426
        return ret
363
427
 
 
428
    def destroy_repository(self):
 
429
        """Destroy the repository in this BzrDir"""
 
430
        raise NotImplementedError(self.destroy_repository)
 
431
 
 
432
    def create_branch(self, name=None):
 
433
        """Create a branch in this BzrDir.
 
434
 
 
435
        :param name: Name of the colocated branch to create, None for
 
436
            the default branch.
 
437
 
 
438
        The bzrdir's format will control what branch format is created.
 
439
        For more control see BranchFormatXX.create(a_bzrdir).
 
440
        """
 
441
        raise NotImplementedError(self.create_branch)
 
442
 
 
443
    def destroy_branch(self, name=None):
 
444
        """Destroy a branch in this BzrDir.
 
445
        
 
446
        :param name: Name of the branch to destroy, None for the default 
 
447
            branch.
 
448
        """
 
449
        raise NotImplementedError(self.destroy_branch)
 
450
 
364
451
    @staticmethod
365
452
    def create_branch_and_repo(base, force_new_repo=False, format=None):
366
453
        """Create a new BzrDir, Branch and Repository at the url 'base'.
515
602
                                               format=format).bzrdir
516
603
        return bzrdir.create_workingtree()
517
604
 
 
605
    def create_workingtree(self, revision_id=None, from_branch=None,
 
606
        accelerator_tree=None, hardlink=False):
 
607
        """Create a working tree at this BzrDir.
 
608
 
 
609
        :param revision_id: create it as of this revision id.
 
610
        :param from_branch: override bzrdir branch (for lightweight checkouts)
 
611
        :param accelerator_tree: A tree which can be used for retrieving file
 
612
            contents more quickly than the revision tree, i.e. a workingtree.
 
613
            The revision tree will be used for cases where accelerator_tree's
 
614
            content is different.
 
615
        """
 
616
        raise NotImplementedError(self.create_workingtree)
 
617
 
518
618
    def generate_backup_name(self, base):
519
619
        """Generate a non-existing backup file name based on base."""
520
620
        counter = 1
570
670
                else:
571
671
                    pass
572
672
 
 
673
    def destroy_workingtree(self):
 
674
        """Destroy the working tree at this BzrDir.
 
675
 
 
676
        Formats that do not support this may raise UnsupportedOperation.
 
677
        """
 
678
        raise NotImplementedError(self.destroy_workingtree)
 
679
 
 
680
    def destroy_workingtree_metadata(self):
 
681
        """Destroy the control files for the working tree at this BzrDir.
 
682
 
 
683
        The contents of working tree files are not affected.
 
684
        Formats that do not support this may raise UnsupportedOperation.
 
685
        """
 
686
        raise NotImplementedError(self.destroy_workingtree_metadata)
 
687
 
573
688
    def _find_containing(self, evaluate):
574
689
        """Find something in a containing control directory.
575
690
 
624
739
            raise errors.NoRepositoryPresent(self)
625
740
        return found_repo
626
741
 
 
742
    def get_branch_reference(self, name=None):
 
743
        """Return the referenced URL for the branch in this bzrdir.
 
744
 
 
745
        :param name: Optional colocated branch name
 
746
        :raises NotBranchError: If there is no Branch.
 
747
        :raises NoColocatedBranchSupport: If a branch name was specified
 
748
            but colocated branches are not supported.
 
749
        :return: The URL the branch in this bzrdir references if it is a
 
750
            reference branch, or None for regular branches.
 
751
        """
 
752
        if name is not None:
 
753
            raise errors.NoColocatedBranchSupport(self)
 
754
        return None
 
755
 
 
756
    def get_branch_transport(self, branch_format, name=None):
 
757
        """Get the transport for use by branch format in this BzrDir.
 
758
 
 
759
        Note that bzr dirs that do not support format strings will raise
 
760
        IncompatibleFormat if the branch format they are given has
 
761
        a format string, and vice versa.
 
762
 
 
763
        If branch_format is None, the transport is returned with no
 
764
        checking. If it is not None, then the returned transport is
 
765
        guaranteed to point to an existing directory ready for use.
 
766
        """
 
767
        raise NotImplementedError(self.get_branch_transport)
 
768
 
627
769
    def _find_creation_modes(self):
628
770
        """Determine the appropriate modes for files and directories.
629
771
 
668
810
            self._find_creation_modes()
669
811
        return self._dir_mode
670
812
 
 
813
    def get_repository_transport(self, repository_format):
 
814
        """Get the transport for use by repository format in this BzrDir.
 
815
 
 
816
        Note that bzr dirs that do not support format strings will raise
 
817
        IncompatibleFormat if the repository format they are given has
 
818
        a format string, and vice versa.
 
819
 
 
820
        If repository_format is None, the transport is returned with no
 
821
        checking. If it is not None, then the returned transport is
 
822
        guaranteed to point to an existing directory ready for use.
 
823
        """
 
824
        raise NotImplementedError(self.get_repository_transport)
 
825
 
 
826
    def get_workingtree_transport(self, tree_format):
 
827
        """Get the transport for use by workingtree format in this BzrDir.
 
828
 
 
829
        Note that bzr dirs that do not support format strings will raise
 
830
        IncompatibleFormat if the workingtree format they are given has a
 
831
        format string, and vice versa.
 
832
 
 
833
        If workingtree_format is None, the transport is returned with no
 
834
        checking. If it is not None, then the returned transport is
 
835
        guaranteed to point to an existing directory ready for use.
 
836
        """
 
837
        raise NotImplementedError(self.get_workingtree_transport)
 
838
 
671
839
    def get_config(self):
672
840
        """Get configuration for this BzrDir."""
673
841
        return config.BzrDirConfig(self)
691
859
        self.transport = _transport.clone('.bzr')
692
860
        self.root_transport = _transport
693
861
        self._mode_check_done = False
694
 
 
 
862
        
695
863
    @property 
696
864
    def user_transport(self):
697
865
        return self.root_transport
698
 
 
 
866
        
699
867
    @property
700
868
    def control_transport(self):
701
869
        return self.transport
707
875
 
708
876
        This is true IF and ONLY IF the filename is part of the namespace reserved
709
877
        for bzr control dirs. Currently this is the '.bzr' directory in the root
710
 
        of the root_transport. 
 
878
        of the root_transport. it is expected that plugins will need to extend
 
879
        this in the future - for instance to make bzr talk with svn working
 
880
        trees.
711
881
        """
712
882
        # this might be better on the BzrDirFormat class because it refers to
713
883
        # all the possible bzrdir disk formats.
717
887
        # add new tests for it to the appropriate place.
718
888
        return filename == '.bzr' or filename.startswith('.bzr/')
719
889
 
 
890
    def needs_format_conversion(self, format=None):
 
891
        """Return true if this bzrdir needs convert_format run on it.
 
892
 
 
893
        For instance, if the repository format is out of date but the
 
894
        branch and working tree are not, this should return True.
 
895
 
 
896
        :param format: Optional parameter indicating a specific desired
 
897
                       format we plan to arrive at.
 
898
        """
 
899
        raise NotImplementedError(self.needs_format_conversion)
 
900
 
720
901
    @staticmethod
721
902
    def open_unsupported(base):
722
903
        """Open a branch which is not supported."""
745
926
        # the redirections.
746
927
        base = transport.base
747
928
        def find_format(transport):
748
 
            return transport, controldir.ControlDirFormat.find_format(
 
929
            return transport, BzrDirFormat.find_format(
749
930
                transport, _server_formats=_server_formats)
750
931
 
751
932
        def redirected(transport, e, redirection_notice):
766
947
        BzrDir._check_supported(format, _unsupported)
767
948
        return format.open(transport, _found=True)
768
949
 
 
950
    def open_branch(self, name=None, unsupported=False,
 
951
                    ignore_fallbacks=False):
 
952
        """Open the branch object at this BzrDir if one is present.
 
953
 
 
954
        If unsupported is True, then no longer supported branch formats can
 
955
        still be opened.
 
956
 
 
957
        TODO: static convenience version of this?
 
958
        """
 
959
        raise NotImplementedError(self.open_branch)
 
960
 
769
961
    @staticmethod
770
962
    def open_containing(url, possible_transports=None):
771
963
        """Open an existing branch which contains url.
809
1001
                raise errors.NotBranchError(path=url)
810
1002
            a_transport = new_t
811
1003
 
 
1004
    def _get_tree_branch(self, name=None):
 
1005
        """Return the branch and tree, if any, for this bzrdir.
 
1006
 
 
1007
        :param name: Name of colocated branch to open.
 
1008
 
 
1009
        Return None for tree if not present or inaccessible.
 
1010
        Raise NotBranchError if no branch is present.
 
1011
        :return: (tree, branch)
 
1012
        """
 
1013
        try:
 
1014
            tree = self.open_workingtree()
 
1015
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
1016
            tree = None
 
1017
            branch = self.open_branch(name=name)
 
1018
        else:
 
1019
            if name is not None:
 
1020
                branch = self.open_branch(name=name)
 
1021
            else:
 
1022
                branch = tree.branch
 
1023
        return tree, branch
 
1024
 
812
1025
    @classmethod
813
1026
    def open_tree_or_branch(klass, location):
814
1027
        """Return the branch and working tree at a location.
860
1073
                raise errors.NotBranchError(location)
861
1074
        return tree, branch, branch.repository, relpath
862
1075
 
 
1076
    def open_repository(self, _unsupported=False):
 
1077
        """Open the repository object at this BzrDir if one is present.
 
1078
 
 
1079
        This will not follow the Branch object pointer - it's strictly a direct
 
1080
        open facility. Most client code should use open_branch().repository to
 
1081
        get at a repository.
 
1082
 
 
1083
        :param _unsupported: a private parameter, not part of the api.
 
1084
        TODO: static convenience version of this?
 
1085
        """
 
1086
        raise NotImplementedError(self.open_repository)
 
1087
 
 
1088
    def open_workingtree(self, _unsupported=False,
 
1089
                         recommend_upgrade=True, from_branch=None):
 
1090
        """Open the workingtree object at this BzrDir if one is present.
 
1091
 
 
1092
        :param recommend_upgrade: Optional keyword parameter, when True (the
 
1093
            default), emit through the ui module a recommendation that the user
 
1094
            upgrade the working tree when the workingtree being opened is old
 
1095
            (but still fully supported).
 
1096
        :param from_branch: override bzrdir branch (for lightweight checkouts)
 
1097
        """
 
1098
        raise NotImplementedError(self.open_workingtree)
 
1099
 
 
1100
    def has_branch(self, name=None):
 
1101
        """Tell if this bzrdir contains a branch.
 
1102
 
 
1103
        Note: if you're going to open the branch, you should just go ahead
 
1104
        and try, and not ask permission first.  (This method just opens the
 
1105
        branch and discards it, and that's somewhat expensive.)
 
1106
        """
 
1107
        try:
 
1108
            self.open_branch(name)
 
1109
            return True
 
1110
        except errors.NotBranchError:
 
1111
            return False
 
1112
 
 
1113
    def has_workingtree(self):
 
1114
        """Tell if this bzrdir contains a working tree.
 
1115
 
 
1116
        This will still raise an exception if the bzrdir has a workingtree that
 
1117
        is remote & inaccessible.
 
1118
 
 
1119
        Note: if you're going to open the working tree, you should just go ahead
 
1120
        and try, and not ask permission first.  (This method just opens the
 
1121
        workingtree and discards it, and that's somewhat expensive.)
 
1122
        """
 
1123
        try:
 
1124
            self.open_workingtree(recommend_upgrade=False)
 
1125
            return True
 
1126
        except errors.NoWorkingTree:
 
1127
            return False
 
1128
 
863
1129
    def _cloning_metadir(self):
864
1130
        """Produce a metadir suitable for cloning with.
865
1131
 
923
1189
            format.require_stacking()
924
1190
        return format
925
1191
 
926
 
    @classmethod
927
 
    def create(cls, base, format=None, possible_transports=None):
928
 
        """Create a new BzrDir at the url 'base'.
929
 
 
930
 
        :param format: If supplied, the format of branch to create.  If not
931
 
            supplied, the default is used.
932
 
        :param possible_transports: If supplied, a list of transports that
933
 
            can be reused to share a remote connection.
 
1192
    def checkout_metadir(self):
 
1193
        return self.cloning_metadir()
 
1194
 
 
1195
    def sprout(self, url, revision_id=None, force_new_repo=False,
 
1196
               recurse='down', possible_transports=None,
 
1197
               accelerator_tree=None, hardlink=False, stacked=False,
 
1198
               source_branch=None, create_tree_if_local=True):
 
1199
        """Create a copy of this bzrdir prepared for use as a new line of
 
1200
        development.
 
1201
 
 
1202
        If url's last component does not exist, it will be created.
 
1203
 
 
1204
        Attributes related to the identity of the source branch like
 
1205
        branch nickname will be cleaned, a working tree is created
 
1206
        whether one existed before or not; and a local branch is always
 
1207
        created.
 
1208
 
 
1209
        if revision_id is not None, then the clone operation may tune
 
1210
            itself to download less data.
 
1211
        :param accelerator_tree: A tree which can be used for retrieving file
 
1212
            contents more quickly than the revision tree, i.e. a workingtree.
 
1213
            The revision tree will be used for cases where accelerator_tree's
 
1214
            content is different.
 
1215
        :param hardlink: If true, hard-link files from accelerator_tree,
 
1216
            where possible.
 
1217
        :param stacked: If true, create a stacked branch referring to the
 
1218
            location of this control directory.
 
1219
        :param create_tree_if_local: If true, a working-tree will be created
 
1220
            when working locally.
934
1221
        """
935
 
        if cls is not BzrDir:
936
 
            raise AssertionError("BzrDir.create always creates the"
937
 
                "default format, not one of %r" % cls)
938
 
        t = get_transport(base, possible_transports)
939
 
        t.ensure_base()
940
 
        if format is None:
941
 
            format = controldir.ControlDirFormat.get_default_format()
942
 
        return format.initialize_on_transport(t)
943
 
 
 
1222
        target_transport = get_transport(url, possible_transports)
 
1223
        target_transport.ensure_base()
 
1224
        cloning_format = self.cloning_metadir(stacked)
 
1225
        # Create/update the result branch
 
1226
        result = cloning_format.initialize_on_transport(target_transport)
 
1227
        # if a stacked branch wasn't requested, we don't create one
 
1228
        # even if the origin was stacked
 
1229
        stacked_branch_url = None
 
1230
        if source_branch is not None:
 
1231
            if stacked:
 
1232
                stacked_branch_url = self.root_transport.base
 
1233
            source_repository = source_branch.repository
 
1234
        else:
 
1235
            try:
 
1236
                source_branch = self.open_branch()
 
1237
                source_repository = source_branch.repository
 
1238
                if stacked:
 
1239
                    stacked_branch_url = self.root_transport.base
 
1240
            except errors.NotBranchError:
 
1241
                source_branch = None
 
1242
                try:
 
1243
                    source_repository = self.open_repository()
 
1244
                except errors.NoRepositoryPresent:
 
1245
                    source_repository = None
 
1246
        repository_policy = result.determine_repository_policy(
 
1247
            force_new_repo, stacked_branch_url, require_stacking=stacked)
 
1248
        result_repo, is_new_repo = repository_policy.acquire_repository()
 
1249
        is_stacked = stacked or (len(result_repo._fallback_repositories) != 0)
 
1250
        if is_new_repo and revision_id is not None and not is_stacked:
 
1251
            fetch_spec = graph.PendingAncestryResult(
 
1252
                [revision_id], source_repository)
 
1253
        else:
 
1254
            fetch_spec = None
 
1255
        if source_repository is not None:
 
1256
            # Fetch while stacked to prevent unstacked fetch from
 
1257
            # Branch.sprout.
 
1258
            if fetch_spec is None:
 
1259
                result_repo.fetch(source_repository, revision_id=revision_id)
 
1260
            else:
 
1261
                result_repo.fetch(source_repository, fetch_spec=fetch_spec)
 
1262
 
 
1263
        if source_branch is None:
 
1264
            # this is for sprouting a bzrdir without a branch; is that
 
1265
            # actually useful?
 
1266
            # Not especially, but it's part of the contract.
 
1267
            result_branch = result.create_branch()
 
1268
        else:
 
1269
            result_branch = source_branch.sprout(result,
 
1270
                revision_id=revision_id, repository_policy=repository_policy)
 
1271
        mutter("created new branch %r" % (result_branch,))
 
1272
 
 
1273
        # Create/update the result working tree
 
1274
        if (create_tree_if_local and
 
1275
            isinstance(target_transport, local.LocalTransport) and
 
1276
            (result_repo is None or result_repo.make_working_trees())):
 
1277
            wt = result.create_workingtree(accelerator_tree=accelerator_tree,
 
1278
                hardlink=hardlink)
 
1279
            wt.lock_write()
 
1280
            try:
 
1281
                if wt.path2id('') is None:
 
1282
                    try:
 
1283
                        wt.set_root_id(self.open_workingtree.get_root_id())
 
1284
                    except errors.NoWorkingTree:
 
1285
                        pass
 
1286
            finally:
 
1287
                wt.unlock()
 
1288
        else:
 
1289
            wt = None
 
1290
        if recurse == 'down':
 
1291
            if wt is not None:
 
1292
                basis = wt.basis_tree()
 
1293
                basis.lock_read()
 
1294
                subtrees = basis.iter_references()
 
1295
            elif result_branch is not None:
 
1296
                basis = result_branch.basis_tree()
 
1297
                basis.lock_read()
 
1298
                subtrees = basis.iter_references()
 
1299
            elif source_branch is not None:
 
1300
                basis = source_branch.basis_tree()
 
1301
                basis.lock_read()
 
1302
                subtrees = basis.iter_references()
 
1303
            else:
 
1304
                subtrees = []
 
1305
                basis = None
 
1306
            try:
 
1307
                for path, file_id in subtrees:
 
1308
                    target = urlutils.join(url, urlutils.escape(path))
 
1309
                    sublocation = source_branch.reference_parent(file_id, path)
 
1310
                    sublocation.bzrdir.sprout(target,
 
1311
                        basis.get_reference_revision(file_id, path),
 
1312
                        force_new_repo=force_new_repo, recurse=recurse,
 
1313
                        stacked=stacked)
 
1314
            finally:
 
1315
                if basis is not None:
 
1316
                    basis.unlock()
 
1317
        return result
 
1318
 
 
1319
    def push_branch(self, source, revision_id=None, overwrite=False, 
 
1320
        remember=False, create_prefix=False):
 
1321
        """Push the source branch into this BzrDir."""
 
1322
        br_to = None
 
1323
        # If we can open a branch, use its direct repository, otherwise see
 
1324
        # if there is a repository without a branch.
 
1325
        try:
 
1326
            br_to = self.open_branch()
 
1327
        except errors.NotBranchError:
 
1328
            # Didn't find a branch, can we find a repository?
 
1329
            repository_to = self.find_repository()
 
1330
        else:
 
1331
            # Found a branch, so we must have found a repository
 
1332
            repository_to = br_to.repository
 
1333
 
 
1334
        push_result = PushResult()
 
1335
        push_result.source_branch = source
 
1336
        if br_to is None:
 
1337
            # We have a repository but no branch, copy the revisions, and then
 
1338
            # create a branch.
 
1339
            repository_to.fetch(source.repository, revision_id=revision_id)
 
1340
            br_to = source.clone(self, revision_id=revision_id)
 
1341
            if source.get_push_location() is None or remember:
 
1342
                source.set_push_location(br_to.base)
 
1343
            push_result.stacked_on = None
 
1344
            push_result.branch_push_result = None
 
1345
            push_result.old_revno = None
 
1346
            push_result.old_revid = _mod_revision.NULL_REVISION
 
1347
            push_result.target_branch = br_to
 
1348
            push_result.master_branch = None
 
1349
            push_result.workingtree_updated = False
 
1350
        else:
 
1351
            # We have successfully opened the branch, remember if necessary:
 
1352
            if source.get_push_location() is None or remember:
 
1353
                source.set_push_location(br_to.base)
 
1354
            try:
 
1355
                tree_to = self.open_workingtree()
 
1356
            except errors.NotLocalUrl:
 
1357
                push_result.branch_push_result = source.push(br_to, 
 
1358
                    overwrite, stop_revision=revision_id)
 
1359
                push_result.workingtree_updated = False
 
1360
            except errors.NoWorkingTree:
 
1361
                push_result.branch_push_result = source.push(br_to,
 
1362
                    overwrite, stop_revision=revision_id)
 
1363
                push_result.workingtree_updated = None # Not applicable
 
1364
            else:
 
1365
                tree_to.lock_write()
 
1366
                try:
 
1367
                    push_result.branch_push_result = source.push(
 
1368
                        tree_to.branch, overwrite, stop_revision=revision_id)
 
1369
                    tree_to.update()
 
1370
                finally:
 
1371
                    tree_to.unlock()
 
1372
                push_result.workingtree_updated = True
 
1373
            push_result.old_revno = push_result.branch_push_result.old_revno
 
1374
            push_result.old_revid = push_result.branch_push_result.old_revid
 
1375
            push_result.target_branch = \
 
1376
                push_result.branch_push_result.target_branch
 
1377
        return push_result
944
1378
 
945
1379
 
946
1380
class BzrDirHooks(hooks.Hooks):
1016
1450
    def cloning_metadir(self, require_stacking=False):
1017
1451
        """Produce a metadir suitable for cloning with."""
1018
1452
        if require_stacking:
1019
 
            return controldir.format_registry.make_bzrdir('1.6')
 
1453
            return format_registry.make_bzrdir('1.6')
1020
1454
        return self._format.__class__()
1021
1455
 
1022
1456
    def clone(self, url, revision_id=None, force_new_repo=False,
1459
1893
        return config.TransportConfig(self.transport, 'control.conf')
1460
1894
 
1461
1895
 
1462
 
class BzrProber(controldir.Prober):
1463
 
    """Prober for formats that use a .bzr/ control directory."""
1464
 
 
1465
 
    _formats = {}
1466
 
    """The known .bzr formats."""
1467
 
 
1468
 
    @classmethod
1469
 
    def register_bzrdir_format(klass, format):
1470
 
        klass._formats[format.get_format_string()] = format
1471
 
 
1472
 
    @classmethod
1473
 
    def unregister_bzrdir_format(klass, format):
1474
 
        del klass._formats[format.get_format_string()]
1475
 
 
1476
 
    @classmethod
1477
 
    def probe_transport(klass, transport):
1478
 
        """Return the .bzrdir style format present in a directory."""
1479
 
        try:
1480
 
            format_string = transport.get_bytes(".bzr/branch-format")
1481
 
        except errors.NoSuchFile:
1482
 
            raise errors.NotBranchError(path=transport.base)
1483
 
        try:
1484
 
            return klass._formats[format_string]
1485
 
        except KeyError:
1486
 
            raise errors.UnknownFormatError(format=format_string, kind='bzrdir')
1487
 
 
1488
 
 
1489
 
controldir.ControlDirFormat.register_prober(BzrProber)
1490
 
 
1491
 
 
1492
 
class RemoteBzrProber(controldir.Prober):
1493
 
    """Prober for remote servers that provide a Bazaar smart server."""
1494
 
 
1495
 
    @classmethod
1496
 
    def probe_transport(klass, transport):
1497
 
        """Return a RemoteBzrDirFormat object if it looks possible."""
1498
 
        try:
1499
 
            medium = transport.get_smart_medium()
1500
 
        except (NotImplementedError, AttributeError,
1501
 
                errors.TransportNotPossible, errors.NoSmartMedium,
1502
 
                errors.SmartProtocolError):
1503
 
            # no smart server, so not a branch for this format type.
1504
 
            raise errors.NotBranchError(path=transport.base)
1505
 
        else:
1506
 
            # Decline to open it if the server doesn't support our required
1507
 
            # version (3) so that the VFS-based transport will do it.
1508
 
            if medium.should_probe():
1509
 
                try:
1510
 
                    server_version = medium.protocol_version()
1511
 
                except errors.SmartProtocolError:
1512
 
                    # Apparently there's no usable smart server there, even though
1513
 
                    # the medium supports the smart protocol.
1514
 
                    raise errors.NotBranchError(path=transport.base)
1515
 
                if server_version != '2':
1516
 
                    raise errors.NotBranchError(path=transport.base)
1517
 
            return RemoteBzrDirFormat()
1518
 
 
1519
 
 
1520
 
class BzrDirFormat(controldir.ControlDirFormat):
1521
 
    """ControlDirFormat base class for .bzr/ directories.
 
1896
class BzrDirFormat(object):
 
1897
    """An encapsulation of the initialization and open routines for a format.
 
1898
 
 
1899
    Formats provide three things:
 
1900
     * An initialization routine,
 
1901
     * a format string,
 
1902
     * an open routine.
1522
1903
 
1523
1904
    Formats are placed in a dict by their format string for reference
1524
1905
    during bzrdir opening. These should be subclasses of BzrDirFormat
1527
1908
    Once a format is deprecated, just deprecate the initialize and open
1528
1909
    methods on the format class. Do not deprecate the object, as the
1529
1910
    object will be created every system load.
 
1911
 
 
1912
    :cvar colocated_branches: Whether this formats supports colocated branches.
 
1913
    """
 
1914
 
 
1915
    _default_format = None
 
1916
    """The default format used for new .bzr dirs."""
 
1917
 
 
1918
    _formats = {}
 
1919
    """The known formats."""
 
1920
 
 
1921
    _control_formats = []
 
1922
    """The registered control formats - .bzr, ....
 
1923
 
 
1924
    This is a list of BzrDirFormat objects.
 
1925
    """
 
1926
 
 
1927
    _control_server_formats = []
 
1928
    """The registered control server formats, e.g. RemoteBzrDirs.
 
1929
 
 
1930
    This is a list of BzrDirFormat objects.
1530
1931
    """
1531
1932
 
1532
1933
    _lock_file_name = 'branch-lock'
1533
1934
 
 
1935
    colocated_branches = False
 
1936
    """Whether co-located branches are supported for this control dir format.
 
1937
    """
 
1938
 
1534
1939
    # _lock_class must be set in subclasses to the lock type, typ.
1535
1940
    # TransportLock or LockDir
1536
1941
 
 
1942
    @classmethod
 
1943
    def find_format(klass, transport, _server_formats=True):
 
1944
        """Return the format present at transport."""
 
1945
        if _server_formats:
 
1946
            formats = klass._control_server_formats + klass._control_formats
 
1947
        else:
 
1948
            formats = klass._control_formats
 
1949
        for format in formats:
 
1950
            try:
 
1951
                return format.probe_transport(transport)
 
1952
            except errors.NotBranchError:
 
1953
                # this format does not find a control dir here.
 
1954
                pass
 
1955
        raise errors.NotBranchError(path=transport.base)
 
1956
 
 
1957
    @classmethod
 
1958
    def probe_transport(klass, transport):
 
1959
        """Return the .bzrdir style format present in a directory."""
 
1960
        try:
 
1961
            format_string = transport.get_bytes(".bzr/branch-format")
 
1962
        except errors.NoSuchFile:
 
1963
            raise errors.NotBranchError(path=transport.base)
 
1964
        try:
 
1965
            return klass._formats[format_string]
 
1966
        except KeyError:
 
1967
            raise errors.UnknownFormatError(format=format_string, kind='bzrdir')
 
1968
 
 
1969
    @classmethod
 
1970
    def get_default_format(klass):
 
1971
        """Return the current default format."""
 
1972
        return klass._default_format
 
1973
 
1537
1974
    def get_format_string(self):
1538
1975
        """Return the ASCII format string that identifies this format."""
1539
1976
        raise NotImplementedError(self.get_format_string)
1540
1977
 
 
1978
    def get_format_description(self):
 
1979
        """Return the short description for this format."""
 
1980
        raise NotImplementedError(self.get_format_description)
 
1981
 
 
1982
    def get_converter(self, format=None):
 
1983
        """Return the converter to use to convert bzrdirs needing converts.
 
1984
 
 
1985
        This returns a bzrlib.bzrdir.Converter object.
 
1986
 
 
1987
        This should return the best upgrader to step this format towards the
 
1988
        current default format. In the case of plugins we can/should provide
 
1989
        some means for them to extend the range of returnable converters.
 
1990
 
 
1991
        :param format: Optional format to override the default format of the
 
1992
                       library.
 
1993
        """
 
1994
        raise NotImplementedError(self.get_converter)
 
1995
 
 
1996
    def initialize(self, url, possible_transports=None):
 
1997
        """Create a bzr control dir at this url and return an opened copy.
 
1998
 
 
1999
        While not deprecated, this method is very specific and its use will
 
2000
        lead to many round trips to setup a working environment. See
 
2001
        initialize_on_transport_ex for a [nearly] all-in-one method.
 
2002
 
 
2003
        Subclasses should typically override initialize_on_transport
 
2004
        instead of this method.
 
2005
        """
 
2006
        return self.initialize_on_transport(get_transport(url,
 
2007
                                                          possible_transports))
 
2008
 
1541
2009
    def initialize_on_transport(self, transport):
1542
2010
        """Initialize a new bzrdir in the base directory of a Transport."""
1543
2011
        try:
1691
2159
            control_files.unlock()
1692
2160
        return self.open(transport, _found=True)
1693
2161
 
 
2162
    def is_supported(self):
 
2163
        """Is this format supported?
 
2164
 
 
2165
        Supported formats must be initializable and openable.
 
2166
        Unsupported formats may not support initialization or committing or
 
2167
        some other features depending on the reason for not being supported.
 
2168
        """
 
2169
        return True
 
2170
 
 
2171
    def network_name(self):
 
2172
        """A simple byte string uniquely identifying this format for RPC calls.
 
2173
 
 
2174
        Bzr control formats use thir disk format string to identify the format
 
2175
        over the wire. Its possible that other control formats have more
 
2176
        complex detection requirements, so we permit them to use any unique and
 
2177
        immutable string they desire.
 
2178
        """
 
2179
        raise NotImplementedError(self.network_name)
 
2180
 
 
2181
    def same_model(self, target_format):
 
2182
        return (self.repository_format.rich_root_data ==
 
2183
            target_format.rich_root_data)
 
2184
 
 
2185
    @classmethod
 
2186
    def known_formats(klass):
 
2187
        """Return all the known formats.
 
2188
 
 
2189
        Concrete formats should override _known_formats.
 
2190
        """
 
2191
        # There is double indirection here to make sure that control
 
2192
        # formats used by more than one dir format will only be probed
 
2193
        # once. This can otherwise be quite expensive for remote connections.
 
2194
        result = set()
 
2195
        for format in klass._control_formats:
 
2196
            result.update(format._known_formats())
 
2197
        return result
 
2198
 
 
2199
    @classmethod
 
2200
    def _known_formats(klass):
 
2201
        """Return the known format instances for this control format."""
 
2202
        return set(klass._formats.values())
 
2203
 
1694
2204
    def open(self, transport, _found=False):
1695
2205
        """Return an instance of this format for the dir transport points at.
1696
2206
 
1697
2207
        _found is a private parameter, do not use it.
1698
2208
        """
1699
2209
        if not _found:
1700
 
            found_format = controldir.ControlDirFormat.find_format(transport)
 
2210
            found_format = BzrDirFormat.find_format(transport)
1701
2211
            if not isinstance(found_format, self.__class__):
1702
2212
                raise AssertionError("%s was asked to open %s, but it seems to need "
1703
2213
                        "format %s"
1717
2227
 
1718
2228
    @classmethod
1719
2229
    def register_format(klass, format):
1720
 
        BzrProber.register_bzrdir_format(format)
 
2230
        klass._formats[format.get_format_string()] = format
1721
2231
        # bzr native formats have a network name of their format string.
1722
2232
        network_format_registry.register(format.get_format_string(), format.__class__)
1723
 
        controldir.ControlDirFormat.register_format(format)
 
2233
 
 
2234
    @classmethod
 
2235
    def register_control_format(klass, format):
 
2236
        """Register a format that does not use '.bzr' for its control dir.
 
2237
 
 
2238
        TODO: This should be pulled up into a 'ControlDirFormat' base class
 
2239
        which BzrDirFormat can inherit from, and renamed to register_format
 
2240
        there. It has been done without that for now for simplicity of
 
2241
        implementation.
 
2242
        """
 
2243
        klass._control_formats.append(format)
 
2244
 
 
2245
    @classmethod
 
2246
    def register_control_server_format(klass, format):
 
2247
        """Register a control format for client-server environments.
 
2248
 
 
2249
        These formats will be tried before ones registered with
 
2250
        register_control_format.  This gives implementations that decide to the
 
2251
        chance to grab it before anything looks at the contents of the format
 
2252
        file.
 
2253
        """
 
2254
        klass._control_server_formats.append(format)
 
2255
 
 
2256
    @classmethod
 
2257
    def _set_default_format(klass, format):
 
2258
        """Set default format (for testing behavior of defaults only)"""
 
2259
        klass._default_format = format
 
2260
 
 
2261
    def __str__(self):
 
2262
        # Trim the newline
 
2263
        return self.get_format_description().rstrip()
1724
2264
 
1725
2265
    def _supply_sub_formats_to(self, other_format):
1726
2266
        """Give other_format the same values for sub formats as this has.
1736
2276
 
1737
2277
    @classmethod
1738
2278
    def unregister_format(klass, format):
1739
 
        BzrProber.unregister_bzrdir_format(format)
1740
 
        controldir.ControlDirFormat.unregister_format(format)
1741
 
        network_format_registry.remove(format.get_format_string())
 
2279
        del klass._formats[format.get_format_string()]
 
2280
 
 
2281
    @classmethod
 
2282
    def unregister_control_format(klass, format):
 
2283
        klass._control_formats.remove(format)
1742
2284
 
1743
2285
 
1744
2286
class BzrDirFormat4(BzrDirFormat):
2156
2698
"""
2157
2699
 
2158
2700
 
 
2701
# Register bzr control format
 
2702
BzrDirFormat.register_control_format(BzrDirFormat)
 
2703
 
2159
2704
# Register bzr formats
2160
2705
BzrDirFormat.register_format(BzrDirFormat4())
2161
2706
BzrDirFormat.register_format(BzrDirFormat5())
2162
2707
BzrDirFormat.register_format(BzrDirFormat6())
2163
2708
__default_format = BzrDirMetaFormat1()
2164
2709
BzrDirFormat.register_format(__default_format)
2165
 
controldir.ControlDirFormat._default_format = __default_format
 
2710
BzrDirFormat._default_format = __default_format
2166
2711
 
2167
2712
 
2168
2713
class Converter(object):
2730
3275
        else:
2731
3276
            raise AssertionError("No network name set.")
2732
3277
 
 
3278
    @classmethod
 
3279
    def probe_transport(klass, transport):
 
3280
        """Return a RemoteBzrDirFormat object if it looks possible."""
 
3281
        try:
 
3282
            medium = transport.get_smart_medium()
 
3283
        except (NotImplementedError, AttributeError,
 
3284
                errors.TransportNotPossible, errors.NoSmartMedium,
 
3285
                errors.SmartProtocolError):
 
3286
            # no smart server, so not a branch for this format type.
 
3287
            raise errors.NotBranchError(path=transport.base)
 
3288
        else:
 
3289
            # Decline to open it if the server doesn't support our required
 
3290
            # version (3) so that the VFS-based transport will do it.
 
3291
            if medium.should_probe():
 
3292
                try:
 
3293
                    server_version = medium.protocol_version()
 
3294
                except errors.SmartProtocolError:
 
3295
                    # Apparently there's no usable smart server there, even though
 
3296
                    # the medium supports the smart protocol.
 
3297
                    raise errors.NotBranchError(path=transport.base)
 
3298
                if server_version != '2':
 
3299
                    raise errors.NotBranchError(path=transport.base)
 
3300
            return klass()
 
3301
 
2733
3302
    def initialize_on_transport(self, transport):
2734
3303
        try:
2735
3304
            # hand off the request to the smart server
2934
3503
        BzrDirMetaFormat1._set_repository_format) #.im_func)
2935
3504
 
2936
3505
 
2937
 
controldir.ControlDirFormat.register_server_prober(RemoteBzrProber)
 
3506
BzrDirFormat.register_control_server_format(RemoteBzrDirFormat)
 
3507
 
 
3508
 
 
3509
class BzrDirFormatInfo(object):
 
3510
 
 
3511
    def __init__(self, native, deprecated, hidden, experimental):
 
3512
        self.deprecated = deprecated
 
3513
        self.native = native
 
3514
        self.hidden = hidden
 
3515
        self.experimental = experimental
 
3516
 
 
3517
 
 
3518
class BzrDirFormatRegistry(registry.Registry):
 
3519
    """Registry of user-selectable BzrDir subformats.
 
3520
 
 
3521
    Differs from BzrDirFormat._control_formats in that it provides sub-formats,
 
3522
    e.g. BzrDirMeta1 with weave repository.  Also, it's more user-oriented.
 
3523
    """
 
3524
 
 
3525
    def __init__(self):
 
3526
        """Create a BzrDirFormatRegistry."""
 
3527
        self._aliases = set()
 
3528
        self._registration_order = list()
 
3529
        super(BzrDirFormatRegistry, self).__init__()
 
3530
 
 
3531
    def aliases(self):
 
3532
        """Return a set of the format names which are aliases."""
 
3533
        return frozenset(self._aliases)
 
3534
 
 
3535
    def register_metadir(self, key,
 
3536
             repository_format, help, native=True, deprecated=False,
 
3537
             branch_format=None,
 
3538
             tree_format=None,
 
3539
             hidden=False,
 
3540
             experimental=False,
 
3541
             alias=False):
 
3542
        """Register a metadir subformat.
 
3543
 
 
3544
        These all use a BzrDirMetaFormat1 bzrdir, but can be parameterized
 
3545
        by the Repository/Branch/WorkingTreeformats.
 
3546
 
 
3547
        :param repository_format: The fully-qualified repository format class
 
3548
            name as a string.
 
3549
        :param branch_format: Fully-qualified branch format class name as
 
3550
            a string.
 
3551
        :param tree_format: Fully-qualified tree format class name as
 
3552
            a string.
 
3553
        """
 
3554
        # This should be expanded to support setting WorkingTree and Branch
 
3555
        # formats, once BzrDirMetaFormat1 supports that.
 
3556
        def _load(full_name):
 
3557
            mod_name, factory_name = full_name.rsplit('.', 1)
 
3558
            try:
 
3559
                mod = __import__(mod_name, globals(), locals(),
 
3560
                        [factory_name])
 
3561
            except ImportError, e:
 
3562
                raise ImportError('failed to load %s: %s' % (full_name, e))
 
3563
            try:
 
3564
                factory = getattr(mod, factory_name)
 
3565
            except AttributeError:
 
3566
                raise AttributeError('no factory %s in module %r'
 
3567
                    % (full_name, mod))
 
3568
            return factory()
 
3569
 
 
3570
        def helper():
 
3571
            bd = BzrDirMetaFormat1()
 
3572
            if branch_format is not None:
 
3573
                bd.set_branch_format(_load(branch_format))
 
3574
            if tree_format is not None:
 
3575
                bd.workingtree_format = _load(tree_format)
 
3576
            if repository_format is not None:
 
3577
                bd.repository_format = _load(repository_format)
 
3578
            return bd
 
3579
        self.register(key, helper, help, native, deprecated, hidden,
 
3580
            experimental, alias)
 
3581
 
 
3582
    def register(self, key, factory, help, native=True, deprecated=False,
 
3583
                 hidden=False, experimental=False, alias=False):
 
3584
        """Register a BzrDirFormat factory.
 
3585
 
 
3586
        The factory must be a callable that takes one parameter: the key.
 
3587
        It must produce an instance of the BzrDirFormat when called.
 
3588
 
 
3589
        This function mainly exists to prevent the info object from being
 
3590
        supplied directly.
 
3591
        """
 
3592
        registry.Registry.register(self, key, factory, help,
 
3593
            BzrDirFormatInfo(native, deprecated, hidden, experimental))
 
3594
        if alias:
 
3595
            self._aliases.add(key)
 
3596
        self._registration_order.append(key)
 
3597
 
 
3598
    def register_lazy(self, key, module_name, member_name, help, native=True,
 
3599
        deprecated=False, hidden=False, experimental=False, alias=False):
 
3600
        registry.Registry.register_lazy(self, key, module_name, member_name,
 
3601
            help, BzrDirFormatInfo(native, deprecated, hidden, experimental))
 
3602
        if alias:
 
3603
            self._aliases.add(key)
 
3604
        self._registration_order.append(key)
 
3605
 
 
3606
    def set_default(self, key):
 
3607
        """Set the 'default' key to be a clone of the supplied key.
 
3608
 
 
3609
        This method must be called once and only once.
 
3610
        """
 
3611
        registry.Registry.register(self, 'default', self.get(key),
 
3612
            self.get_help(key), info=self.get_info(key))
 
3613
        self._aliases.add('default')
 
3614
 
 
3615
    def set_default_repository(self, key):
 
3616
        """Set the FormatRegistry default and Repository default.
 
3617
 
 
3618
        This is a transitional method while Repository.set_default_format
 
3619
        is deprecated.
 
3620
        """
 
3621
        if 'default' in self:
 
3622
            self.remove('default')
 
3623
        self.set_default(key)
 
3624
        format = self.get('default')()
 
3625
 
 
3626
    def make_bzrdir(self, key):
 
3627
        return self.get(key)()
 
3628
 
 
3629
    def help_topic(self, topic):
 
3630
        output = ""
 
3631
        default_realkey = None
 
3632
        default_help = self.get_help('default')
 
3633
        help_pairs = []
 
3634
        for key in self._registration_order:
 
3635
            if key == 'default':
 
3636
                continue
 
3637
            help = self.get_help(key)
 
3638
            if help == default_help:
 
3639
                default_realkey = key
 
3640
            else:
 
3641
                help_pairs.append((key, help))
 
3642
 
 
3643
        def wrapped(key, help, info):
 
3644
            if info.native:
 
3645
                help = '(native) ' + help
 
3646
            return ':%s:\n%s\n\n' % (key,
 
3647
                textwrap.fill(help, initial_indent='    ',
 
3648
                    subsequent_indent='    ',
 
3649
                    break_long_words=False))
 
3650
        if default_realkey is not None:
 
3651
            output += wrapped(default_realkey, '(default) %s' % default_help,
 
3652
                              self.get_info('default'))
 
3653
        deprecated_pairs = []
 
3654
        experimental_pairs = []
 
3655
        for key, help in help_pairs:
 
3656
            info = self.get_info(key)
 
3657
            if info.hidden:
 
3658
                continue
 
3659
            elif info.deprecated:
 
3660
                deprecated_pairs.append((key, help))
 
3661
            elif info.experimental:
 
3662
                experimental_pairs.append((key, help))
 
3663
            else:
 
3664
                output += wrapped(key, help, info)
 
3665
        output += "\nSee :doc:`formats-help` for more about storage formats."
 
3666
        other_output = ""
 
3667
        if len(experimental_pairs) > 0:
 
3668
            other_output += "Experimental formats are shown below.\n\n"
 
3669
            for key, help in experimental_pairs:
 
3670
                info = self.get_info(key)
 
3671
                other_output += wrapped(key, help, info)
 
3672
        else:
 
3673
            other_output += \
 
3674
                "No experimental formats are available.\n\n"
 
3675
        if len(deprecated_pairs) > 0:
 
3676
            other_output += "\nDeprecated formats are shown below.\n\n"
 
3677
            for key, help in deprecated_pairs:
 
3678
                info = self.get_info(key)
 
3679
                other_output += wrapped(key, help, info)
 
3680
        else:
 
3681
            other_output += \
 
3682
                "\nNo deprecated formats are available.\n\n"
 
3683
        other_output += \
 
3684
                "\nSee :doc:`formats-help` for more about storage formats."
 
3685
 
 
3686
        if topic == 'other-formats':
 
3687
            return other_output
 
3688
        else:
 
3689
            return output
2938
3690
 
2939
3691
 
2940
3692
class RepositoryAcquisitionPolicy(object):
3094
3846
        return self._repository, False
3095
3847
 
3096
3848
 
3097
 
def register_metadir(registry, key,
3098
 
         repository_format, help, native=True, deprecated=False,
3099
 
         branch_format=None,
3100
 
         tree_format=None,
3101
 
         hidden=False,
3102
 
         experimental=False,
3103
 
         alias=False):
3104
 
    """Register a metadir subformat.
3105
 
 
3106
 
    These all use a BzrDirMetaFormat1 bzrdir, but can be parameterized
3107
 
    by the Repository/Branch/WorkingTreeformats.
3108
 
 
3109
 
    :param repository_format: The fully-qualified repository format class
3110
 
        name as a string.
3111
 
    :param branch_format: Fully-qualified branch format class name as
3112
 
        a string.
3113
 
    :param tree_format: Fully-qualified tree format class name as
3114
 
        a string.
3115
 
    """
3116
 
    # This should be expanded to support setting WorkingTree and Branch
3117
 
    # formats, once BzrDirMetaFormat1 supports that.
3118
 
    def _load(full_name):
3119
 
        mod_name, factory_name = full_name.rsplit('.', 1)
3120
 
        try:
3121
 
            mod = __import__(mod_name, globals(), locals(),
3122
 
                    [factory_name])
3123
 
        except ImportError, e:
3124
 
            raise ImportError('failed to load %s: %s' % (full_name, e))
3125
 
        try:
3126
 
            factory = getattr(mod, factory_name)
3127
 
        except AttributeError:
3128
 
            raise AttributeError('no factory %s in module %r'
3129
 
                % (full_name, mod))
3130
 
        return factory()
3131
 
 
3132
 
    def helper():
3133
 
        bd = BzrDirMetaFormat1()
3134
 
        if branch_format is not None:
3135
 
            bd.set_branch_format(_load(branch_format))
3136
 
        if tree_format is not None:
3137
 
            bd.workingtree_format = _load(tree_format)
3138
 
        if repository_format is not None:
3139
 
            bd.repository_format = _load(repository_format)
3140
 
        return bd
3141
 
    registry.register(key, helper, help, native, deprecated, hidden,
3142
 
        experimental, alias)
3143
 
 
 
3849
# Please register new formats after old formats so that formats
 
3850
# appear in chronological order and format descriptions can build
 
3851
# on previous ones.
 
3852
format_registry = BzrDirFormatRegistry()
3144
3853
# The pre-0.8 formats have their repository format network name registered in
3145
3854
# repository.py. MetaDir formats have their repository format network name
3146
3855
# inferred from their disk format string.
3147
 
controldir.format_registry.register('weave', BzrDirFormat6,
 
3856
format_registry.register('weave', BzrDirFormat6,
3148
3857
    'Pre-0.8 format.  Slower than knit and does not'
3149
3858
    ' support checkouts or shared repositories.',
3150
3859
    hidden=True,
3151
3860
    deprecated=True)
3152
 
register_metadir(controldir.format_registry, 'metaweave',
 
3861
format_registry.register_metadir('metaweave',
3153
3862
    'bzrlib.repofmt.weaverepo.RepositoryFormat7',
3154
3863
    'Transitional format in 0.8.  Slower than knit.',
3155
3864
    branch_format='bzrlib.branch.BzrBranchFormat5',
3156
3865
    tree_format='bzrlib.workingtree.WorkingTreeFormat3',
3157
3866
    hidden=True,
3158
3867
    deprecated=True)
3159
 
register_metadir(controldir.format_registry, 'knit',
 
3868
format_registry.register_metadir('knit',
3160
3869
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
3161
3870
    'Format using knits.  Recommended for interoperation with bzr <= 0.14.',
3162
3871
    branch_format='bzrlib.branch.BzrBranchFormat5',
3163
3872
    tree_format='bzrlib.workingtree.WorkingTreeFormat3',
3164
3873
    hidden=True,
3165
3874
    deprecated=True)
3166
 
register_metadir(controldir.format_registry, 'dirstate',
 
3875
format_registry.register_metadir('dirstate',
3167
3876
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
3168
3877
    help='New in 0.15: Fast local operations. Compatible with bzr 0.8 and '
3169
3878
        'above when accessed over the network.',
3173
3882
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3174
3883
    hidden=True,
3175
3884
    deprecated=True)
3176
 
register_metadir(controldir.format_registry, 'dirstate-tags',
 
3885
format_registry.register_metadir('dirstate-tags',
3177
3886
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
3178
3887
    help='New in 0.15: Fast local operations and improved scaling for '
3179
3888
        'network operations. Additionally adds support for tags.'
3182
3891
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3183
3892
    hidden=True,
3184
3893
    deprecated=True)
3185
 
register_metadir(controldir.format_registry, 'rich-root',
 
3894
format_registry.register_metadir('rich-root',
3186
3895
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit4',
3187
3896
    help='New in 1.0.  Better handling of tree roots.  Incompatible with'
3188
3897
        ' bzr < 1.0.',
3190
3899
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3191
3900
    hidden=True,
3192
3901
    deprecated=True)
3193
 
register_metadir(controldir.format_registry, 'dirstate-with-subtree',
 
3902
format_registry.register_metadir('dirstate-with-subtree',
3194
3903
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
3195
3904
    help='New in 0.15: Fast local operations and improved scaling for '
3196
3905
        'network operations. Additionally adds support for versioning nested '
3200
3909
    experimental=True,
3201
3910
    hidden=True,
3202
3911
    )
3203
 
register_metadir(controldir.format_registry, 'pack-0.92',
 
3912
format_registry.register_metadir('pack-0.92',
3204
3913
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack1',
3205
3914
    help='New in 0.92: Pack-based format with data compatible with '
3206
3915
        'dirstate-tags format repositories. Interoperates with '
3209
3918
    branch_format='bzrlib.branch.BzrBranchFormat6',
3210
3919
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3211
3920
    )
3212
 
register_metadir(controldir.format_registry, 'pack-0.92-subtree',
 
3921
format_registry.register_metadir('pack-0.92-subtree',
3213
3922
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack3',
3214
3923
    help='New in 0.92: Pack-based format with data compatible with '
3215
3924
        'dirstate-with-subtree format repositories. Interoperates with '
3220
3929
    hidden=True,
3221
3930
    experimental=True,
3222
3931
    )
3223
 
register_metadir(controldir.format_registry, 'rich-root-pack',
 
3932
format_registry.register_metadir('rich-root-pack',
3224
3933
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack4',
3225
3934
    help='New in 1.0: A variant of pack-0.92 that supports rich-root data '
3226
3935
         '(needed for bzr-svn and bzr-git).',
3228
3937
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3229
3938
    hidden=True,
3230
3939
    )
3231
 
register_metadir(controldir.format_registry, '1.6',
 
3940
format_registry.register_metadir('1.6',
3232
3941
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5',
3233
3942
    help='A format that allows a branch to indicate that there is another '
3234
3943
         '(stacked) repository that should be used to access data that is '
3237
3946
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3238
3947
    hidden=True,
3239
3948
    )
3240
 
register_metadir(controldir.format_registry, '1.6.1-rich-root',
 
3949
format_registry.register_metadir('1.6.1-rich-root',
3241
3950
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5RichRoot',
3242
3951
    help='A variant of 1.6 that supports rich-root data '
3243
3952
         '(needed for bzr-svn and bzr-git).',
3245
3954
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3246
3955
    hidden=True,
3247
3956
    )
3248
 
register_metadir(controldir.format_registry, '1.9',
 
3957
format_registry.register_metadir('1.9',
3249
3958
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
3250
3959
    help='A repository format using B+tree indexes. These indexes '
3251
3960
         'are smaller in size, have smarter caching and provide faster '
3254
3963
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3255
3964
    hidden=True,
3256
3965
    )
3257
 
register_metadir(controldir.format_registry, '1.9-rich-root',
 
3966
format_registry.register_metadir('1.9-rich-root',
3258
3967
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
3259
3968
    help='A variant of 1.9 that supports rich-root data '
3260
3969
         '(needed for bzr-svn and bzr-git).',
3262
3971
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3263
3972
    hidden=True,
3264
3973
    )
3265
 
register_metadir(controldir.format_registry, '1.14',
 
3974
format_registry.register_metadir('1.14',
3266
3975
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
3267
3976
    help='A working-tree format that supports content filtering.',
3268
3977
    branch_format='bzrlib.branch.BzrBranchFormat7',
3269
3978
    tree_format='bzrlib.workingtree.WorkingTreeFormat5',
3270
3979
    )
3271
 
register_metadir(controldir.format_registry, '1.14-rich-root',
 
3980
format_registry.register_metadir('1.14-rich-root',
3272
3981
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
3273
3982
    help='A variant of 1.14 that supports rich-root data '
3274
3983
         '(needed for bzr-svn and bzr-git).',
3276
3985
    tree_format='bzrlib.workingtree.WorkingTreeFormat5',
3277
3986
    )
3278
3987
# The following un-numbered 'development' formats should always just be aliases.
3279
 
register_metadir(controldir.format_registry, 'development-rich-root',
 
3988
format_registry.register_metadir('development-rich-root',
3280
3989
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormatCHK1',
3281
3990
    help='Current development format. Supports rich roots. Can convert data '
3282
3991
        'to and from rich-root-pack (and anything compatible with '
3290
3999
    alias=True,
3291
4000
    hidden=True,
3292
4001
    )
3293
 
register_metadir(controldir.format_registry, 'development-subtree',
 
4002
format_registry.register_metadir('development-subtree',
3294
4003
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment2Subtree',
3295
4004
    help='Current development format, subtree variant. Can convert data to and '
3296
4005
        'from pack-0.92-subtree (and anything compatible with '
3308
4017
    )
3309
4018
 
3310
4019
# And the development formats above will have aliased one of the following:
3311
 
register_metadir(controldir.format_registry, 'development6-rich-root',
 
4020
format_registry.register_metadir('development6-rich-root',
3312
4021
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormatCHK1',
3313
4022
    help='pack-1.9 with 255-way hashed CHK inv, group compress, rich roots '
3314
4023
        'Please read '
3320
4029
    experimental=True,
3321
4030
    )
3322
4031
 
3323
 
register_metadir(controldir.format_registry, 'development7-rich-root',
 
4032
format_registry.register_metadir('development7-rich-root',
3324
4033
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormatCHK2',
3325
4034
    help='pack-1.9 with 255-way hashed CHK inv, bencode revision, group compress, '
3326
4035
        'rich roots. Please read '
3332
4041
    experimental=True,
3333
4042
    )
3334
4043
 
3335
 
register_metadir(controldir.format_registry, '2a',
 
4044
format_registry.register_metadir('2a',
3336
4045
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2a',
3337
4046
    help='First format for bzr 2.0 series.\n'
3338
4047
        'Uses group-compress storage.\n'
3346
4055
 
3347
4056
# The following format should be an alias for the rich root equivalent 
3348
4057
# of the default format
3349
 
register_metadir(controldir.format_registry, 'default-rich-root',
 
4058
format_registry.register_metadir('default-rich-root',
3350
4059
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2a',
3351
4060
    branch_format='bzrlib.branch.BzrBranchFormat7',
3352
4061
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
3355
4064
    help='Same as 2a.')
3356
4065
 
3357
4066
# The current format that is made on 'bzr init'.
3358
 
controldir.format_registry.set_default('2a')
3359
 
 
3360
 
# XXX 2010-08-20 JRV: There is still a lot of code relying on
3361
 
# bzrlib.bzrdir.format_registry existing. When BzrDir.create/BzrDir.open/etc
3362
 
# get changed to ControlDir.create/ControlDir.open/etc this should be removed.
3363
 
format_registry = controldir.format_registry
 
4067
format_registry.set_default('2a')