~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: 2009-08-03 07:15:11 UTC
  • mfrom: (4580.1.2 408199-check-2a)
  • Revision ID: pqm@pqm.ubuntu.com-20090803071511-dwb041qzak0vjzdk
(mbp) check blackbox tests now handle the root being included in the
        file-id count

Show diffs side-by-side

added added

removed removed

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