~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-24 21:59:21 UTC
  • mfrom: (5363.2.22 controldir-1)
  • Revision ID: pqm@pqm.ubuntu.com-20100824215921-p4nheij9k4x6i1jw
(jelmer) Split generic interface code out of bzrlib.bzrdir.BzrDir into
 bzrlib.controldir.ControlDir. (Jelmer Vernooij)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
 
1
# Copyright (C) 2006-2010 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
29
29
 
30
30
import os
31
31
import sys
 
32
import warnings
32
33
 
33
34
from bzrlib.lazy_import import lazy_import
34
35
lazy_import(globals(), """
35
36
from stat import S_ISDIR
36
 
import textwrap
37
37
 
38
38
import bzrlib
39
39
from bzrlib import (
40
40
    branch,
41
41
    config,
 
42
    controldir,
42
43
    errors,
43
44
    graph,
44
45
    lockable_files,
87
88
    )
88
89
 
89
90
 
90
 
class BzrDir(object):
 
91
class BzrDir(controldir.ControlDir):
91
92
    """A .bzr control diretory.
92
93
 
93
94
    BzrDir instances let you create or open any of the things that can be
124
125
                    return
125
126
        thing_to_unlock.break_lock()
126
127
 
127
 
    def can_convert_format(self):
128
 
        """Return true if this bzrdir is one whose format we can convert from."""
129
 
        return True
130
 
 
131
128
    def check_conversion_target(self, target_format):
 
129
        """Check that a bzrdir as a whole can be converted to a new format."""
 
130
        # The only current restriction is that the repository content can be 
 
131
        # fetched compatibly with the target.
132
132
        target_repo_format = target_format.repository_format
133
 
        source_repo_format = self._format.repository_format
134
 
        source_repo_format.check_conversion_target(target_repo_format)
 
133
        try:
 
134
            self.open_repository()._format.check_conversion_target(
 
135
                target_repo_format)
 
136
        except errors.NoRepositoryPresent:
 
137
            # No repo, no problem.
 
138
            pass
135
139
 
136
140
    @staticmethod
137
141
    def _check_supported(format, allow_unsupported,
200
204
        """
201
205
        # Overview: put together a broad description of what we want to end up
202
206
        # with; then make as few api calls as possible to do it.
203
 
        
 
207
 
204
208
        # We may want to create a repo/branch/tree, if we do so what format
205
209
        # would we want for each:
206
210
        require_stacking = (stacked_on is not None)
207
211
        format = self.cloning_metadir(require_stacking)
208
 
        
 
212
 
209
213
        # Figure out what objects we want:
210
214
        try:
211
215
            local_repo = self.find_repository()
253
257
                # copied, and finally if we are copying up to a specific
254
258
                # revision_id then we can use the pending-ancestry-result which
255
259
                # does not require traversing all of history to describe it.
256
 
                if (result_repo.bzrdir.root_transport.base ==
257
 
                    result.root_transport.base and not require_stacking and
 
260
                if (result_repo.user_url == result.user_url
 
261
                    and not require_stacking and
258
262
                    revision_id is not None):
259
263
                    fetch_spec = graph.PendingAncestryResult(
260
264
                        [revision_id], local_repo)
288
292
        t = get_transport(url)
289
293
        t.ensure_base()
290
294
 
291
 
    @classmethod
292
 
    def create(cls, base, format=None, possible_transports=None):
293
 
        """Create a new BzrDir at the url 'base'.
294
 
 
295
 
        :param format: If supplied, the format of branch to create.  If not
296
 
            supplied, the default is used.
297
 
        :param possible_transports: If supplied, a list of transports that
298
 
            can be reused to share a remote connection.
299
 
        """
300
 
        if cls is not BzrDir:
301
 
            raise AssertionError("BzrDir.create always creates the default"
302
 
                " format, not one of %r" % cls)
303
 
        t = get_transport(base, possible_transports)
304
 
        t.ensure_base()
305
 
        if format is None:
306
 
            format = BzrDirFormat.get_default_format()
307
 
        return format.initialize_on_transport(t)
308
 
 
309
295
    @staticmethod
310
296
    def find_bzrdirs(transport, evaluate=None, list_current=None):
311
297
        """Find bzrdirs recursively from current location.
334
320
            recurse = True
335
321
            try:
336
322
                bzrdir = BzrDir.open_from_transport(current_transport)
337
 
            except errors.NotBranchError:
 
323
            except (errors.NotBranchError, errors.PermissionDenied):
338
324
                pass
339
325
            else:
340
326
                recurse, value = evaluate(bzrdir)
341
327
                yield value
342
328
            try:
343
329
                subdirs = list_current(current_transport)
344
 
            except errors.NoSuchFile:
 
330
            except (errors.NoSuchFile, errors.PermissionDenied):
345
331
                continue
346
332
            if recurse:
347
333
                for subdir in sorted(subdirs, reverse=True):
364
350
            except errors.NoRepositoryPresent:
365
351
                pass
366
352
            else:
367
 
                return False, (None, repository)
368
 
            try:
369
 
                branch = bzrdir.open_branch()
370
 
            except errors.NotBranchError:
371
 
                return True, (None, None)
372
 
            else:
373
 
                return True, (branch, None)
374
 
        branches = []
375
 
        for branch, repo in BzrDir.find_bzrdirs(transport, evaluate=evaluate):
 
353
                return False, ([], repository)
 
354
            return True, (bzrdir.list_branches(), None)
 
355
        ret = []
 
356
        for branches, repo in BzrDir.find_bzrdirs(transport,
 
357
                                                  evaluate=evaluate):
376
358
            if repo is not None:
377
 
                branches.extend(repo.find_branches())
378
 
            if branch is not None:
379
 
                branches.append(branch)
380
 
        return branches
381
 
 
382
 
    def destroy_repository(self):
383
 
        """Destroy the repository in this BzrDir"""
384
 
        raise NotImplementedError(self.destroy_repository)
385
 
 
386
 
    def create_branch(self):
387
 
        """Create a branch in this BzrDir.
388
 
 
389
 
        The bzrdir's format will control what branch format is created.
390
 
        For more control see BranchFormatXX.create(a_bzrdir).
391
 
        """
392
 
        raise NotImplementedError(self.create_branch)
393
 
 
394
 
    def destroy_branch(self):
395
 
        """Destroy the branch in this BzrDir"""
396
 
        raise NotImplementedError(self.destroy_branch)
 
359
                ret.extend(repo.find_branches())
 
360
            if branches is not None:
 
361
                ret.extend(branches)
 
362
        return ret
397
363
 
398
364
    @staticmethod
399
365
    def create_branch_and_repo(base, force_new_repo=False, format=None):
438
404
            stop = False
439
405
            stack_on = config.get_default_stack_on()
440
406
            if stack_on is not None:
441
 
                stack_on_pwd = found_bzrdir.root_transport.base
 
407
                stack_on_pwd = found_bzrdir.user_url
442
408
                stop = True
443
409
            # does it have a repository ?
444
410
            try:
446
412
            except errors.NoRepositoryPresent:
447
413
                repository = None
448
414
            else:
449
 
                if ((found_bzrdir.root_transport.base !=
450
 
                     self.root_transport.base) and not repository.is_shared()):
 
415
                if (found_bzrdir.user_url != self.user_url 
 
416
                    and not repository.is_shared()):
451
417
                    # Don't look higher, can't use a higher shared repo.
452
418
                    repository = None
453
419
                    stop = True
549
515
                                               format=format).bzrdir
550
516
        return bzrdir.create_workingtree()
551
517
 
552
 
    def create_workingtree(self, revision_id=None, from_branch=None,
553
 
        accelerator_tree=None, hardlink=False):
554
 
        """Create a working tree at this BzrDir.
555
 
 
556
 
        :param revision_id: create it as of this revision id.
557
 
        :param from_branch: override bzrdir branch (for lightweight checkouts)
558
 
        :param accelerator_tree: A tree which can be used for retrieving file
559
 
            contents more quickly than the revision tree, i.e. a workingtree.
560
 
            The revision tree will be used for cases where accelerator_tree's
561
 
            content is different.
562
 
        """
563
 
        raise NotImplementedError(self.create_workingtree)
 
518
    def generate_backup_name(self, base):
 
519
        """Generate a non-existing backup file name based on base."""
 
520
        counter = 1
 
521
        name = "%s.~%d~" % (base, counter)
 
522
        while self.root_transport.has(name):
 
523
            counter += 1
 
524
            name = "%s.~%d~" % (base, counter)
 
525
        return name
564
526
 
565
527
    def backup_bzrdir(self):
566
528
        """Backup this bzr control directory.
567
529
 
568
530
        :return: Tuple with old path name and new path name
569
531
        """
 
532
 
 
533
        backup_dir=self.generate_backup_name('backup.bzr')
570
534
        pb = ui.ui_factory.nested_progress_bar()
571
535
        try:
572
536
            # FIXME: bug 300001 -- the backup fails if the backup directory
573
537
            # already exists, but it should instead either remove it or make
574
538
            # a new backup directory.
575
539
            #
576
 
            # FIXME: bug 262450 -- the backup directory should have the same
577
 
            # permissions as the .bzr directory (probably a bug in copy_tree)
578
540
            old_path = self.root_transport.abspath('.bzr')
579
 
            new_path = self.root_transport.abspath('backup.bzr')
580
 
            pb.note('making backup of %s' % (old_path,))
581
 
            pb.note('  to %s' % (new_path,))
582
 
            self.root_transport.copy_tree('.bzr', 'backup.bzr')
 
541
            new_path = self.root_transport.abspath(backup_dir)
 
542
            ui.ui_factory.note('making backup of %s\n  to %s' % (old_path, new_path,))
 
543
            self.root_transport.copy_tree('.bzr', backup_dir)
583
544
            return (old_path, new_path)
584
545
        finally:
585
546
            pb.finished()
609
570
                else:
610
571
                    pass
611
572
 
612
 
    def destroy_workingtree(self):
613
 
        """Destroy the working tree at this BzrDir.
614
 
 
615
 
        Formats that do not support this may raise UnsupportedOperation.
616
 
        """
617
 
        raise NotImplementedError(self.destroy_workingtree)
618
 
 
619
 
    def destroy_workingtree_metadata(self):
620
 
        """Destroy the control files for the working tree at this BzrDir.
621
 
 
622
 
        The contents of working tree files are not affected.
623
 
        Formats that do not support this may raise UnsupportedOperation.
624
 
        """
625
 
        raise NotImplementedError(self.destroy_workingtree_metadata)
626
 
 
627
573
    def _find_containing(self, evaluate):
628
574
        """Find something in a containing control directory.
629
575
 
643
589
            if stop:
644
590
                return result
645
591
            next_transport = found_bzrdir.root_transport.clone('..')
646
 
            if (found_bzrdir.root_transport.base == next_transport.base):
 
592
            if (found_bzrdir.user_url == next_transport.base):
647
593
                # top of the file system
648
594
                return None
649
595
            # find the next containing bzrdir
666
612
                repository = found_bzrdir.open_repository()
667
613
            except errors.NoRepositoryPresent:
668
614
                return None, False
669
 
            if found_bzrdir.root_transport.base == self.root_transport.base:
 
615
            if found_bzrdir.user_url == self.user_url:
670
616
                return repository, True
671
617
            elif repository.is_shared():
672
618
                return repository, True
678
624
            raise errors.NoRepositoryPresent(self)
679
625
        return found_repo
680
626
 
681
 
    def get_branch_reference(self):
682
 
        """Return the referenced URL for the branch in this bzrdir.
683
 
 
684
 
        :raises NotBranchError: If there is no Branch.
685
 
        :return: The URL the branch in this bzrdir references if it is a
686
 
            reference branch, or None for regular branches.
687
 
        """
688
 
        return None
689
 
 
690
 
    def get_branch_transport(self, branch_format):
691
 
        """Get the transport for use by branch format in this BzrDir.
692
 
 
693
 
        Note that bzr dirs that do not support format strings will raise
694
 
        IncompatibleFormat if the branch format they are given has
695
 
        a format string, and vice versa.
696
 
 
697
 
        If branch_format is None, the transport is returned with no
698
 
        checking. If it is not None, then the returned transport is
699
 
        guaranteed to point to an existing directory ready for use.
700
 
        """
701
 
        raise NotImplementedError(self.get_branch_transport)
702
 
 
703
627
    def _find_creation_modes(self):
704
628
        """Determine the appropriate modes for files and directories.
705
629
 
744
668
            self._find_creation_modes()
745
669
        return self._dir_mode
746
670
 
747
 
    def get_repository_transport(self, repository_format):
748
 
        """Get the transport for use by repository format in this BzrDir.
749
 
 
750
 
        Note that bzr dirs that do not support format strings will raise
751
 
        IncompatibleFormat if the repository format they are given has
752
 
        a format string, and vice versa.
753
 
 
754
 
        If repository_format is None, the transport is returned with no
755
 
        checking. If it is not None, then the returned transport is
756
 
        guaranteed to point to an existing directory ready for use.
757
 
        """
758
 
        raise NotImplementedError(self.get_repository_transport)
759
 
 
760
 
    def get_workingtree_transport(self, tree_format):
761
 
        """Get the transport for use by workingtree format in this BzrDir.
762
 
 
763
 
        Note that bzr dirs that do not support format strings will raise
764
 
        IncompatibleFormat if the workingtree format they are given has a
765
 
        format string, and vice versa.
766
 
 
767
 
        If workingtree_format is None, the transport is returned with no
768
 
        checking. If it is not None, then the returned transport is
769
 
        guaranteed to point to an existing directory ready for use.
770
 
        """
771
 
        raise NotImplementedError(self.get_workingtree_transport)
772
 
 
773
671
    def get_config(self):
774
672
        """Get configuration for this BzrDir."""
775
673
        return config.BzrDirConfig(self)
788
686
        :param _transport: the transport this dir is based at.
789
687
        """
790
688
        self._format = _format
 
689
        # these are also under the more standard names of 
 
690
        # control_transport and user_transport
791
691
        self.transport = _transport.clone('.bzr')
792
692
        self.root_transport = _transport
793
693
        self._mode_check_done = False
794
694
 
 
695
    @property 
 
696
    def user_transport(self):
 
697
        return self.root_transport
 
698
 
 
699
    @property
 
700
    def control_transport(self):
 
701
        return self.transport
 
702
 
795
703
    def is_control_filename(self, filename):
796
704
        """True if filename is the name of a path which is reserved for bzrdir's.
797
705
 
799
707
 
800
708
        This is true IF and ONLY IF the filename is part of the namespace reserved
801
709
        for bzr control dirs. Currently this is the '.bzr' directory in the root
802
 
        of the root_transport. it is expected that plugins will need to extend
803
 
        this in the future - for instance to make bzr talk with svn working
804
 
        trees.
 
710
        of the root_transport. 
805
711
        """
806
712
        # this might be better on the BzrDirFormat class because it refers to
807
713
        # all the possible bzrdir disk formats.
811
717
        # add new tests for it to the appropriate place.
812
718
        return filename == '.bzr' or filename.startswith('.bzr/')
813
719
 
814
 
    def needs_format_conversion(self, format=None):
815
 
        """Return true if this bzrdir needs convert_format run on it.
816
 
 
817
 
        For instance, if the repository format is out of date but the
818
 
        branch and working tree are not, this should return True.
819
 
 
820
 
        :param format: Optional parameter indicating a specific desired
821
 
                       format we plan to arrive at.
822
 
        """
823
 
        raise NotImplementedError(self.needs_format_conversion)
824
 
 
825
720
    @staticmethod
826
721
    def open_unsupported(base):
827
722
        """Open a branch which is not supported."""
850
745
        # the redirections.
851
746
        base = transport.base
852
747
        def find_format(transport):
853
 
            return transport, BzrDirFormat.find_format(
 
748
            return transport, controldir.ControlDirFormat.find_format(
854
749
                transport, _server_formats=_server_formats)
855
750
 
856
751
        def redirected(transport, e, redirection_notice):
871
766
        BzrDir._check_supported(format, _unsupported)
872
767
        return format.open(transport, _found=True)
873
768
 
874
 
    def open_branch(self, unsupported=False, ignore_fallbacks=False):
875
 
        """Open the branch object at this BzrDir if one is present.
876
 
 
877
 
        If unsupported is True, then no longer supported branch formats can
878
 
        still be opened.
879
 
 
880
 
        TODO: static convenience version of this?
881
 
        """
882
 
        raise NotImplementedError(self.open_branch)
883
 
 
884
769
    @staticmethod
885
770
    def open_containing(url, possible_transports=None):
886
771
        """Open an existing branch which contains url.
924
809
                raise errors.NotBranchError(path=url)
925
810
            a_transport = new_t
926
811
 
927
 
    def _get_tree_branch(self):
928
 
        """Return the branch and tree, if any, for this bzrdir.
929
 
 
930
 
        Return None for tree if not present or inaccessible.
931
 
        Raise NotBranchError if no branch is present.
932
 
        :return: (tree, branch)
933
 
        """
934
 
        try:
935
 
            tree = self.open_workingtree()
936
 
        except (errors.NoWorkingTree, errors.NotLocalUrl):
937
 
            tree = None
938
 
            branch = self.open_branch()
939
 
        else:
940
 
            branch = tree.branch
941
 
        return tree, branch
942
 
 
943
812
    @classmethod
944
813
    def open_tree_or_branch(klass, location):
945
814
        """Return the branch and working tree at a location.
991
860
                raise errors.NotBranchError(location)
992
861
        return tree, branch, branch.repository, relpath
993
862
 
994
 
    def open_repository(self, _unsupported=False):
995
 
        """Open the repository object at this BzrDir if one is present.
996
 
 
997
 
        This will not follow the Branch object pointer - it's strictly a direct
998
 
        open facility. Most client code should use open_branch().repository to
999
 
        get at a repository.
1000
 
 
1001
 
        :param _unsupported: a private parameter, not part of the api.
1002
 
        TODO: static convenience version of this?
1003
 
        """
1004
 
        raise NotImplementedError(self.open_repository)
1005
 
 
1006
 
    def open_workingtree(self, _unsupported=False,
1007
 
                         recommend_upgrade=True, from_branch=None):
1008
 
        """Open the workingtree object at this BzrDir if one is present.
1009
 
 
1010
 
        :param recommend_upgrade: Optional keyword parameter, when True (the
1011
 
            default), emit through the ui module a recommendation that the user
1012
 
            upgrade the working tree when the workingtree being opened is old
1013
 
            (but still fully supported).
1014
 
        :param from_branch: override bzrdir branch (for lightweight checkouts)
1015
 
        """
1016
 
        raise NotImplementedError(self.open_workingtree)
1017
 
 
1018
 
    def has_branch(self):
1019
 
        """Tell if this bzrdir contains a branch.
1020
 
 
1021
 
        Note: if you're going to open the branch, you should just go ahead
1022
 
        and try, and not ask permission first.  (This method just opens the
1023
 
        branch and discards it, and that's somewhat expensive.)
1024
 
        """
1025
 
        try:
1026
 
            self.open_branch()
1027
 
            return True
1028
 
        except errors.NotBranchError:
1029
 
            return False
1030
 
 
1031
 
    def has_workingtree(self):
1032
 
        """Tell if this bzrdir contains a working tree.
1033
 
 
1034
 
        This will still raise an exception if the bzrdir has a workingtree that
1035
 
        is remote & inaccessible.
1036
 
 
1037
 
        Note: if you're going to open the working tree, you should just go ahead
1038
 
        and try, and not ask permission first.  (This method just opens the
1039
 
        workingtree and discards it, and that's somewhat expensive.)
1040
 
        """
1041
 
        try:
1042
 
            self.open_workingtree(recommend_upgrade=False)
1043
 
            return True
1044
 
        except errors.NoWorkingTree:
1045
 
            return False
1046
 
 
1047
863
    def _cloning_metadir(self):
1048
864
        """Produce a metadir suitable for cloning with.
1049
865
 
1107
923
            format.require_stacking()
1108
924
        return format
1109
925
 
1110
 
    def checkout_metadir(self):
1111
 
        return self.cloning_metadir()
1112
 
 
1113
 
    def sprout(self, url, revision_id=None, force_new_repo=False,
1114
 
               recurse='down', possible_transports=None,
1115
 
               accelerator_tree=None, hardlink=False, stacked=False,
1116
 
               source_branch=None, create_tree_if_local=True):
1117
 
        """Create a copy of this bzrdir prepared for use as a new line of
1118
 
        development.
1119
 
 
1120
 
        If url's last component does not exist, it will be created.
1121
 
 
1122
 
        Attributes related to the identity of the source branch like
1123
 
        branch nickname will be cleaned, a working tree is created
1124
 
        whether one existed before or not; and a local branch is always
1125
 
        created.
1126
 
 
1127
 
        if revision_id is not None, then the clone operation may tune
1128
 
            itself to download less data.
1129
 
        :param accelerator_tree: A tree which can be used for retrieving file
1130
 
            contents more quickly than the revision tree, i.e. a workingtree.
1131
 
            The revision tree will be used for cases where accelerator_tree's
1132
 
            content is different.
1133
 
        :param hardlink: If true, hard-link files from accelerator_tree,
1134
 
            where possible.
1135
 
        :param stacked: If true, create a stacked branch referring to the
1136
 
            location of this control directory.
1137
 
        :param create_tree_if_local: If true, a working-tree will be created
1138
 
            when working locally.
 
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.
1139
934
        """
1140
 
        target_transport = get_transport(url, possible_transports)
1141
 
        target_transport.ensure_base()
1142
 
        cloning_format = self.cloning_metadir(stacked)
1143
 
        # Create/update the result branch
1144
 
        result = cloning_format.initialize_on_transport(target_transport)
1145
 
        # if a stacked branch wasn't requested, we don't create one
1146
 
        # even if the origin was stacked
1147
 
        stacked_branch_url = None
1148
 
        if source_branch is not None:
1149
 
            if stacked:
1150
 
                stacked_branch_url = self.root_transport.base
1151
 
            source_repository = source_branch.repository
1152
 
        else:
1153
 
            try:
1154
 
                source_branch = self.open_branch()
1155
 
                source_repository = source_branch.repository
1156
 
                if stacked:
1157
 
                    stacked_branch_url = self.root_transport.base
1158
 
            except errors.NotBranchError:
1159
 
                source_branch = None
1160
 
                try:
1161
 
                    source_repository = self.open_repository()
1162
 
                except errors.NoRepositoryPresent:
1163
 
                    source_repository = None
1164
 
        repository_policy = result.determine_repository_policy(
1165
 
            force_new_repo, stacked_branch_url, require_stacking=stacked)
1166
 
        result_repo, is_new_repo = repository_policy.acquire_repository()
1167
 
        if is_new_repo and revision_id is not None and not stacked:
1168
 
            fetch_spec = graph.PendingAncestryResult(
1169
 
                [revision_id], source_repository)
1170
 
        else:
1171
 
            fetch_spec = None
1172
 
        if source_repository is not None:
1173
 
            # Fetch while stacked to prevent unstacked fetch from
1174
 
            # Branch.sprout.
1175
 
            if fetch_spec is None:
1176
 
                result_repo.fetch(source_repository, revision_id=revision_id)
1177
 
            else:
1178
 
                result_repo.fetch(source_repository, fetch_spec=fetch_spec)
1179
 
 
1180
 
        if source_branch is None:
1181
 
            # this is for sprouting a bzrdir without a branch; is that
1182
 
            # actually useful?
1183
 
            # Not especially, but it's part of the contract.
1184
 
            result_branch = result.create_branch()
1185
 
        else:
1186
 
            result_branch = source_branch.sprout(result,
1187
 
                revision_id=revision_id, repository_policy=repository_policy)
1188
 
        mutter("created new branch %r" % (result_branch,))
1189
 
 
1190
 
        # Create/update the result working tree
1191
 
        if (create_tree_if_local and
1192
 
            isinstance(target_transport, local.LocalTransport) and
1193
 
            (result_repo is None or result_repo.make_working_trees())):
1194
 
            wt = result.create_workingtree(accelerator_tree=accelerator_tree,
1195
 
                hardlink=hardlink)
1196
 
            wt.lock_write()
1197
 
            try:
1198
 
                if wt.path2id('') is None:
1199
 
                    try:
1200
 
                        wt.set_root_id(self.open_workingtree.get_root_id())
1201
 
                    except errors.NoWorkingTree:
1202
 
                        pass
1203
 
            finally:
1204
 
                wt.unlock()
1205
 
        else:
1206
 
            wt = None
1207
 
        if recurse == 'down':
1208
 
            if wt is not None:
1209
 
                basis = wt.basis_tree()
1210
 
                basis.lock_read()
1211
 
                subtrees = basis.iter_references()
1212
 
            elif result_branch is not None:
1213
 
                basis = result_branch.basis_tree()
1214
 
                basis.lock_read()
1215
 
                subtrees = basis.iter_references()
1216
 
            elif source_branch is not None:
1217
 
                basis = source_branch.basis_tree()
1218
 
                basis.lock_read()
1219
 
                subtrees = basis.iter_references()
1220
 
            else:
1221
 
                subtrees = []
1222
 
                basis = None
1223
 
            try:
1224
 
                for path, file_id in subtrees:
1225
 
                    target = urlutils.join(url, urlutils.escape(path))
1226
 
                    sublocation = source_branch.reference_parent(file_id, path)
1227
 
                    sublocation.bzrdir.sprout(target,
1228
 
                        basis.get_reference_revision(file_id, path),
1229
 
                        force_new_repo=force_new_repo, recurse=recurse,
1230
 
                        stacked=stacked)
1231
 
            finally:
1232
 
                if basis is not None:
1233
 
                    basis.unlock()
1234
 
        return result
1235
 
 
1236
 
    def push_branch(self, source, revision_id=None, overwrite=False, 
1237
 
        remember=False, create_prefix=False):
1238
 
        """Push the source branch into this BzrDir."""
1239
 
        br_to = None
1240
 
        # If we can open a branch, use its direct repository, otherwise see
1241
 
        # if there is a repository without a branch.
1242
 
        try:
1243
 
            br_to = self.open_branch()
1244
 
        except errors.NotBranchError:
1245
 
            # Didn't find a branch, can we find a repository?
1246
 
            repository_to = self.find_repository()
1247
 
        else:
1248
 
            # Found a branch, so we must have found a repository
1249
 
            repository_to = br_to.repository
1250
 
 
1251
 
        push_result = PushResult()
1252
 
        push_result.source_branch = source
1253
 
        if br_to is None:
1254
 
            # We have a repository but no branch, copy the revisions, and then
1255
 
            # create a branch.
1256
 
            repository_to.fetch(source.repository, revision_id=revision_id)
1257
 
            br_to = source.clone(self, revision_id=revision_id)
1258
 
            if source.get_push_location() is None or remember:
1259
 
                source.set_push_location(br_to.base)
1260
 
            push_result.stacked_on = None
1261
 
            push_result.branch_push_result = None
1262
 
            push_result.old_revno = None
1263
 
            push_result.old_revid = _mod_revision.NULL_REVISION
1264
 
            push_result.target_branch = br_to
1265
 
            push_result.master_branch = None
1266
 
            push_result.workingtree_updated = False
1267
 
        else:
1268
 
            # We have successfully opened the branch, remember if necessary:
1269
 
            if source.get_push_location() is None or remember:
1270
 
                source.set_push_location(br_to.base)
1271
 
            try:
1272
 
                tree_to = self.open_workingtree()
1273
 
            except errors.NotLocalUrl:
1274
 
                push_result.branch_push_result = source.push(br_to, 
1275
 
                    overwrite, stop_revision=revision_id)
1276
 
                push_result.workingtree_updated = False
1277
 
            except errors.NoWorkingTree:
1278
 
                push_result.branch_push_result = source.push(br_to,
1279
 
                    overwrite, stop_revision=revision_id)
1280
 
                push_result.workingtree_updated = None # Not applicable
1281
 
            else:
1282
 
                tree_to.lock_write()
1283
 
                try:
1284
 
                    push_result.branch_push_result = source.push(
1285
 
                        tree_to.branch, overwrite, stop_revision=revision_id)
1286
 
                    tree_to.update()
1287
 
                finally:
1288
 
                    tree_to.unlock()
1289
 
                push_result.workingtree_updated = True
1290
 
            push_result.old_revno = push_result.branch_push_result.old_revno
1291
 
            push_result.old_revid = push_result.branch_push_result.old_revid
1292
 
            push_result.target_branch = \
1293
 
                push_result.branch_push_result.target_branch
1294
 
        return push_result
 
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
 
1295
944
 
1296
945
 
1297
946
class BzrDirHooks(hooks.Hooks):
1303
952
        self.create_hook(hooks.HookPoint('pre_open',
1304
953
            "Invoked before attempting to open a BzrDir with the transport "
1305
954
            "that the open will use.", (1, 14), None))
 
955
        self.create_hook(hooks.HookPoint('post_repo_init',
 
956
            "Invoked after a repository has been initialized. "
 
957
            "post_repo_init is called with a "
 
958
            "bzrlib.bzrdir.RepoInitHookParams.",
 
959
            (2, 2), None))
1306
960
 
1307
961
# install the default hooks
1308
962
BzrDir.hooks = BzrDirHooks()
1309
963
 
1310
964
 
 
965
class RepoInitHookParams(object):
 
966
    """Object holding parameters passed to *_repo_init hooks.
 
967
 
 
968
    There are 4 fields that hooks may wish to access:
 
969
 
 
970
    :ivar repository: Repository created
 
971
    :ivar format: Repository format
 
972
    :ivar bzrdir: The bzrdir for the repository
 
973
    :ivar shared: The repository is shared
 
974
    """
 
975
 
 
976
    def __init__(self, repository, format, a_bzrdir, shared):
 
977
        """Create a group of RepoInitHook parameters.
 
978
 
 
979
        :param repository: Repository created
 
980
        :param format: Repository format
 
981
        :param bzrdir: The bzrdir for the repository
 
982
        :param shared: The repository is shared
 
983
        """
 
984
        self.repository = repository
 
985
        self.format = format
 
986
        self.bzrdir = a_bzrdir
 
987
        self.shared = shared
 
988
 
 
989
    def __eq__(self, other):
 
990
        return self.__dict__ == other.__dict__
 
991
 
 
992
    def __repr__(self):
 
993
        if self.repository:
 
994
            return "<%s for %s>" % (self.__class__.__name__,
 
995
                self.repository)
 
996
        else:
 
997
            return "<%s for %s>" % (self.__class__.__name__,
 
998
                self.bzrdir)
 
999
 
 
1000
 
1311
1001
class BzrDirPreSplitOut(BzrDir):
1312
1002
    """A common class for the all-in-one formats."""
1313
1003
 
1326
1016
    def cloning_metadir(self, require_stacking=False):
1327
1017
        """Produce a metadir suitable for cloning with."""
1328
1018
        if require_stacking:
1329
 
            return format_registry.make_bzrdir('1.6')
 
1019
            return controldir.format_registry.make_bzrdir('1.6')
1330
1020
        return self._format.__class__()
1331
1021
 
1332
1022
    def clone(self, url, revision_id=None, force_new_repo=False,
1352
1042
            tree.clone(result)
1353
1043
        return result
1354
1044
 
1355
 
    def create_branch(self):
 
1045
    def create_branch(self, name=None):
1356
1046
        """See BzrDir.create_branch."""
1357
 
        return self._format.get_branch_format().initialize(self)
 
1047
        return self._format.get_branch_format().initialize(self, name=name)
1358
1048
 
1359
 
    def destroy_branch(self):
 
1049
    def destroy_branch(self, name=None):
1360
1050
        """See BzrDir.destroy_branch."""
1361
1051
        raise errors.UnsupportedOperation(self.destroy_branch, self)
1362
1052
 
1418
1108
        raise errors.UnsupportedOperation(self.destroy_workingtree_metadata,
1419
1109
                                          self)
1420
1110
 
1421
 
    def get_branch_transport(self, branch_format):
 
1111
    def get_branch_transport(self, branch_format, name=None):
1422
1112
        """See BzrDir.get_branch_transport()."""
 
1113
        if name is not None:
 
1114
            raise errors.NoColocatedBranchSupport(self)
1423
1115
        if branch_format is None:
1424
1116
            return self.transport
1425
1117
        try:
1458
1150
            format = BzrDirFormat.get_default_format()
1459
1151
        return not isinstance(self._format, format.__class__)
1460
1152
 
1461
 
    def open_branch(self, unsupported=False, ignore_fallbacks=False):
 
1153
    def open_branch(self, name=None, unsupported=False,
 
1154
                    ignore_fallbacks=False):
1462
1155
        """See BzrDir.open_branch."""
1463
1156
        from bzrlib.branch import BzrBranchFormat4
1464
1157
        format = BzrBranchFormat4()
1465
1158
        self._check_supported(format, unsupported)
1466
 
        return format.open(self, _found=True)
 
1159
        return format.open(self, name, _found=True)
1467
1160
 
1468
1161
    def sprout(self, url, revision_id=None, force_new_repo=False,
1469
1162
               possible_transports=None, accelerator_tree=None,
1530
1223
    This is a deprecated format and may be removed after sept 2006.
1531
1224
    """
1532
1225
 
 
1226
    def has_workingtree(self):
 
1227
        """See BzrDir.has_workingtree."""
 
1228
        return True
 
1229
    
1533
1230
    def open_repository(self):
1534
1231
        """See BzrDir.open_repository."""
1535
1232
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
1551
1248
    This is a deprecated format and may be removed after sept 2006.
1552
1249
    """
1553
1250
 
 
1251
    def has_workingtree(self):
 
1252
        """See BzrDir.has_workingtree."""
 
1253
        return True
 
1254
    
1554
1255
    def open_repository(self):
1555
1256
        """See BzrDir.open_repository."""
1556
1257
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
1578
1279
        """See BzrDir.can_convert_format()."""
1579
1280
        return True
1580
1281
 
1581
 
    def create_branch(self):
 
1282
    def create_branch(self, name=None):
1582
1283
        """See BzrDir.create_branch."""
1583
 
        return self._format.get_branch_format().initialize(self)
 
1284
        return self._format.get_branch_format().initialize(self, name=name)
1584
1285
 
1585
 
    def destroy_branch(self):
 
1286
    def destroy_branch(self, name=None):
1586
1287
        """See BzrDir.create_branch."""
 
1288
        if name is not None:
 
1289
            raise errors.NoColocatedBranchSupport(self)
1587
1290
        self.transport.delete_tree('branch')
1588
1291
 
1589
1292
    def create_repository(self, shared=False):
1612
1315
    def destroy_workingtree_metadata(self):
1613
1316
        self.transport.delete_tree('checkout')
1614
1317
 
1615
 
    def find_branch_format(self):
 
1318
    def find_branch_format(self, name=None):
1616
1319
        """Find the branch 'format' for this bzrdir.
1617
1320
 
1618
1321
        This might be a synthetic object for e.g. RemoteBranch and SVN.
1619
1322
        """
1620
1323
        from bzrlib.branch import BranchFormat
1621
 
        return BranchFormat.find_format(self)
 
1324
        return BranchFormat.find_format(self, name=name)
1622
1325
 
1623
1326
    def _get_mkdir_mode(self):
1624
1327
        """Figure out the mode to use when creating a bzrdir subdir."""
1626
1329
                                     lockable_files.TransportLock)
1627
1330
        return temp_control._dir_mode
1628
1331
 
1629
 
    def get_branch_reference(self):
 
1332
    def get_branch_reference(self, name=None):
1630
1333
        """See BzrDir.get_branch_reference()."""
1631
1334
        from bzrlib.branch import BranchFormat
1632
 
        format = BranchFormat.find_format(self)
1633
 
        return format.get_reference(self)
 
1335
        format = BranchFormat.find_format(self, name=name)
 
1336
        return format.get_reference(self, name=name)
1634
1337
 
1635
 
    def get_branch_transport(self, branch_format):
 
1338
    def get_branch_transport(self, branch_format, name=None):
1636
1339
        """See BzrDir.get_branch_transport()."""
 
1340
        if name is not None:
 
1341
            raise errors.NoColocatedBranchSupport(self)
1637
1342
        # XXX: this shouldn't implicitly create the directory if it's just
1638
1343
        # promising to get a transport -- mbp 20090727
1639
1344
        if branch_format is None:
1676
1381
            pass
1677
1382
        return self.transport.clone('checkout')
1678
1383
 
 
1384
    def has_workingtree(self):
 
1385
        """Tell if this bzrdir contains a working tree.
 
1386
 
 
1387
        This will still raise an exception if the bzrdir has a workingtree that
 
1388
        is remote & inaccessible.
 
1389
 
 
1390
        Note: if you're going to open the working tree, you should just go
 
1391
        ahead and try, and not ask permission first.
 
1392
        """
 
1393
        from bzrlib.workingtree import WorkingTreeFormat
 
1394
        try:
 
1395
            WorkingTreeFormat.find_format(self)
 
1396
        except errors.NoWorkingTree:
 
1397
            return False
 
1398
        return True
 
1399
 
1679
1400
    def needs_format_conversion(self, format=None):
1680
1401
        """See BzrDir.needs_format_conversion()."""
1681
1402
        if format is None:
1694
1415
                return True
1695
1416
        except errors.NoRepositoryPresent:
1696
1417
            pass
1697
 
        try:
1698
 
            if not isinstance(self.open_branch()._format,
 
1418
        for branch in self.list_branches():
 
1419
            if not isinstance(branch._format,
1699
1420
                              format.get_branch_format().__class__):
1700
1421
                # the branch needs an upgrade.
1701
1422
                return True
1702
 
        except errors.NotBranchError:
1703
 
            pass
1704
1423
        try:
1705
1424
            my_wt = self.open_workingtree(recommend_upgrade=False)
1706
1425
            if not isinstance(my_wt._format,
1711
1430
            pass
1712
1431
        return False
1713
1432
 
1714
 
    def open_branch(self, unsupported=False, ignore_fallbacks=False):
 
1433
    def open_branch(self, name=None, unsupported=False,
 
1434
                    ignore_fallbacks=False):
1715
1435
        """See BzrDir.open_branch."""
1716
 
        format = self.find_branch_format()
 
1436
        format = self.find_branch_format(name=name)
1717
1437
        self._check_supported(format, unsupported)
1718
 
        return format.open(self, _found=True, ignore_fallbacks=ignore_fallbacks)
 
1438
        return format.open(self, name=name,
 
1439
            _found=True, ignore_fallbacks=ignore_fallbacks)
1719
1440
 
1720
1441
    def open_repository(self, unsupported=False):
1721
1442
        """See BzrDir.open_repository."""
1738
1459
        return config.TransportConfig(self.transport, 'control.conf')
1739
1460
 
1740
1461
 
1741
 
class BzrDirFormat(object):
1742
 
    """An encapsulation of the initialization and open routines for a format.
1743
 
 
1744
 
    Formats provide three things:
1745
 
     * An initialization routine,
1746
 
     * a format string,
1747
 
     * an open routine.
 
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.
1748
1522
 
1749
1523
    Formats are placed in a dict by their format string for reference
1750
1524
    during bzrdir opening. These should be subclasses of BzrDirFormat
1755
1529
    object will be created every system load.
1756
1530
    """
1757
1531
 
1758
 
    _default_format = None
1759
 
    """The default format used for new .bzr dirs."""
1760
 
 
1761
 
    _formats = {}
1762
 
    """The known formats."""
1763
 
 
1764
 
    _control_formats = []
1765
 
    """The registered control formats - .bzr, ....
1766
 
 
1767
 
    This is a list of BzrDirFormat objects.
1768
 
    """
1769
 
 
1770
 
    _control_server_formats = []
1771
 
    """The registered control server formats, e.g. RemoteBzrDirs.
1772
 
 
1773
 
    This is a list of BzrDirFormat objects.
1774
 
    """
1775
 
 
1776
1532
    _lock_file_name = 'branch-lock'
1777
1533
 
1778
1534
    # _lock_class must be set in subclasses to the lock type, typ.
1779
1535
    # TransportLock or LockDir
1780
1536
 
1781
 
    @classmethod
1782
 
    def find_format(klass, transport, _server_formats=True):
1783
 
        """Return the format present at transport."""
1784
 
        if _server_formats:
1785
 
            formats = klass._control_server_formats + klass._control_formats
1786
 
        else:
1787
 
            formats = klass._control_formats
1788
 
        for format in formats:
1789
 
            try:
1790
 
                return format.probe_transport(transport)
1791
 
            except errors.NotBranchError:
1792
 
                # this format does not find a control dir here.
1793
 
                pass
1794
 
        raise errors.NotBranchError(path=transport.base)
1795
 
 
1796
 
    @classmethod
1797
 
    def probe_transport(klass, transport):
1798
 
        """Return the .bzrdir style format present in a directory."""
1799
 
        try:
1800
 
            format_string = transport.get(".bzr/branch-format").read()
1801
 
        except errors.NoSuchFile:
1802
 
            raise errors.NotBranchError(path=transport.base)
1803
 
 
1804
 
        try:
1805
 
            return klass._formats[format_string]
1806
 
        except KeyError:
1807
 
            raise errors.UnknownFormatError(format=format_string, kind='bzrdir')
1808
 
 
1809
 
    @classmethod
1810
 
    def get_default_format(klass):
1811
 
        """Return the current default format."""
1812
 
        return klass._default_format
1813
 
 
1814
1537
    def get_format_string(self):
1815
1538
        """Return the ASCII format string that identifies this format."""
1816
1539
        raise NotImplementedError(self.get_format_string)
1817
1540
 
1818
 
    def get_format_description(self):
1819
 
        """Return the short description for this format."""
1820
 
        raise NotImplementedError(self.get_format_description)
1821
 
 
1822
 
    def get_converter(self, format=None):
1823
 
        """Return the converter to use to convert bzrdirs needing converts.
1824
 
 
1825
 
        This returns a bzrlib.bzrdir.Converter object.
1826
 
 
1827
 
        This should return the best upgrader to step this format towards the
1828
 
        current default format. In the case of plugins we can/should provide
1829
 
        some means for them to extend the range of returnable converters.
1830
 
 
1831
 
        :param format: Optional format to override the default format of the
1832
 
                       library.
1833
 
        """
1834
 
        raise NotImplementedError(self.get_converter)
1835
 
 
1836
 
    def initialize(self, url, possible_transports=None):
1837
 
        """Create a bzr control dir at this url and return an opened copy.
1838
 
 
1839
 
        While not deprecated, this method is very specific and its use will
1840
 
        lead to many round trips to setup a working environment. See
1841
 
        initialize_on_transport_ex for a [nearly] all-in-one method.
1842
 
 
1843
 
        Subclasses should typically override initialize_on_transport
1844
 
        instead of this method.
1845
 
        """
1846
 
        return self.initialize_on_transport(get_transport(url,
1847
 
                                                          possible_transports))
1848
 
 
1849
1541
    def initialize_on_transport(self, transport):
1850
1542
        """Initialize a new bzrdir in the base directory of a Transport."""
1851
1543
        try:
1999
1691
            control_files.unlock()
2000
1692
        return self.open(transport, _found=True)
2001
1693
 
2002
 
    def is_supported(self):
2003
 
        """Is this format supported?
2004
 
 
2005
 
        Supported formats must be initializable and openable.
2006
 
        Unsupported formats may not support initialization or committing or
2007
 
        some other features depending on the reason for not being supported.
2008
 
        """
2009
 
        return True
2010
 
 
2011
 
    def network_name(self):
2012
 
        """A simple byte string uniquely identifying this format for RPC calls.
2013
 
 
2014
 
        Bzr control formats use thir disk format string to identify the format
2015
 
        over the wire. Its possible that other control formats have more
2016
 
        complex detection requirements, so we permit them to use any unique and
2017
 
        immutable string they desire.
2018
 
        """
2019
 
        raise NotImplementedError(self.network_name)
2020
 
 
2021
 
    def same_model(self, target_format):
2022
 
        return (self.repository_format.rich_root_data ==
2023
 
            target_format.rich_root_data)
2024
 
 
2025
 
    @classmethod
2026
 
    def known_formats(klass):
2027
 
        """Return all the known formats.
2028
 
 
2029
 
        Concrete formats should override _known_formats.
2030
 
        """
2031
 
        # There is double indirection here to make sure that control
2032
 
        # formats used by more than one dir format will only be probed
2033
 
        # once. This can otherwise be quite expensive for remote connections.
2034
 
        result = set()
2035
 
        for format in klass._control_formats:
2036
 
            result.update(format._known_formats())
2037
 
        return result
2038
 
 
2039
 
    @classmethod
2040
 
    def _known_formats(klass):
2041
 
        """Return the known format instances for this control format."""
2042
 
        return set(klass._formats.values())
2043
 
 
2044
1694
    def open(self, transport, _found=False):
2045
1695
        """Return an instance of this format for the dir transport points at.
2046
1696
 
2047
1697
        _found is a private parameter, do not use it.
2048
1698
        """
2049
1699
        if not _found:
2050
 
            found_format = BzrDirFormat.find_format(transport)
 
1700
            found_format = controldir.ControlDirFormat.find_format(transport)
2051
1701
            if not isinstance(found_format, self.__class__):
2052
1702
                raise AssertionError("%s was asked to open %s, but it seems to need "
2053
1703
                        "format %s"
2067
1717
 
2068
1718
    @classmethod
2069
1719
    def register_format(klass, format):
2070
 
        klass._formats[format.get_format_string()] = format
 
1720
        BzrProber.register_bzrdir_format(format)
2071
1721
        # bzr native formats have a network name of their format string.
2072
1722
        network_format_registry.register(format.get_format_string(), format.__class__)
2073
 
 
2074
 
    @classmethod
2075
 
    def register_control_format(klass, format):
2076
 
        """Register a format that does not use '.bzr' for its control dir.
2077
 
 
2078
 
        TODO: This should be pulled up into a 'ControlDirFormat' base class
2079
 
        which BzrDirFormat can inherit from, and renamed to register_format
2080
 
        there. It has been done without that for now for simplicity of
2081
 
        implementation.
2082
 
        """
2083
 
        klass._control_formats.append(format)
2084
 
 
2085
 
    @classmethod
2086
 
    def register_control_server_format(klass, format):
2087
 
        """Register a control format for client-server environments.
2088
 
 
2089
 
        These formats will be tried before ones registered with
2090
 
        register_control_format.  This gives implementations that decide to the
2091
 
        chance to grab it before anything looks at the contents of the format
2092
 
        file.
2093
 
        """
2094
 
        klass._control_server_formats.append(format)
2095
 
 
2096
 
    @classmethod
2097
 
    def _set_default_format(klass, format):
2098
 
        """Set default format (for testing behavior of defaults only)"""
2099
 
        klass._default_format = format
2100
 
 
2101
 
    def __str__(self):
2102
 
        # Trim the newline
2103
 
        return self.get_format_description().rstrip()
 
1723
        controldir.ControlDirFormat.register_format(format)
2104
1724
 
2105
1725
    def _supply_sub_formats_to(self, other_format):
2106
1726
        """Give other_format the same values for sub formats as this has.
2116
1736
 
2117
1737
    @classmethod
2118
1738
    def unregister_format(klass, format):
2119
 
        del klass._formats[format.get_format_string()]
2120
 
 
2121
 
    @classmethod
2122
 
    def unregister_control_format(klass, format):
2123
 
        klass._control_formats.remove(format)
 
1739
        BzrProber.unregister_bzrdir_format(format)
 
1740
        controldir.ControlDirFormat.unregister_format(format)
 
1741
        network_format_registry.remove(format.get_format_string())
2124
1742
 
2125
1743
 
2126
1744
class BzrDirFormat4(BzrDirFormat):
2538
2156
"""
2539
2157
 
2540
2158
 
2541
 
# Register bzr control format
2542
 
BzrDirFormat.register_control_format(BzrDirFormat)
2543
 
 
2544
2159
# Register bzr formats
2545
2160
BzrDirFormat.register_format(BzrDirFormat4())
2546
2161
BzrDirFormat.register_format(BzrDirFormat5())
2547
2162
BzrDirFormat.register_format(BzrDirFormat6())
2548
2163
__default_format = BzrDirMetaFormat1()
2549
2164
BzrDirFormat.register_format(__default_format)
2550
 
BzrDirFormat._default_format = __default_format
 
2165
controldir.ControlDirFormat._default_format = __default_format
2551
2166
 
2552
2167
 
2553
2168
class Converter(object):
2579
2194
    def convert(self, to_convert, pb):
2580
2195
        """See Converter.convert()."""
2581
2196
        self.bzrdir = to_convert
2582
 
        self.pb = pb
2583
 
        self.pb.note('starting upgrade from format 4 to 5')
2584
 
        if isinstance(self.bzrdir.transport, local.LocalTransport):
2585
 
            self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
2586
 
        self._convert_to_weaves()
2587
 
        return BzrDir.open(self.bzrdir.root_transport.base)
 
2197
        if pb is not None:
 
2198
            warnings.warn("pb parameter to convert() is deprecated")
 
2199
        self.pb = ui.ui_factory.nested_progress_bar()
 
2200
        try:
 
2201
            ui.ui_factory.note('starting upgrade from format 4 to 5')
 
2202
            if isinstance(self.bzrdir.transport, local.LocalTransport):
 
2203
                self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
 
2204
            self._convert_to_weaves()
 
2205
            return BzrDir.open(self.bzrdir.user_url)
 
2206
        finally:
 
2207
            self.pb.finished()
2588
2208
 
2589
2209
    def _convert_to_weaves(self):
2590
 
        self.pb.note('note: upgrade may be faster if all store files are ungzipped first')
 
2210
        ui.ui_factory.note('note: upgrade may be faster if all store files are ungzipped first')
2591
2211
        try:
2592
2212
            # TODO permissions
2593
2213
            stat = self.bzrdir.transport.stat('weaves')
2621
2241
        self.pb.clear()
2622
2242
        self._write_all_weaves()
2623
2243
        self._write_all_revs()
2624
 
        self.pb.note('upgraded to weaves:')
2625
 
        self.pb.note('  %6d revisions and inventories', len(self.revisions))
2626
 
        self.pb.note('  %6d revisions not present', len(self.absent_revisions))
2627
 
        self.pb.note('  %6d texts', self.text_count)
 
2244
        ui.ui_factory.note('upgraded to weaves:')
 
2245
        ui.ui_factory.note('  %6d revisions and inventories' % len(self.revisions))
 
2246
        ui.ui_factory.note('  %6d revisions not present' % len(self.absent_revisions))
 
2247
        ui.ui_factory.note('  %6d texts' % self.text_count)
2628
2248
        self._cleanup_spare_files_after_format4()
2629
2249
        self.branch._transport.put_bytes(
2630
2250
            'branch-format',
2698
2318
                       len(self.known_revisions))
2699
2319
        if not self.branch.repository.has_revision(rev_id):
2700
2320
            self.pb.clear()
2701
 
            self.pb.note('revision {%s} not present in branch; '
2702
 
                         'will be converted as a ghost',
 
2321
            ui.ui_factory.note('revision {%s} not present in branch; '
 
2322
                         'will be converted as a ghost' %
2703
2323
                         rev_id)
2704
2324
            self.absent_revisions.add(rev_id)
2705
2325
        else:
2710
2330
            self.revisions[rev_id] = rev
2711
2331
 
2712
2332
    def _load_old_inventory(self, rev_id):
2713
 
        old_inv_xml = self.branch.repository.inventory_store.get(rev_id).read()
 
2333
        f = self.branch.repository.inventory_store.get(rev_id)
 
2334
        try:
 
2335
            old_inv_xml = f.read()
 
2336
        finally:
 
2337
            f.close()
2714
2338
        inv = xml4.serializer_v4.read_inventory_from_string(old_inv_xml)
2715
2339
        inv.revision_id = rev_id
2716
2340
        rev = self.revisions[rev_id]
2772
2396
        previous_entries = dict((head, parent_candiate_entries[head]) for head
2773
2397
            in heads)
2774
2398
        self.snapshot_ie(previous_entries, ie, w, rev_id)
2775
 
        del ie.text_id
2776
2399
 
2777
2400
    def get_parent_map(self, revision_ids):
2778
2401
        """See graph.StackedParentsProvider.get_parent_map"""
2794
2417
                ie.revision = previous_ie.revision
2795
2418
                return
2796
2419
        if ie.has_text():
2797
 
            text = self.branch.repository._text_store.get(ie.text_id)
2798
 
            file_lines = text.readlines()
 
2420
            f = self.branch.repository._text_store.get(ie.text_id)
 
2421
            try:
 
2422
                file_lines = f.readlines()
 
2423
            finally:
 
2424
                f.close()
2799
2425
            w.add_lines(rev_id, previous_revisions, file_lines)
2800
2426
            self.text_count += 1
2801
2427
        else:
2831
2457
    def convert(self, to_convert, pb):
2832
2458
        """See Converter.convert()."""
2833
2459
        self.bzrdir = to_convert
2834
 
        self.pb = pb
2835
 
        self.pb.note('starting upgrade from format 5 to 6')
2836
 
        self._convert_to_prefixed()
2837
 
        return BzrDir.open(self.bzrdir.root_transport.base)
 
2460
        pb = ui.ui_factory.nested_progress_bar()
 
2461
        try:
 
2462
            ui.ui_factory.note('starting upgrade from format 5 to 6')
 
2463
            self._convert_to_prefixed()
 
2464
            return BzrDir.open(self.bzrdir.user_url)
 
2465
        finally:
 
2466
            pb.finished()
2838
2467
 
2839
2468
    def _convert_to_prefixed(self):
2840
2469
        from bzrlib.store import TransportStore
2841
2470
        self.bzrdir.transport.delete('branch-format')
2842
2471
        for store_name in ["weaves", "revision-store"]:
2843
 
            self.pb.note("adding prefixes to %s" % store_name)
 
2472
            ui.ui_factory.note("adding prefixes to %s" % store_name)
2844
2473
            store_transport = self.bzrdir.transport.clone(store_name)
2845
2474
            store = TransportStore(store_transport, prefixed=True)
2846
2475
            for urlfilename in store_transport.list_dir('.'):
2873
2502
        from bzrlib.repofmt.weaverepo import RepositoryFormat7
2874
2503
        from bzrlib.branch import BzrBranchFormat5
2875
2504
        self.bzrdir = to_convert
2876
 
        self.pb = pb
 
2505
        self.pb = ui.ui_factory.nested_progress_bar()
2877
2506
        self.count = 0
2878
2507
        self.total = 20 # the steps we know about
2879
2508
        self.garbage_inventories = []
2880
2509
        self.dir_mode = self.bzrdir._get_dir_mode()
2881
2510
        self.file_mode = self.bzrdir._get_file_mode()
2882
2511
 
2883
 
        self.pb.note('starting upgrade from format 6 to metadir')
 
2512
        ui.ui_factory.note('starting upgrade from format 6 to metadir')
2884
2513
        self.bzrdir.transport.put_bytes(
2885
2514
                'branch-format',
2886
2515
                "Converting to format 6",
2936
2565
        else:
2937
2566
            has_checkout = True
2938
2567
        if not has_checkout:
2939
 
            self.pb.note('No working tree.')
 
2568
            ui.ui_factory.note('No working tree.')
2940
2569
            # If some checkout files are there, we may as well get rid of them.
2941
2570
            for name, mandatory in checkout_files:
2942
2571
                if name in bzrcontents:
2959
2588
            'branch-format',
2960
2589
            BzrDirMetaFormat1().get_format_string(),
2961
2590
            mode=self.file_mode)
2962
 
        return BzrDir.open(self.bzrdir.root_transport.base)
 
2591
        self.pb.finished()
 
2592
        return BzrDir.open(self.bzrdir.user_url)
2963
2593
 
2964
2594
    def make_lock(self, name):
2965
2595
        """Make a lock for the new control dir name."""
3000
2630
    def convert(self, to_convert, pb):
3001
2631
        """See Converter.convert()."""
3002
2632
        self.bzrdir = to_convert
3003
 
        self.pb = pb
 
2633
        self.pb = ui.ui_factory.nested_progress_bar()
3004
2634
        self.count = 0
3005
2635
        self.total = 1
3006
2636
        self.step('checking repository format')
3011
2641
        else:
3012
2642
            if not isinstance(repo._format, self.target_format.repository_format.__class__):
3013
2643
                from bzrlib.repository import CopyConverter
3014
 
                self.pb.note('starting repository conversion')
 
2644
                ui.ui_factory.note('starting repository conversion')
3015
2645
                converter = CopyConverter(self.target_format.repository_format)
3016
2646
                converter.convert(repo, pb)
3017
 
        try:
3018
 
            branch = self.bzrdir.open_branch()
3019
 
        except errors.NotBranchError:
3020
 
            pass
3021
 
        else:
 
2647
        for branch in self.bzrdir.list_branches():
3022
2648
            # TODO: conversions of Branch and Tree should be done by
3023
2649
            # InterXFormat lookups/some sort of registry.
3024
2650
            # Avoid circular imports
3039
2665
                      new is _mod_branch.BzrBranchFormat8):
3040
2666
                    branch_converter = _mod_branch.Converter7to8()
3041
2667
                else:
3042
 
                    raise errors.BadConversionTarget("No converter", new)
 
2668
                    raise errors.BadConversionTarget("No converter", new,
 
2669
                        branch._format)
3043
2670
                branch_converter.convert(branch)
3044
2671
                branch = self.bzrdir.open_branch()
3045
2672
                old = branch._format.__class__
3065
2692
                isinstance(self.target_format.workingtree_format,
3066
2693
                    workingtree_4.WorkingTreeFormat6)):
3067
2694
                workingtree_4.Converter4or5to6().convert(tree)
 
2695
        self.pb.finished()
3068
2696
        return to_convert
3069
2697
 
3070
2698
 
3077
2705
 
3078
2706
    def __init__(self):
3079
2707
        BzrDirMetaFormat1.__init__(self)
 
2708
        # XXX: It's a bit ugly that the network name is here, because we'd
 
2709
        # like to believe that format objects are stateless or at least
 
2710
        # immutable,  However, we do at least avoid mutating the name after
 
2711
        # it's returned.  See <https://bugs.launchpad.net/bzr/+bug/504102>
3080
2712
        self._network_name = None
3081
2713
 
 
2714
    def __repr__(self):
 
2715
        return "%s(_network_name=%r)" % (self.__class__.__name__,
 
2716
            self._network_name)
 
2717
 
3082
2718
    def get_format_description(self):
 
2719
        if self._network_name:
 
2720
            real_format = network_format_registry.get(self._network_name)
 
2721
            return 'Remote: ' + real_format.get_format_description()
3083
2722
        return 'bzr remote bzrdir'
3084
2723
 
3085
2724
    def get_format_string(self):
3091
2730
        else:
3092
2731
            raise AssertionError("No network name set.")
3093
2732
 
3094
 
    @classmethod
3095
 
    def probe_transport(klass, transport):
3096
 
        """Return a RemoteBzrDirFormat object if it looks possible."""
3097
 
        try:
3098
 
            medium = transport.get_smart_medium()
3099
 
        except (NotImplementedError, AttributeError,
3100
 
                errors.TransportNotPossible, errors.NoSmartMedium,
3101
 
                errors.SmartProtocolError):
3102
 
            # no smart server, so not a branch for this format type.
3103
 
            raise errors.NotBranchError(path=transport.base)
3104
 
        else:
3105
 
            # Decline to open it if the server doesn't support our required
3106
 
            # version (3) so that the VFS-based transport will do it.
3107
 
            if medium.should_probe():
3108
 
                try:
3109
 
                    server_version = medium.protocol_version()
3110
 
                except errors.SmartProtocolError:
3111
 
                    # Apparently there's no usable smart server there, even though
3112
 
                    # the medium supports the smart protocol.
3113
 
                    raise errors.NotBranchError(path=transport.base)
3114
 
                if server_version != '2':
3115
 
                    raise errors.NotBranchError(path=transport.base)
3116
 
            return klass()
3117
 
 
3118
2733
    def initialize_on_transport(self, transport):
3119
2734
        try:
3120
2735
            # hand off the request to the smart server
3218
2833
        args.append(self._serialize_NoneString(repo_format_name))
3219
2834
        args.append(self._serialize_NoneTrueFalse(make_working_trees))
3220
2835
        args.append(self._serialize_NoneTrueFalse(shared_repo))
3221
 
        if self._network_name is None:
3222
 
            self._network_name = \
 
2836
        request_network_name = self._network_name or \
3223
2837
            BzrDirFormat.get_default_format().network_name()
3224
2838
        try:
3225
2839
            response = client.call('BzrDirFormat.initialize_ex_1.16',
3226
 
                self.network_name(), path, *args)
 
2840
                request_network_name, path, *args)
3227
2841
        except errors.UnknownSmartMethod:
3228
2842
            client._medium._remember_remote_is_before((1,16))
3229
2843
            local_dir_format = BzrDirMetaFormat1()
3320
2934
        BzrDirMetaFormat1._set_repository_format) #.im_func)
3321
2935
 
3322
2936
 
3323
 
BzrDirFormat.register_control_server_format(RemoteBzrDirFormat)
3324
 
 
3325
 
 
3326
 
class BzrDirFormatInfo(object):
3327
 
 
3328
 
    def __init__(self, native, deprecated, hidden, experimental):
3329
 
        self.deprecated = deprecated
3330
 
        self.native = native
3331
 
        self.hidden = hidden
3332
 
        self.experimental = experimental
3333
 
 
3334
 
 
3335
 
class BzrDirFormatRegistry(registry.Registry):
3336
 
    """Registry of user-selectable BzrDir subformats.
3337
 
 
3338
 
    Differs from BzrDirFormat._control_formats in that it provides sub-formats,
3339
 
    e.g. BzrDirMeta1 with weave repository.  Also, it's more user-oriented.
3340
 
    """
3341
 
 
3342
 
    def __init__(self):
3343
 
        """Create a BzrDirFormatRegistry."""
3344
 
        self._aliases = set()
3345
 
        self._registration_order = list()
3346
 
        super(BzrDirFormatRegistry, self).__init__()
3347
 
 
3348
 
    def aliases(self):
3349
 
        """Return a set of the format names which are aliases."""
3350
 
        return frozenset(self._aliases)
3351
 
 
3352
 
    def register_metadir(self, key,
3353
 
             repository_format, help, native=True, deprecated=False,
3354
 
             branch_format=None,
3355
 
             tree_format=None,
3356
 
             hidden=False,
3357
 
             experimental=False,
3358
 
             alias=False):
3359
 
        """Register a metadir subformat.
3360
 
 
3361
 
        These all use a BzrDirMetaFormat1 bzrdir, but can be parameterized
3362
 
        by the Repository/Branch/WorkingTreeformats.
3363
 
 
3364
 
        :param repository_format: The fully-qualified repository format class
3365
 
            name as a string.
3366
 
        :param branch_format: Fully-qualified branch format class name as
3367
 
            a string.
3368
 
        :param tree_format: Fully-qualified tree format class name as
3369
 
            a string.
3370
 
        """
3371
 
        # This should be expanded to support setting WorkingTree and Branch
3372
 
        # formats, once BzrDirMetaFormat1 supports that.
3373
 
        def _load(full_name):
3374
 
            mod_name, factory_name = full_name.rsplit('.', 1)
3375
 
            try:
3376
 
                mod = __import__(mod_name, globals(), locals(),
3377
 
                        [factory_name])
3378
 
            except ImportError, e:
3379
 
                raise ImportError('failed to load %s: %s' % (full_name, e))
3380
 
            try:
3381
 
                factory = getattr(mod, factory_name)
3382
 
            except AttributeError:
3383
 
                raise AttributeError('no factory %s in module %r'
3384
 
                    % (full_name, mod))
3385
 
            return factory()
3386
 
 
3387
 
        def helper():
3388
 
            bd = BzrDirMetaFormat1()
3389
 
            if branch_format is not None:
3390
 
                bd.set_branch_format(_load(branch_format))
3391
 
            if tree_format is not None:
3392
 
                bd.workingtree_format = _load(tree_format)
3393
 
            if repository_format is not None:
3394
 
                bd.repository_format = _load(repository_format)
3395
 
            return bd
3396
 
        self.register(key, helper, help, native, deprecated, hidden,
3397
 
            experimental, alias)
3398
 
 
3399
 
    def register(self, key, factory, help, native=True, deprecated=False,
3400
 
                 hidden=False, experimental=False, alias=False):
3401
 
        """Register a BzrDirFormat factory.
3402
 
 
3403
 
        The factory must be a callable that takes one parameter: the key.
3404
 
        It must produce an instance of the BzrDirFormat when called.
3405
 
 
3406
 
        This function mainly exists to prevent the info object from being
3407
 
        supplied directly.
3408
 
        """
3409
 
        registry.Registry.register(self, key, factory, help,
3410
 
            BzrDirFormatInfo(native, deprecated, hidden, experimental))
3411
 
        if alias:
3412
 
            self._aliases.add(key)
3413
 
        self._registration_order.append(key)
3414
 
 
3415
 
    def register_lazy(self, key, module_name, member_name, help, native=True,
3416
 
        deprecated=False, hidden=False, experimental=False, alias=False):
3417
 
        registry.Registry.register_lazy(self, key, module_name, member_name,
3418
 
            help, BzrDirFormatInfo(native, deprecated, hidden, experimental))
3419
 
        if alias:
3420
 
            self._aliases.add(key)
3421
 
        self._registration_order.append(key)
3422
 
 
3423
 
    def set_default(self, key):
3424
 
        """Set the 'default' key to be a clone of the supplied key.
3425
 
 
3426
 
        This method must be called once and only once.
3427
 
        """
3428
 
        registry.Registry.register(self, 'default', self.get(key),
3429
 
            self.get_help(key), info=self.get_info(key))
3430
 
        self._aliases.add('default')
3431
 
 
3432
 
    def set_default_repository(self, key):
3433
 
        """Set the FormatRegistry default and Repository default.
3434
 
 
3435
 
        This is a transitional method while Repository.set_default_format
3436
 
        is deprecated.
3437
 
        """
3438
 
        if 'default' in self:
3439
 
            self.remove('default')
3440
 
        self.set_default(key)
3441
 
        format = self.get('default')()
3442
 
 
3443
 
    def make_bzrdir(self, key):
3444
 
        return self.get(key)()
3445
 
 
3446
 
    def help_topic(self, topic):
3447
 
        output = ""
3448
 
        default_realkey = None
3449
 
        default_help = self.get_help('default')
3450
 
        help_pairs = []
3451
 
        for key in self._registration_order:
3452
 
            if key == 'default':
3453
 
                continue
3454
 
            help = self.get_help(key)
3455
 
            if help == default_help:
3456
 
                default_realkey = key
3457
 
            else:
3458
 
                help_pairs.append((key, help))
3459
 
 
3460
 
        def wrapped(key, help, info):
3461
 
            if info.native:
3462
 
                help = '(native) ' + help
3463
 
            return ':%s:\n%s\n\n' % (key,
3464
 
                textwrap.fill(help, initial_indent='    ',
3465
 
                    subsequent_indent='    ',
3466
 
                    break_long_words=False))
3467
 
        if default_realkey is not None:
3468
 
            output += wrapped(default_realkey, '(default) %s' % default_help,
3469
 
                              self.get_info('default'))
3470
 
        deprecated_pairs = []
3471
 
        experimental_pairs = []
3472
 
        for key, help in help_pairs:
3473
 
            info = self.get_info(key)
3474
 
            if info.hidden:
3475
 
                continue
3476
 
            elif info.deprecated:
3477
 
                deprecated_pairs.append((key, help))
3478
 
            elif info.experimental:
3479
 
                experimental_pairs.append((key, help))
3480
 
            else:
3481
 
                output += wrapped(key, help, info)
3482
 
        output += "\nSee ``bzr help formats`` for more about storage formats."
3483
 
        other_output = ""
3484
 
        if len(experimental_pairs) > 0:
3485
 
            other_output += "Experimental formats are shown below.\n\n"
3486
 
            for key, help in experimental_pairs:
3487
 
                info = self.get_info(key)
3488
 
                other_output += wrapped(key, help, info)
3489
 
        else:
3490
 
            other_output += \
3491
 
                "No experimental formats are available.\n\n"
3492
 
        if len(deprecated_pairs) > 0:
3493
 
            other_output += "\nDeprecated formats are shown below.\n\n"
3494
 
            for key, help in deprecated_pairs:
3495
 
                info = self.get_info(key)
3496
 
                other_output += wrapped(key, help, info)
3497
 
        else:
3498
 
            other_output += \
3499
 
                "\nNo deprecated formats are available.\n\n"
3500
 
        other_output += \
3501
 
            "\nSee ``bzr help formats`` for more about storage formats."
3502
 
 
3503
 
        if topic == 'other-formats':
3504
 
            return other_output
3505
 
        else:
3506
 
            return output
 
2937
controldir.ControlDirFormat.register_server_prober(RemoteBzrProber)
3507
2938
 
3508
2939
 
3509
2940
class RepositoryAcquisitionPolicy(object):
3538
2969
            try:
3539
2970
                stack_on = urlutils.rebase_url(self._stack_on,
3540
2971
                    self._stack_on_pwd,
3541
 
                    branch.bzrdir.root_transport.base)
 
2972
                    branch.user_url)
3542
2973
            except errors.InvalidRebaseURLs:
3543
2974
                stack_on = self._get_full_stack_on()
3544
2975
        try:
3548
2979
            if self._require_stacking:
3549
2980
                raise
3550
2981
 
 
2982
    def requires_stacking(self):
 
2983
        """Return True if this policy requires stacking."""
 
2984
        return self._stack_on is not None and self._require_stacking
 
2985
 
3551
2986
    def _get_full_stack_on(self):
3552
2987
        """Get a fully-qualified URL for the stack_on location."""
3553
2988
        if self._stack_on is None:
3659
3094
        return self._repository, False
3660
3095
 
3661
3096
 
3662
 
# Please register new formats after old formats so that formats
3663
 
# appear in chronological order and format descriptions can build
3664
 
# on previous ones.
3665
 
format_registry = BzrDirFormatRegistry()
 
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
 
3666
3144
# The pre-0.8 formats have their repository format network name registered in
3667
3145
# repository.py. MetaDir formats have their repository format network name
3668
3146
# inferred from their disk format string.
3669
 
format_registry.register('weave', BzrDirFormat6,
 
3147
controldir.format_registry.register('weave', BzrDirFormat6,
3670
3148
    'Pre-0.8 format.  Slower than knit and does not'
3671
3149
    ' support checkouts or shared repositories.',
 
3150
    hidden=True,
3672
3151
    deprecated=True)
3673
 
format_registry.register_metadir('metaweave',
 
3152
register_metadir(controldir.format_registry, 'metaweave',
3674
3153
    'bzrlib.repofmt.weaverepo.RepositoryFormat7',
3675
3154
    'Transitional format in 0.8.  Slower than knit.',
3676
3155
    branch_format='bzrlib.branch.BzrBranchFormat5',
3677
3156
    tree_format='bzrlib.workingtree.WorkingTreeFormat3',
 
3157
    hidden=True,
3678
3158
    deprecated=True)
3679
 
format_registry.register_metadir('knit',
 
3159
register_metadir(controldir.format_registry, 'knit',
3680
3160
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
3681
3161
    'Format using knits.  Recommended for interoperation with bzr <= 0.14.',
3682
3162
    branch_format='bzrlib.branch.BzrBranchFormat5',
3683
3163
    tree_format='bzrlib.workingtree.WorkingTreeFormat3',
 
3164
    hidden=True,
3684
3165
    deprecated=True)
3685
 
format_registry.register_metadir('dirstate',
 
3166
register_metadir(controldir.format_registry, 'dirstate',
3686
3167
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
3687
3168
    help='New in 0.15: Fast local operations. Compatible with bzr 0.8 and '
3688
3169
        'above when accessed over the network.',
3690
3171
    # this uses bzrlib.workingtree.WorkingTreeFormat4 because importing
3691
3172
    # directly from workingtree_4 triggers a circular import.
3692
3173
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3174
    hidden=True,
3693
3175
    deprecated=True)
3694
 
format_registry.register_metadir('dirstate-tags',
 
3176
register_metadir(controldir.format_registry, 'dirstate-tags',
3695
3177
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
3696
3178
    help='New in 0.15: Fast local operations and improved scaling for '
3697
3179
        'network operations. Additionally adds support for tags.'
3698
3180
        ' Incompatible with bzr < 0.15.',
3699
3181
    branch_format='bzrlib.branch.BzrBranchFormat6',
3700
3182
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3183
    hidden=True,
3701
3184
    deprecated=True)
3702
 
format_registry.register_metadir('rich-root',
 
3185
register_metadir(controldir.format_registry, 'rich-root',
3703
3186
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit4',
3704
3187
    help='New in 1.0.  Better handling of tree roots.  Incompatible with'
3705
3188
        ' bzr < 1.0.',
3706
3189
    branch_format='bzrlib.branch.BzrBranchFormat6',
3707
3190
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3191
    hidden=True,
3708
3192
    deprecated=True)
3709
 
format_registry.register_metadir('dirstate-with-subtree',
 
3193
register_metadir(controldir.format_registry, 'dirstate-with-subtree',
3710
3194
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
3711
3195
    help='New in 0.15: Fast local operations and improved scaling for '
3712
3196
        'network operations. Additionally adds support for versioning nested '
3716
3200
    experimental=True,
3717
3201
    hidden=True,
3718
3202
    )
3719
 
format_registry.register_metadir('pack-0.92',
 
3203
register_metadir(controldir.format_registry, 'pack-0.92',
3720
3204
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack1',
3721
3205
    help='New in 0.92: Pack-based format with data compatible with '
3722
3206
        'dirstate-tags format repositories. Interoperates with '
3723
3207
        'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
3724
 
        'Previously called knitpack-experimental.  '
3725
 
        'For more information, see '
3726
 
        'http://doc.bazaar-vcs.org/latest/developers/packrepo.html.',
 
3208
        ,
3727
3209
    branch_format='bzrlib.branch.BzrBranchFormat6',
3728
3210
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3729
3211
    )
3730
 
format_registry.register_metadir('pack-0.92-subtree',
 
3212
register_metadir(controldir.format_registry, 'pack-0.92-subtree',
3731
3213
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack3',
3732
3214
    help='New in 0.92: Pack-based format with data compatible with '
3733
3215
        'dirstate-with-subtree format repositories. Interoperates with '
3734
3216
        'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
3735
 
        'Previously called knitpack-experimental.  '
3736
 
        'For more information, see '
3737
 
        'http://doc.bazaar-vcs.org/latest/developers/packrepo.html.',
 
3217
        ,
3738
3218
    branch_format='bzrlib.branch.BzrBranchFormat6',
3739
3219
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3740
3220
    hidden=True,
3741
3221
    experimental=True,
3742
3222
    )
3743
 
format_registry.register_metadir('rich-root-pack',
 
3223
register_metadir(controldir.format_registry, 'rich-root-pack',
3744
3224
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack4',
3745
3225
    help='New in 1.0: A variant of pack-0.92 that supports rich-root data '
3746
3226
         '(needed for bzr-svn and bzr-git).',
3747
3227
    branch_format='bzrlib.branch.BzrBranchFormat6',
3748
3228
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3229
    hidden=True,
3749
3230
    )
3750
 
format_registry.register_metadir('1.6',
 
3231
register_metadir(controldir.format_registry, '1.6',
3751
3232
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5',
3752
3233
    help='A format that allows a branch to indicate that there is another '
3753
3234
         '(stacked) repository that should be used to access data that is '
3754
3235
         'not present locally.',
3755
3236
    branch_format='bzrlib.branch.BzrBranchFormat7',
3756
3237
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3238
    hidden=True,
3757
3239
    )
3758
 
format_registry.register_metadir('1.6.1-rich-root',
 
3240
register_metadir(controldir.format_registry, '1.6.1-rich-root',
3759
3241
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5RichRoot',
3760
3242
    help='A variant of 1.6 that supports rich-root data '
3761
3243
         '(needed for bzr-svn and bzr-git).',
3762
3244
    branch_format='bzrlib.branch.BzrBranchFormat7',
3763
3245
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3246
    hidden=True,
3764
3247
    )
3765
 
format_registry.register_metadir('1.9',
 
3248
register_metadir(controldir.format_registry, '1.9',
3766
3249
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
3767
3250
    help='A repository format using B+tree indexes. These indexes '
3768
3251
         'are smaller in size, have smarter caching and provide faster '
3769
3252
         'performance for most operations.',
3770
3253
    branch_format='bzrlib.branch.BzrBranchFormat7',
3771
3254
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3255
    hidden=True,
3772
3256
    )
3773
 
format_registry.register_metadir('1.9-rich-root',
 
3257
register_metadir(controldir.format_registry, '1.9-rich-root',
3774
3258
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
3775
3259
    help='A variant of 1.9 that supports rich-root data '
3776
3260
         '(needed for bzr-svn and bzr-git).',
3777
3261
    branch_format='bzrlib.branch.BzrBranchFormat7',
3778
3262
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3263
    hidden=True,
3779
3264
    )
3780
 
format_registry.register_metadir('1.14',
 
3265
register_metadir(controldir.format_registry, '1.14',
3781
3266
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
3782
3267
    help='A working-tree format that supports content filtering.',
3783
3268
    branch_format='bzrlib.branch.BzrBranchFormat7',
3784
3269
    tree_format='bzrlib.workingtree.WorkingTreeFormat5',
3785
3270
    )
3786
 
format_registry.register_metadir('1.14-rich-root',
 
3271
register_metadir(controldir.format_registry, '1.14-rich-root',
3787
3272
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
3788
3273
    help='A variant of 1.14 that supports rich-root data '
3789
3274
         '(needed for bzr-svn and bzr-git).',
3791
3276
    tree_format='bzrlib.workingtree.WorkingTreeFormat5',
3792
3277
    )
3793
3278
# The following un-numbered 'development' formats should always just be aliases.
3794
 
format_registry.register_metadir('development-rich-root',
 
3279
register_metadir(controldir.format_registry, 'development-rich-root',
3795
3280
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormatCHK1',
3796
3281
    help='Current development format. Supports rich roots. Can convert data '
3797
3282
        'to and from rich-root-pack (and anything compatible with '
3798
3283
        'rich-root-pack) format repositories. Repositories and branches in '
3799
3284
        'this format can only be read by bzr.dev. Please read '
3800
 
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
 
3285
        'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
3801
3286
        'before use.',
3802
3287
    branch_format='bzrlib.branch.BzrBranchFormat7',
3803
3288
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
3804
3289
    experimental=True,
3805
3290
    alias=True,
 
3291
    hidden=True,
3806
3292
    )
3807
 
format_registry.register_metadir('development-subtree',
 
3293
register_metadir(controldir.format_registry, 'development-subtree',
3808
3294
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment2Subtree',
3809
3295
    help='Current development format, subtree variant. Can convert data to and '
3810
3296
        'from pack-0.92-subtree (and anything compatible with '
3811
3297
        'pack-0.92-subtree) format repositories. Repositories and branches in '
3812
3298
        'this format can only be read by bzr.dev. Please read '
3813
 
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
 
3299
        'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
3814
3300
        'before use.',
3815
3301
    branch_format='bzrlib.branch.BzrBranchFormat7',
3816
3302
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
3817
3303
    experimental=True,
 
3304
    hidden=True,
3818
3305
    alias=False, # Restore to being an alias when an actual development subtree format is added
3819
3306
                 # This current non-alias status is simply because we did not introduce a
3820
3307
                 # chk based subtree format.
3821
3308
    )
3822
3309
 
3823
3310
# And the development formats above will have aliased one of the following:
3824
 
format_registry.register_metadir('development6-rich-root',
 
3311
register_metadir(controldir.format_registry, 'development6-rich-root',
3825
3312
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormatCHK1',
3826
3313
    help='pack-1.9 with 255-way hashed CHK inv, group compress, rich roots '
3827
3314
        'Please read '
3828
 
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
 
3315
        'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
3829
3316
        'before use.',
3830
3317
    branch_format='bzrlib.branch.BzrBranchFormat7',
3831
3318
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
3833
3320
    experimental=True,
3834
3321
    )
3835
3322
 
3836
 
format_registry.register_metadir('development7-rich-root',
 
3323
register_metadir(controldir.format_registry, 'development7-rich-root',
3837
3324
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormatCHK2',
3838
3325
    help='pack-1.9 with 255-way hashed CHK inv, bencode revision, group compress, '
3839
3326
        'rich roots. Please read '
3840
 
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
 
3327
        'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
3841
3328
        'before use.',
3842
3329
    branch_format='bzrlib.branch.BzrBranchFormat7',
3843
3330
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
3845
3332
    experimental=True,
3846
3333
    )
3847
3334
 
3848
 
format_registry.register_metadir('2a',
 
3335
register_metadir(controldir.format_registry, '2a',
3849
3336
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2a',
3850
3337
    help='First format for bzr 2.0 series.\n'
3851
3338
        'Uses group-compress storage.\n'
3859
3346
 
3860
3347
# The following format should be an alias for the rich root equivalent 
3861
3348
# of the default format
3862
 
format_registry.register_metadir('default-rich-root',
3863
 
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack4',
3864
 
    help='Default format, rich root variant. (needed for bzr-svn and bzr-git).',
3865
 
    branch_format='bzrlib.branch.BzrBranchFormat6',
3866
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3349
register_metadir(controldir.format_registry, 'default-rich-root',
 
3350
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2a',
 
3351
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
3352
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
3867
3353
    alias=True,
3868
 
    )
 
3354
    hidden=True,
 
3355
    help='Same as 2a.')
 
3356
 
3869
3357
# The current format that is made on 'bzr init'.
3870
 
format_registry.set_default('pack-0.92')
 
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