~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

  • Committer: Jelmer Vernooij
  • Date: 2012-02-20 12:19:29 UTC
  • mfrom: (6437.23.11 2.5)
  • mto: (6581.1.1 trunk)
  • mto: This revision was merged to the branch mainline in revision 6582.
  • Revision ID: jelmer@samba.org-20120220121929-7ni2psvjoatm1yp4
Merge bzr/2.5.

Show diffs side-by-side

added added

removed removed

Lines of Context:
25
25
objects returned.
26
26
"""
27
27
 
 
28
from __future__ import absolute_import
 
29
 
28
30
import sys
29
31
 
30
32
from bzrlib.lazy_import import lazy_import
46
48
    transport as _mod_transport,
47
49
    ui,
48
50
    urlutils,
 
51
    vf_search,
49
52
    win32utils,
50
53
    workingtree_3,
51
54
    workingtree_4,
55
58
    do_catching_redirections,
56
59
    local,
57
60
    )
 
61
from bzrlib.i18n import gettext
58
62
""")
59
63
 
60
64
from bzrlib.trace import (
65
69
from bzrlib import (
66
70
    config,
67
71
    controldir,
68
 
    hooks,
69
72
    registry,
70
73
    )
71
74
from bzrlib.symbol_versioning import (
200
203
                if (result_repo.user_url == result.user_url
201
204
                    and not require_stacking and
202
205
                    revision_id is not None):
203
 
                    fetch_spec = graph.PendingAncestryResult(
 
206
                    fetch_spec = vf_search.PendingAncestryResult(
204
207
                        [revision_id], local_repo)
205
208
                    result_repo.fetch(local_repo, fetch_spec=fetch_spec)
206
209
                else:
221
224
            # the tree and fail.
222
225
            result.root_transport.local_abspath('.')
223
226
            if result_repo is None or result_repo.make_working_trees():
224
 
                self.open_workingtree().clone(result)
 
227
                self.open_workingtree().clone(result, revision_id=revision_id)
225
228
        except (errors.NoWorkingTree, errors.NotLocalUrl):
226
229
            pass
227
230
        return result
232
235
        t = _mod_transport.get_transport(url)
233
236
        t.ensure_base()
234
237
 
235
 
    @staticmethod
236
 
    def find_bzrdirs(transport, evaluate=None, list_current=None):
237
 
        """Find bzrdirs recursively from current location.
238
 
 
239
 
        This is intended primarily as a building block for more sophisticated
240
 
        functionality, like finding trees under a directory, or finding
241
 
        branches that use a given repository.
242
 
 
243
 
        :param evaluate: An optional callable that yields recurse, value,
244
 
            where recurse controls whether this bzrdir is recursed into
245
 
            and value is the value to yield.  By default, all bzrdirs
246
 
            are recursed into, and the return value is the bzrdir.
247
 
        :param list_current: if supplied, use this function to list the current
248
 
            directory, instead of Transport.list_dir
249
 
        :return: a generator of found bzrdirs, or whatever evaluate returns.
250
 
        """
251
 
        if list_current is None:
252
 
            def list_current(transport):
253
 
                return transport.list_dir('')
254
 
        if evaluate is None:
255
 
            def evaluate(bzrdir):
256
 
                return True, bzrdir
257
 
 
258
 
        pending = [transport]
259
 
        while len(pending) > 0:
260
 
            current_transport = pending.pop()
261
 
            recurse = True
262
 
            try:
263
 
                bzrdir = BzrDir.open_from_transport(current_transport)
264
 
            except (errors.NotBranchError, errors.PermissionDenied):
265
 
                pass
266
 
            else:
267
 
                recurse, value = evaluate(bzrdir)
268
 
                yield value
269
 
            try:
270
 
                subdirs = list_current(current_transport)
271
 
            except (errors.NoSuchFile, errors.PermissionDenied):
272
 
                continue
273
 
            if recurse:
274
 
                for subdir in sorted(subdirs, reverse=True):
275
 
                    pending.append(current_transport.clone(subdir))
276
 
 
277
 
    @staticmethod
278
 
    def find_branches(transport):
279
 
        """Find all branches under a transport.
280
 
 
281
 
        This will find all branches below the transport, including branches
282
 
        inside other branches.  Where possible, it will use
283
 
        Repository.find_branches.
284
 
 
285
 
        To list all the branches that use a particular Repository, see
286
 
        Repository.find_branches
287
 
        """
288
 
        def evaluate(bzrdir):
289
 
            try:
290
 
                repository = bzrdir.open_repository()
291
 
            except errors.NoRepositoryPresent:
292
 
                pass
293
 
            else:
294
 
                return False, ([], repository)
295
 
            return True, (bzrdir.list_branches(), None)
296
 
        ret = []
297
 
        for branches, repo in BzrDir.find_bzrdirs(transport,
298
 
                                                  evaluate=evaluate):
299
 
            if repo is not None:
300
 
                ret.extend(repo.find_branches())
301
 
            if branches is not None:
302
 
                ret.extend(branches)
303
 
        return ret
304
 
 
305
 
    @staticmethod
306
 
    def create_branch_and_repo(base, force_new_repo=False, format=None):
307
 
        """Create a new BzrDir, Branch and Repository at the url 'base'.
308
 
 
309
 
        This will use the current default BzrDirFormat unless one is
310
 
        specified, and use whatever
311
 
        repository format that that uses via bzrdir.create_branch and
312
 
        create_repository. If a shared repository is available that is used
313
 
        preferentially.
314
 
 
315
 
        The created Branch object is returned.
316
 
 
317
 
        :param base: The URL to create the branch at.
318
 
        :param force_new_repo: If True a new repository is always created.
319
 
        :param format: If supplied, the format of branch to create.  If not
320
 
            supplied, the default is used.
321
 
        """
322
 
        bzrdir = BzrDir.create(base, format)
323
 
        bzrdir._find_or_create_repository(force_new_repo)
324
 
        return bzrdir.create_branch()
325
 
 
326
238
    def determine_repository_policy(self, force_new_repo=False, stack_on=None,
327
239
                                    stack_on_pwd=None, require_stacking=False):
328
240
        """Return an object representing a policy to use.
443
355
            location of this control directory.
444
356
        :param create_tree_if_local: If true, a working-tree will be created
445
357
            when working locally.
 
358
        :return: The created control directory
446
359
        """
447
360
        operation = cleanup.OperationWithCleanups(self._sprout)
448
361
        return operation.run(url, revision_id=revision_id,
461
374
        if revision_id is not None:
462
375
            fetch_spec_factory.add_revision_ids([revision_id])
463
376
            fetch_spec_factory.source_branch_stop_revision_id = revision_id
 
377
        if possible_transports is None:
 
378
            possible_transports = []
 
379
        else:
 
380
            possible_transports = list(possible_transports) + [
 
381
                self.root_transport]
464
382
        target_transport = _mod_transport.get_transport(url,
465
383
            possible_transports)
466
384
        target_transport.ensure_base()
467
385
        cloning_format = self.cloning_metadir(stacked)
468
386
        # Create/update the result branch
469
 
        result = cloning_format.initialize_on_transport(target_transport)
 
387
        try:
 
388
            result = controldir.ControlDir.open_from_transport(target_transport)
 
389
        except errors.NotBranchError:
 
390
            result = cloning_format.initialize_on_transport(target_transport)
470
391
        source_branch, source_repository = self._find_source_repo(
471
392
            add_cleanup, source_branch)
472
393
        fetch_spec_factory.source_branch = source_branch
478
399
            stacked_branch_url = None
479
400
        repository_policy = result.determine_repository_policy(
480
401
            force_new_repo, stacked_branch_url, require_stacking=stacked)
481
 
        result_repo, is_new_repo = repository_policy.acquire_repository()
 
402
        result_repo, is_new_repo = repository_policy.acquire_repository(
 
403
            possible_transports=possible_transports)
482
404
        add_cleanup(result_repo.lock_write().unlock)
483
405
        fetch_spec_factory.source_repo = source_repository
484
406
        fetch_spec_factory.target_repo = result_repo
505
427
        mutter("created new branch %r" % (result_branch,))
506
428
 
507
429
        # Create/update the result working tree
508
 
        if (create_tree_if_local and
 
430
        if (create_tree_if_local and not result.has_workingtree() and
509
431
            isinstance(target_transport, local.LocalTransport) and
510
432
            (result_repo is None or result_repo.make_working_trees())):
511
433
            wt = result.create_workingtree(accelerator_tree=accelerator_tree,
543
465
                    stacked=stacked)
544
466
        return result
545
467
 
546
 
 
547
 
 
548
 
    @staticmethod
549
 
    def create_branch_convenience(base, force_new_repo=False,
550
 
                                  force_new_tree=None, format=None,
551
 
                                  possible_transports=None):
552
 
        """Create a new BzrDir, Branch and Repository at the url 'base'.
553
 
 
554
 
        This is a convenience function - it will use an existing repository
555
 
        if possible, can be told explicitly whether to create a working tree or
556
 
        not.
557
 
 
558
 
        This will use the current default BzrDirFormat unless one is
559
 
        specified, and use whatever
560
 
        repository format that that uses via bzrdir.create_branch and
561
 
        create_repository. If a shared repository is available that is used
562
 
        preferentially. Whatever repository is used, its tree creation policy
563
 
        is followed.
564
 
 
565
 
        The created Branch object is returned.
566
 
        If a working tree cannot be made due to base not being a file:// url,
567
 
        no error is raised unless force_new_tree is True, in which case no
568
 
        data is created on disk and NotLocalUrl is raised.
569
 
 
570
 
        :param base: The URL to create the branch at.
571
 
        :param force_new_repo: If True a new repository is always created.
572
 
        :param force_new_tree: If True or False force creation of a tree or
573
 
                               prevent such creation respectively.
574
 
        :param format: Override for the bzrdir format to create.
575
 
        :param possible_transports: An optional reusable transports list.
576
 
        """
577
 
        if force_new_tree:
578
 
            # check for non local urls
579
 
            t = _mod_transport.get_transport(base, possible_transports)
580
 
            if not isinstance(t, local.LocalTransport):
581
 
                raise errors.NotLocalUrl(base)
582
 
        bzrdir = BzrDir.create(base, format, possible_transports)
583
 
        repo = bzrdir._find_or_create_repository(force_new_repo)
584
 
        result = bzrdir.create_branch()
585
 
        if force_new_tree or (repo.make_working_trees() and
586
 
                              force_new_tree is None):
587
 
            try:
588
 
                bzrdir.create_workingtree()
589
 
            except errors.NotLocalUrl:
590
 
                pass
591
 
        return result
592
 
 
593
 
    @staticmethod
594
 
    def create_standalone_workingtree(base, format=None):
595
 
        """Create a new BzrDir, WorkingTree, Branch and Repository at 'base'.
596
 
 
597
 
        'base' must be a local path or a file:// url.
598
 
 
599
 
        This will use the current default BzrDirFormat unless one is
600
 
        specified, and use whatever
601
 
        repository format that that uses for bzrdirformat.create_workingtree,
602
 
        create_branch and create_repository.
603
 
 
604
 
        :param format: Override for the bzrdir format to create.
605
 
        :return: The WorkingTree object.
606
 
        """
607
 
        t = _mod_transport.get_transport(base)
608
 
        if not isinstance(t, local.LocalTransport):
609
 
            raise errors.NotLocalUrl(base)
610
 
        bzrdir = BzrDir.create_branch_and_repo(base,
611
 
                                               force_new_repo=True,
612
 
                                               format=format).bzrdir
613
 
        return bzrdir.create_workingtree()
614
 
 
615
468
    @deprecated_method(deprecated_in((2, 3, 0)))
616
469
    def generate_backup_name(self, base):
617
470
        return self._available_backup_name(base)
634
487
            old_path = self.root_transport.abspath('.bzr')
635
488
            backup_dir = self._available_backup_name('backup.bzr')
636
489
            new_path = self.root_transport.abspath(backup_dir)
637
 
            ui.ui_factory.note('making backup of %s\n  to %s' % (
 
490
            ui.ui_factory.note(gettext('making backup of {0}\n  to {1}').format(
638
491
                urlutils.unescape_for_display(old_path, 'utf-8'),
639
492
                urlutils.unescape_for_display(new_path, 'utf-8')))
640
493
            self.root_transport.copy_tree('.bzr', backup_dir)
657
510
            try:
658
511
                to_path = '.bzr.retired.%d' % i
659
512
                self.root_transport.rename('.bzr', to_path)
660
 
                note("renamed %s to %s"
661
 
                    % (self.root_transport.abspath('.bzr'), to_path))
 
513
                note(gettext("renamed {0} to {1}").format(
 
514
                    self.root_transport.abspath('.bzr'), to_path))
662
515
                return
663
516
            except (errors.TransportError, IOError, errors.PathError):
664
517
                i += 1
691
544
                return None
692
545
            # find the next containing bzrdir
693
546
            try:
694
 
                found_bzrdir = BzrDir.open_containing_from_transport(
 
547
                found_bzrdir = self.open_containing_from_transport(
695
548
                    next_transport)[0]
696
549
            except errors.NotBranchError:
697
550
                return None
814
667
        # add new tests for it to the appropriate place.
815
668
        return filename == '.bzr' or filename.startswith('.bzr/')
816
669
 
817
 
    @staticmethod
818
 
    def open_unsupported(base):
819
 
        """Open a branch which is not supported."""
820
 
        return BzrDir.open(base, _unsupported=True)
821
 
 
822
 
    @staticmethod
823
 
    def open(base, _unsupported=False, possible_transports=None):
824
 
        """Open an existing bzrdir, rooted at 'base' (url).
825
 
 
826
 
        :param _unsupported: a private parameter to the BzrDir class.
827
 
        """
828
 
        t = _mod_transport.get_transport(base, possible_transports)
829
 
        return BzrDir.open_from_transport(t, _unsupported=_unsupported)
830
 
 
831
 
    @staticmethod
832
 
    def open_from_transport(transport, _unsupported=False,
833
 
                            _server_formats=True):
834
 
        """Open a bzrdir within a particular directory.
835
 
 
836
 
        :param transport: Transport containing the bzrdir.
837
 
        :param _unsupported: private.
838
 
        """
839
 
        for hook in BzrDir.hooks['pre_open']:
840
 
            hook(transport)
841
 
        # Keep initial base since 'transport' may be modified while following
842
 
        # the redirections.
843
 
        base = transport.base
844
 
        def find_format(transport):
845
 
            return transport, controldir.ControlDirFormat.find_format(
846
 
                transport, _server_formats=_server_formats)
847
 
 
848
 
        def redirected(transport, e, redirection_notice):
849
 
            redirected_transport = transport._redirected_to(e.source, e.target)
850
 
            if redirected_transport is None:
851
 
                raise errors.NotBranchError(base)
852
 
            note('%s is%s redirected to %s',
853
 
                 transport.base, e.permanently, redirected_transport.base)
854
 
            return redirected_transport
855
 
 
856
 
        try:
857
 
            transport, format = do_catching_redirections(find_format,
858
 
                                                         transport,
859
 
                                                         redirected)
860
 
        except errors.TooManyRedirections:
861
 
            raise errors.NotBranchError(base)
862
 
 
863
 
        format.check_support_status(_unsupported)
864
 
        return format.open(transport, _found=True)
865
 
 
866
 
    @staticmethod
867
 
    def open_containing(url, possible_transports=None):
868
 
        """Open an existing branch which contains url.
869
 
 
870
 
        :param url: url to search from.
871
 
 
872
 
        See open_containing_from_transport for more detail.
873
 
        """
874
 
        transport = _mod_transport.get_transport(url, possible_transports)
875
 
        return BzrDir.open_containing_from_transport(transport)
876
 
 
877
 
    @staticmethod
878
 
    def open_containing_from_transport(a_transport):
879
 
        """Open an existing branch which contains a_transport.base.
880
 
 
881
 
        This probes for a branch at a_transport, and searches upwards from there.
882
 
 
883
 
        Basically we keep looking up until we find the control directory or
884
 
        run into the root.  If there isn't one, raises NotBranchError.
885
 
        If there is one and it is either an unrecognised format or an unsupported
886
 
        format, UnknownFormatError or UnsupportedFormatError are raised.
887
 
        If there is one, it is returned, along with the unused portion of url.
888
 
 
889
 
        :return: The BzrDir that contains the path, and a Unicode path
890
 
                for the rest of the URL.
891
 
        """
892
 
        # this gets the normalised url back. I.e. '.' -> the full path.
893
 
        url = a_transport.base
894
 
        while True:
895
 
            try:
896
 
                result = BzrDir.open_from_transport(a_transport)
897
 
                return result, urlutils.unescape(a_transport.relpath(url))
898
 
            except errors.NotBranchError, e:
899
 
                pass
900
 
            try:
901
 
                new_t = a_transport.clone('..')
902
 
            except errors.InvalidURLJoin:
903
 
                # reached the root, whatever that may be
904
 
                raise errors.NotBranchError(path=url)
905
 
            if new_t.base == a_transport.base:
906
 
                # reached the root, whatever that may be
907
 
                raise errors.NotBranchError(path=url)
908
 
            a_transport = new_t
909
 
 
910
 
    @classmethod
911
 
    def open_tree_or_branch(klass, location):
912
 
        """Return the branch and working tree at a location.
913
 
 
914
 
        If there is no tree at the location, tree will be None.
915
 
        If there is no branch at the location, an exception will be
916
 
        raised
917
 
        :return: (tree, branch)
918
 
        """
919
 
        bzrdir = klass.open(location)
920
 
        return bzrdir._get_tree_branch()
921
 
 
922
 
    @classmethod
923
 
    def open_containing_tree_or_branch(klass, location):
924
 
        """Return the branch and working tree contained by a location.
925
 
 
926
 
        Returns (tree, branch, relpath).
927
 
        If there is no tree at containing the location, tree will be None.
928
 
        If there is no branch containing the location, an exception will be
929
 
        raised
930
 
        relpath is the portion of the path that is contained by the branch.
931
 
        """
932
 
        bzrdir, relpath = klass.open_containing(location)
933
 
        tree, branch = bzrdir._get_tree_branch()
934
 
        return tree, branch, relpath
935
 
 
936
 
    @classmethod
937
 
    def open_containing_tree_branch_or_repository(klass, location):
938
 
        """Return the working tree, branch and repo contained by a location.
939
 
 
940
 
        Returns (tree, branch, repository, relpath).
941
 
        If there is no tree containing the location, tree will be None.
942
 
        If there is no branch containing the location, branch will be None.
943
 
        If there is no repository containing the location, repository will be
944
 
        None.
945
 
        relpath is the portion of the path that is contained by the innermost
946
 
        BzrDir.
947
 
 
948
 
        If no tree, branch or repository is found, a NotBranchError is raised.
949
 
        """
950
 
        bzrdir, relpath = klass.open_containing(location)
951
 
        try:
952
 
            tree, branch = bzrdir._get_tree_branch()
953
 
        except errors.NotBranchError:
954
 
            try:
955
 
                repo = bzrdir.find_repository()
956
 
                return None, None, repo, relpath
957
 
            except (errors.NoRepositoryPresent):
958
 
                raise errors.NotBranchError(location)
959
 
        return tree, branch, branch.repository, relpath
960
 
 
961
670
    def _cloning_metadir(self):
962
671
        """Produce a metadir suitable for cloning with.
963
672
 
1003
712
 
1004
713
        :require_stacking: If True, non-stackable formats will be upgraded
1005
714
            to similar stackable formats.
1006
 
        :returns: a BzrDirFormat with all component formats either set
 
715
        :returns: a ControlDirFormat with all component formats either set
1007
716
            appropriately or set to None if that component should not be
1008
717
            created.
1009
718
        """
1021
730
            format.require_stacking()
1022
731
        return format
1023
732
 
1024
 
    @classmethod
1025
 
    def create(cls, base, format=None, possible_transports=None):
1026
 
        """Create a new BzrDir at the url 'base'.
1027
 
 
1028
 
        :param format: If supplied, the format of branch to create.  If not
1029
 
            supplied, the default is used.
1030
 
        :param possible_transports: If supplied, a list of transports that
1031
 
            can be reused to share a remote connection.
1032
 
        """
1033
 
        if cls is not BzrDir:
1034
 
            raise AssertionError("BzrDir.create always creates the"
1035
 
                "default format, not one of %r" % cls)
1036
 
        t = _mod_transport.get_transport(base, possible_transports)
1037
 
        t.ensure_base()
1038
 
        if format is None:
1039
 
            format = controldir.ControlDirFormat.get_default_format()
1040
 
        return format.initialize_on_transport(t)
1041
 
 
1042
733
    def get_branch_transport(self, branch_format, name=None):
1043
734
        """Get the transport for use by branch format in this BzrDir.
1044
735
 
1078
769
        """
1079
770
        raise NotImplementedError(self.get_workingtree_transport)
1080
771
 
1081
 
 
1082
 
class BzrDirHooks(hooks.Hooks):
1083
 
    """Hooks for BzrDir operations."""
1084
 
 
1085
 
    def __init__(self):
1086
 
        """Create the default hooks."""
1087
 
        hooks.Hooks.__init__(self, "bzrlib.bzrdir", "BzrDir.hooks")
1088
 
        self.add_hook('pre_open',
1089
 
            "Invoked before attempting to open a BzrDir with the transport "
1090
 
            "that the open will use.", (1, 14))
1091
 
        self.add_hook('post_repo_init',
1092
 
            "Invoked after a repository has been initialized. "
1093
 
            "post_repo_init is called with a "
1094
 
            "bzrlib.bzrdir.RepoInitHookParams.",
1095
 
            (2, 2))
1096
 
 
1097
 
# install the default hooks
1098
 
BzrDir.hooks = BzrDirHooks()
1099
 
 
1100
 
 
1101
 
class RepoInitHookParams(object):
1102
 
    """Object holding parameters passed to `*_repo_init` hooks.
1103
 
 
1104
 
    There are 4 fields that hooks may wish to access:
1105
 
 
1106
 
    :ivar repository: Repository created
1107
 
    :ivar format: Repository format
1108
 
    :ivar bzrdir: The bzrdir for the repository
1109
 
    :ivar shared: The repository is shared
1110
 
    """
1111
 
 
1112
 
    def __init__(self, repository, format, a_bzrdir, shared):
1113
 
        """Create a group of RepoInitHook parameters.
1114
 
 
1115
 
        :param repository: Repository created
1116
 
        :param format: Repository format
1117
 
        :param bzrdir: The bzrdir for the repository
1118
 
        :param shared: The repository is shared
 
772
    @classmethod
 
773
    def create(cls, base, format=None, possible_transports=None):
 
774
        """Create a new BzrDir at the url 'base'.
 
775
 
 
776
        :param format: If supplied, the format of branch to create.  If not
 
777
            supplied, the default is used.
 
778
        :param possible_transports: If supplied, a list of transports that
 
779
            can be reused to share a remote connection.
1119
780
        """
1120
 
        self.repository = repository
1121
 
        self.format = format
1122
 
        self.bzrdir = a_bzrdir
1123
 
        self.shared = shared
1124
 
 
1125
 
    def __eq__(self, other):
1126
 
        return self.__dict__ == other.__dict__
 
781
        if cls is not BzrDir:
 
782
            raise AssertionError("BzrDir.create always creates the "
 
783
                "default format, not one of %r" % cls)
 
784
        return controldir.ControlDir.create(base, format=format,
 
785
                possible_transports=possible_transports)
1127
786
 
1128
787
    def __repr__(self):
1129
 
        if self.repository:
1130
 
            return "<%s for %s>" % (self.__class__.__name__,
1131
 
                self.repository)
1132
 
        else:
1133
 
            return "<%s for %s>" % (self.__class__.__name__,
1134
 
                self.bzrdir)
 
788
        return "<%s at %r>" % (self.__class__.__name__, self.user_url)
 
789
 
 
790
    def update_feature_flags(self, updated_flags):
 
791
        """Update the features required by this bzrdir.
 
792
 
 
793
        :param updated_flags: Dictionary mapping feature names to necessities
 
794
            A necessity can be None to indicate the feature should be removed
 
795
        """
 
796
        self.control_files.lock_write()
 
797
        try:
 
798
            self._format._update_feature_flags(updated_flags)
 
799
            self.transport.put_bytes('branch-format', self._format.as_string())
 
800
        finally:
 
801
            self.control_files.unlock()
1135
802
 
1136
803
 
1137
804
class BzrDirMeta1(BzrDir):
1143
810
    present within a BzrDir.
1144
811
    """
1145
812
 
 
813
    def _get_branch_path(self, name):
 
814
        """Obtain the branch path to use.
 
815
 
 
816
        This uses the API specified branch name first, and then falls back to
 
817
        the branch name specified in the URL. If neither of those is specified,
 
818
        it uses the default branch.
 
819
 
 
820
        :param name: Optional branch name to use
 
821
        :return: Relative path to branch
 
822
        """
 
823
        if name == "":
 
824
            return 'branch'
 
825
        return urlutils.join('branches', name.encode("utf-8"))
 
826
 
 
827
    def _read_branch_list(self):
 
828
        """Read the branch list.
 
829
 
 
830
        :return: List of utf-8 encoded branch names.
 
831
        """
 
832
        try:
 
833
            f = self.control_transport.get('branch-list')
 
834
        except errors.NoSuchFile:
 
835
            return []
 
836
 
 
837
        ret = []
 
838
        try:
 
839
            for name in f:
 
840
                ret.append(name.rstrip("\n"))
 
841
        finally:
 
842
            f.close()
 
843
        return ret
 
844
 
 
845
    def _write_branch_list(self, branches):
 
846
        """Write out the branch list.
 
847
 
 
848
        :param branches: List of utf-8 branch names to write
 
849
        """
 
850
        self.transport.put_bytes('branch-list',
 
851
            "".join([name+"\n" for name in branches]))
 
852
 
 
853
    def __init__(self, _transport, _format):
 
854
        super(BzrDirMeta1, self).__init__(_transport, _format)
 
855
        self.control_files = lockable_files.LockableFiles(
 
856
            self.control_transport, self._format._lock_file_name,
 
857
            self._format._lock_class)
 
858
 
1146
859
    def can_convert_format(self):
1147
860
        """See BzrDir.can_convert_format()."""
1148
861
        return True
1149
862
 
1150
 
    def create_branch(self, name=None, repository=None):
1151
 
        """See BzrDir.create_branch."""
 
863
    def create_branch(self, name=None, repository=None,
 
864
            append_revisions_only=None):
 
865
        """See ControlDir.create_branch."""
 
866
        if name is None:
 
867
            name = self._get_selected_branch()
1152
868
        return self._format.get_branch_format().initialize(self, name=name,
1153
 
                repository=repository)
 
869
                repository=repository,
 
870
                append_revisions_only=append_revisions_only)
1154
871
 
1155
872
    def destroy_branch(self, name=None):
1156
 
        """See BzrDir.create_branch."""
1157
 
        if name is not None:
1158
 
            raise errors.NoColocatedBranchSupport(self)
1159
 
        self.transport.delete_tree('branch')
 
873
        """See ControlDir.destroy_branch."""
 
874
        if name is None:
 
875
            name = self._get_selected_branch()
 
876
        path = self._get_branch_path(name)
 
877
        if name != "":
 
878
            self.control_files.lock_write()
 
879
            try:
 
880
                branches = self._read_branch_list()
 
881
                try:
 
882
                    branches.remove(name.encode("utf-8"))
 
883
                except ValueError:
 
884
                    raise errors.NotBranchError(name)
 
885
                self._write_branch_list(branches)
 
886
            finally:
 
887
                self.control_files.unlock()
 
888
        try:
 
889
            self.transport.delete_tree(path)
 
890
        except errors.NoSuchFile:
 
891
            raise errors.NotBranchError(path=urlutils.join(self.transport.base,
 
892
                path), bzrdir=self)
1160
893
 
1161
894
    def create_repository(self, shared=False):
1162
895
        """See BzrDir.create_repository."""
1164
897
 
1165
898
    def destroy_repository(self):
1166
899
        """See BzrDir.destroy_repository."""
1167
 
        self.transport.delete_tree('repository')
 
900
        try:
 
901
            self.transport.delete_tree('repository')
 
902
        except errors.NoSuchFile:
 
903
            raise errors.NoRepositoryPresent(self)
1168
904
 
1169
905
    def create_workingtree(self, revision_id=None, from_branch=None,
1170
906
                           accelerator_tree=None, hardlink=False):
1192
928
 
1193
929
        This might be a synthetic object for e.g. RemoteBranch and SVN.
1194
930
        """
1195
 
        from bzrlib.branch import BranchFormat
1196
 
        return BranchFormat.find_format(self, name=name)
 
931
        from bzrlib.branch import BranchFormatMetadir
 
932
        return BranchFormatMetadir.find_format(self, name=name)
1197
933
 
1198
934
    def _get_mkdir_mode(self):
1199
935
        """Figure out the mode to use when creating a bzrdir subdir."""
1203
939
 
1204
940
    def get_branch_reference(self, name=None):
1205
941
        """See BzrDir.get_branch_reference()."""
1206
 
        from bzrlib.branch import BranchFormat
1207
 
        format = BranchFormat.find_format(self, name=name)
 
942
        from bzrlib.branch import BranchFormatMetadir
 
943
        format = BranchFormatMetadir.find_format(self, name=name)
1208
944
        return format.get_reference(self, name=name)
1209
945
 
 
946
    def set_branch_reference(self, target_branch, name=None):
 
947
        format = _mod_branch.BranchReferenceFormat()
 
948
        return format.initialize(self, target_branch=target_branch, name=name)
 
949
 
1210
950
    def get_branch_transport(self, branch_format, name=None):
1211
951
        """See BzrDir.get_branch_transport()."""
1212
 
        if name is not None:
1213
 
            raise errors.NoColocatedBranchSupport(self)
 
952
        if name is None:
 
953
            name = self._get_selected_branch()
 
954
        path = self._get_branch_path(name)
1214
955
        # XXX: this shouldn't implicitly create the directory if it's just
1215
956
        # promising to get a transport -- mbp 20090727
1216
957
        if branch_format is None:
1217
 
            return self.transport.clone('branch')
 
958
            return self.transport.clone(path)
1218
959
        try:
1219
960
            branch_format.get_format_string()
1220
961
        except NotImplementedError:
1221
962
            raise errors.IncompatibleFormat(branch_format, self._format)
 
963
        if name != "":
 
964
            branches = self._read_branch_list()
 
965
            utf8_name = name.encode("utf-8")
 
966
            if not utf8_name in branches:
 
967
                self.control_files.lock_write()
 
968
                try:
 
969
                    branches = self._read_branch_list()
 
970
                    dirname = urlutils.dirname(utf8_name)
 
971
                    if dirname != "" and dirname in branches:
 
972
                        raise errors.ParentBranchExists(name)
 
973
                    child_branches = [
 
974
                        b.startswith(utf8_name+"/") for b in branches]
 
975
                    if any(child_branches):
 
976
                        raise errors.AlreadyBranchError(name)
 
977
                    branches.append(utf8_name)
 
978
                    self._write_branch_list(branches)
 
979
                finally:
 
980
                    self.control_files.unlock()
 
981
        branch_transport = self.transport.clone(path)
 
982
        mode = self._get_mkdir_mode()
 
983
        branch_transport.create_prefix(mode=mode)
1222
984
        try:
1223
 
            self.transport.mkdir('branch', mode=self._get_mkdir_mode())
 
985
            self.transport.mkdir(path, mode=mode)
1224
986
        except errors.FileExists:
1225
987
            pass
1226
 
        return self.transport.clone('branch')
 
988
        return self.transport.clone(path)
1227
989
 
1228
990
    def get_repository_transport(self, repository_format):
1229
991
        """See BzrDir.get_repository_transport()."""
1253
1015
            pass
1254
1016
        return self.transport.clone('checkout')
1255
1017
 
 
1018
    def get_branches(self):
 
1019
        """See ControlDir.get_branches."""
 
1020
        ret = {}
 
1021
        try:
 
1022
            ret[""] = self.open_branch(name="")
 
1023
        except (errors.NotBranchError, errors.NoRepositoryPresent):
 
1024
            pass
 
1025
 
 
1026
        for name in self._read_branch_list():
 
1027
            ret[name] = self.open_branch(name=name.decode('utf-8'))
 
1028
 
 
1029
        return ret
 
1030
 
1256
1031
    def has_workingtree(self):
1257
1032
        """Tell if this bzrdir contains a working tree.
1258
1033
 
1259
1034
        Note: if you're going to open the working tree, you should just go
1260
1035
        ahead and try, and not ask permission first.
1261
1036
        """
1262
 
        from bzrlib.workingtree import WorkingTreeFormat
 
1037
        from bzrlib.workingtree import WorkingTreeFormatMetaDir
1263
1038
        try:
1264
 
            WorkingTreeFormat.find_format_string(self)
 
1039
            WorkingTreeFormatMetaDir.find_format_string(self)
1265
1040
        except errors.NoWorkingTree:
1266
1041
            return False
1267
1042
        return True
1268
1043
 
1269
1044
    def needs_format_conversion(self, format):
1270
1045
        """See BzrDir.needs_format_conversion()."""
1271
 
        if not isinstance(self._format, format.__class__):
 
1046
        if (not isinstance(self._format, format.__class__) or
 
1047
            self._format.get_format_string() != format.get_format_string()):
1272
1048
            # it is not a meta dir format, conversion is needed.
1273
1049
            return True
1274
1050
        # we might want to push this down to the repository?
1295
1071
        return False
1296
1072
 
1297
1073
    def open_branch(self, name=None, unsupported=False,
1298
 
                    ignore_fallbacks=False):
1299
 
        """See BzrDir.open_branch."""
 
1074
                    ignore_fallbacks=False, possible_transports=None):
 
1075
        """See ControlDir.open_branch."""
 
1076
        if name is None:
 
1077
            name = self._get_selected_branch()
1300
1078
        format = self.find_branch_format(name=name)
1301
1079
        format.check_support_status(unsupported)
1302
1080
        return format.open(self, name=name,
1303
 
            _found=True, ignore_fallbacks=ignore_fallbacks)
 
1081
            _found=True, ignore_fallbacks=ignore_fallbacks,
 
1082
            possible_transports=possible_transports)
1304
1083
 
1305
1084
    def open_repository(self, unsupported=False):
1306
1085
        """See BzrDir.open_repository."""
1307
 
        from bzrlib.repository import RepositoryFormat
1308
 
        format = RepositoryFormat.find_format(self)
 
1086
        from bzrlib.repository import RepositoryFormatMetaDir
 
1087
        format = RepositoryFormatMetaDir.find_format(self)
1309
1088
        format.check_support_status(unsupported)
1310
1089
        return format.open(self, _found=True)
1311
1090
 
1312
1091
    def open_workingtree(self, unsupported=False,
1313
1092
            recommend_upgrade=True):
1314
1093
        """See BzrDir.open_workingtree."""
1315
 
        from bzrlib.workingtree import WorkingTreeFormat
1316
 
        format = WorkingTreeFormat.find_format(self)
 
1094
        from bzrlib.workingtree import WorkingTreeFormatMetaDir
 
1095
        format = WorkingTreeFormatMetaDir.find_format(self)
1317
1096
        format.check_support_status(unsupported, recommend_upgrade,
1318
1097
            basedir=self.root_transport.base)
1319
1098
        return format.open(self, _found=True)
1322
1101
        return config.TransportConfig(self.transport, 'control.conf')
1323
1102
 
1324
1103
 
 
1104
class BzrFormat(object):
 
1105
    """Base class for all formats of things living in metadirs.
 
1106
 
 
1107
    This class manages the format string that is stored in the 'format'
 
1108
    or 'branch-format' file.
 
1109
 
 
1110
    All classes for (branch-, repository-, workingtree-) formats that
 
1111
    live in meta directories and have their own 'format' file
 
1112
    (i.e. different from .bzr/branch-format) derive from this class,
 
1113
    as well as the relevant base class for their kind
 
1114
    (BranchFormat, WorkingTreeFormat, RepositoryFormat).
 
1115
 
 
1116
    Each format is identified by a "format" or "branch-format" file with a
 
1117
    single line containing the base format name and then an optional list of
 
1118
    feature flags.
 
1119
 
 
1120
    Feature flags are supported as of bzr 2.5. Setting feature flags on formats
 
1121
    will render them inaccessible to older versions of bzr.
 
1122
 
 
1123
    :ivar features: Dictionary mapping feature names to their necessity
 
1124
    """
 
1125
 
 
1126
    _present_features = set()
 
1127
 
 
1128
    def __init__(self):
 
1129
        self.features = {}
 
1130
 
 
1131
    @classmethod
 
1132
    def register_feature(cls, name):
 
1133
        """Register a feature as being present.
 
1134
 
 
1135
        :param name: Name of the feature
 
1136
        """
 
1137
        if " " in name:
 
1138
            raise ValueError("spaces are not allowed in feature names")
 
1139
        if name in cls._present_features:
 
1140
            raise errors.FeatureAlreadyRegistered(name)
 
1141
        cls._present_features.add(name)
 
1142
 
 
1143
    @classmethod
 
1144
    def unregister_feature(cls, name):
 
1145
        """Unregister a feature."""
 
1146
        cls._present_features.remove(name)
 
1147
 
 
1148
    def check_support_status(self, allow_unsupported, recommend_upgrade=True,
 
1149
            basedir=None):
 
1150
        for name, necessity in self.features.iteritems():
 
1151
            if name in self._present_features:
 
1152
                continue
 
1153
            if necessity == "optional":
 
1154
                mutter("ignoring optional missing feature %s", name)
 
1155
                continue
 
1156
            elif necessity == "required":
 
1157
                raise errors.MissingFeature(name)
 
1158
            else:
 
1159
                mutter("treating unknown necessity as require for %s",
 
1160
                       name)
 
1161
                raise errors.MissingFeature(name)
 
1162
 
 
1163
    @classmethod
 
1164
    def get_format_string(cls):
 
1165
        """Return the ASCII format string that identifies this format."""
 
1166
        raise NotImplementedError(cls.get_format_string)
 
1167
 
 
1168
    @classmethod
 
1169
    def from_string(cls, text):
 
1170
        format_string = cls.get_format_string()
 
1171
        if not text.startswith(format_string):
 
1172
            raise AssertionError("Invalid format header %r for %r" % (text, cls))
 
1173
        lines = text[len(format_string):].splitlines()
 
1174
        ret = cls()
 
1175
        for lineno, line in enumerate(lines):
 
1176
            try:
 
1177
                (necessity, feature) = line.split(" ", 1)
 
1178
            except ValueError:
 
1179
                raise errors.ParseFormatError(format=cls, lineno=lineno+2,
 
1180
                    line=line, text=text)
 
1181
            ret.features[feature] = necessity
 
1182
        return ret
 
1183
 
 
1184
    def as_string(self):
 
1185
        """Return the string representation of this format.
 
1186
        """
 
1187
        lines = [self.get_format_string()]
 
1188
        lines.extend([("%s %s\n" % (item[1], item[0])) for item in
 
1189
            self.features.iteritems()])
 
1190
        return "".join(lines)
 
1191
 
 
1192
    @classmethod
 
1193
    def _find_format(klass, registry, kind, format_string):
 
1194
        try:
 
1195
            first_line = format_string[:format_string.index("\n")+1]
 
1196
        except ValueError:
 
1197
            first_line = format_string
 
1198
        try:
 
1199
            cls = registry.get(first_line)
 
1200
        except KeyError:
 
1201
            raise errors.UnknownFormatError(format=first_line, kind=kind)
 
1202
        return cls.from_string(format_string)
 
1203
 
 
1204
    def network_name(self):
 
1205
        """A simple byte string uniquely identifying this format for RPC calls.
 
1206
 
 
1207
        Metadir branch formats use their format string.
 
1208
        """
 
1209
        return self.as_string()
 
1210
 
 
1211
    def __eq__(self, other):
 
1212
        return (self.__class__ is other.__class__ and
 
1213
                self.features == other.features)
 
1214
 
 
1215
    def _update_feature_flags(self, updated_flags):
 
1216
        """Update the feature flags in this format.
 
1217
 
 
1218
        :param updated_flags: Updated feature flags
 
1219
        """
 
1220
        for name, necessity in updated_flags.iteritems():
 
1221
            if necessity is None:
 
1222
                try:
 
1223
                    del self.features[name]
 
1224
                except KeyError:
 
1225
                    pass
 
1226
            else:
 
1227
                self.features[name] = necessity
 
1228
 
 
1229
 
1325
1230
class BzrProber(controldir.Prober):
1326
1231
    """Prober for formats that use a .bzr/ control directory."""
1327
1232
 
1346
1251
        except errors.NoSuchFile:
1347
1252
            raise errors.NotBranchError(path=transport.base)
1348
1253
        try:
1349
 
            return klass.formats.get(format_string)
 
1254
            first_line = format_string[:format_string.index("\n")+1]
 
1255
        except ValueError:
 
1256
            first_line = format_string
 
1257
        try:
 
1258
            cls = klass.formats.get(first_line)
1350
1259
        except KeyError:
1351
 
            raise errors.UnknownFormatError(format=format_string, kind='bzrdir')
 
1260
            raise errors.UnknownFormatError(format=first_line, kind='bzrdir')
 
1261
        return cls.from_string(format_string)
1352
1262
 
1353
1263
    @classmethod
1354
1264
    def known_formats(cls):
1397
1307
        return set([RemoteBzrDirFormat()])
1398
1308
 
1399
1309
 
1400
 
class BzrDirFormat(controldir.ControlDirFormat):
 
1310
class BzrDirFormat(BzrFormat, controldir.ControlDirFormat):
1401
1311
    """ControlDirFormat base class for .bzr/ directories.
1402
1312
 
1403
1313
    Formats are placed in a dict by their format string for reference
1414
1324
    # _lock_class must be set in subclasses to the lock type, typ.
1415
1325
    # TransportLock or LockDir
1416
1326
 
1417
 
    @classmethod
1418
 
    def get_format_string(cls):
1419
 
        """Return the ASCII format string that identifies this format."""
1420
 
        raise NotImplementedError(cls.get_format_string)
1421
 
 
1422
1327
    def initialize_on_transport(self, transport):
1423
1328
        """Initialize a new bzrdir in the base directory of a Transport."""
1424
1329
        try:
1546
1451
        # mode from the root directory
1547
1452
        temp_control = lockable_files.LockableFiles(transport,
1548
1453
                            '', lockable_files.TransportLock)
1549
 
        temp_control._transport.mkdir('.bzr',
1550
 
                                      # FIXME: RBC 20060121 don't peek under
1551
 
                                      # the covers
1552
 
                                      mode=temp_control._dir_mode)
 
1454
        try:
 
1455
            temp_control._transport.mkdir('.bzr',
 
1456
                # FIXME: RBC 20060121 don't peek under
 
1457
                # the covers
 
1458
                mode=temp_control._dir_mode)
 
1459
        except errors.FileExists:
 
1460
            raise errors.AlreadyControlDirError(transport.base)
1553
1461
        if sys.platform == 'win32' and isinstance(transport, local.LocalTransport):
1554
1462
            win32utils.set_file_attr_hidden(transport._abspath('.bzr'))
1555
1463
        file_mode = temp_control._file_mode
1559
1467
                       "This is a Bazaar control directory.\n"
1560
1468
                       "Do not change any files in this directory.\n"
1561
1469
                       "See http://bazaar.canonical.com/ for more information about Bazaar.\n"),
1562
 
                      ('branch-format', self.get_format_string()),
 
1470
                      ('branch-format', self.as_string()),
1563
1471
                      ]
1564
1472
        # NB: no need to escape relative paths that are url safe.
1565
1473
        control_files = lockable_files.LockableFiles(bzrdir_transport,
1609
1517
            compatible with whatever sub formats are supported by self.
1610
1518
        :return: None.
1611
1519
        """
 
1520
        other_format.features = dict(self.features)
 
1521
 
 
1522
    def supports_transport(self, transport):
 
1523
        # bzr formats can be opened over all known transports
 
1524
        return True
 
1525
 
 
1526
    def check_support_status(self, allow_unsupported, recommend_upgrade=True,
 
1527
            basedir=None):
 
1528
        controldir.ControlDirFormat.check_support_status(self,
 
1529
            allow_unsupported=allow_unsupported, recommend_upgrade=recommend_upgrade,
 
1530
            basedir=basedir)
 
1531
        BzrFormat.check_support_status(self, allow_unsupported=allow_unsupported,
 
1532
            recommend_upgrade=recommend_upgrade, basedir=basedir)
1612
1533
 
1613
1534
 
1614
1535
class BzrDirMetaFormat1(BzrDirFormat):
1628
1549
 
1629
1550
    fixed_components = False
1630
1551
 
 
1552
    colocated_branches = True
 
1553
 
1631
1554
    def __init__(self):
 
1555
        BzrDirFormat.__init__(self)
1632
1556
        self._workingtree_format = None
1633
1557
        self._branch_format = None
1634
1558
        self._repository_format = None
1640
1564
            return False
1641
1565
        if other.workingtree_format != self.workingtree_format:
1642
1566
            return False
 
1567
        if other.features != self.features:
 
1568
            return False
1643
1569
        return True
1644
1570
 
1645
1571
    def __ne__(self, other):
1723
1649
                    new_repo_format = None
1724
1650
            if new_repo_format is not None:
1725
1651
                self.repository_format = new_repo_format
1726
 
                note('Source repository format does not support stacking,'
1727
 
                     ' using format:\n  %s',
 
1652
                note(gettext('Source repository format does not support stacking,'
 
1653
                     ' using format:\n  %s'),
1728
1654
                     new_repo_format.get_format_description())
1729
1655
 
1730
1656
        if not self.get_branch_format().supports_stacking():
1743
1669
            if new_branch_format is not None:
1744
1670
                # Does support stacking, use its format.
1745
1671
                self.set_branch_format(new_branch_format)
1746
 
                note('Source branch format does not support stacking,'
1747
 
                     ' using format:\n  %s',
 
1672
                note(gettext('Source branch format does not support stacking,'
 
1673
                     ' using format:\n  %s'),
1748
1674
                     new_branch_format.get_format_description())
1749
1675
 
1750
1676
    def get_converter(self, format=None):
1751
1677
        """See BzrDirFormat.get_converter()."""
1752
1678
        if format is None:
1753
1679
            format = BzrDirFormat.get_default_format()
 
1680
        if (type(self) is BzrDirMetaFormat1 and
 
1681
            type(format) is BzrDirMetaFormat1Colo):
 
1682
            return ConvertMetaToColo(format)
 
1683
        if (type(self) is BzrDirMetaFormat1Colo and
 
1684
            type(format) is BzrDirMetaFormat1):
 
1685
            return ConvertMetaToColo(format)
1754
1686
        if not isinstance(self, format.__class__):
1755
1687
            # converting away from metadir is not implemented
1756
1688
            raise NotImplementedError(self.get_converter)
1765
1697
        """See BzrDirFormat.get_format_description()."""
1766
1698
        return "Meta directory format 1"
1767
1699
 
1768
 
    def network_name(self):
1769
 
        return self.get_format_string()
1770
 
 
1771
1700
    def _open(self, transport):
1772
1701
        """See BzrDirFormat._open."""
1773
1702
        # Create a new format instance because otherwise initialisation of new
1802
1731
            compatible with whatever sub formats are supported by self.
1803
1732
        :return: None.
1804
1733
        """
 
1734
        super(BzrDirMetaFormat1, self)._supply_sub_formats_to(other_format)
1805
1735
        if getattr(self, '_repository_format', None) is not None:
1806
1736
            other_format.repository_format = self.repository_format
1807
1737
        if self._branch_format is not None:
1820
1750
    def __set_workingtree_format(self, wt_format):
1821
1751
        self._workingtree_format = wt_format
1822
1752
 
 
1753
    def __repr__(self):
 
1754
        return "<%r>" % (self.__class__.__name__,)
 
1755
 
1823
1756
    workingtree_format = property(__get_workingtree_format,
1824
1757
                                  __set_workingtree_format)
1825
1758
 
1830
1763
controldir.ControlDirFormat._default_format = BzrDirMetaFormat1()
1831
1764
 
1832
1765
 
 
1766
class BzrDirMetaFormat1Colo(BzrDirMetaFormat1):
 
1767
    """BzrDirMeta1 format with support for colocated branches."""
 
1768
 
 
1769
    colocated_branches = True
 
1770
 
 
1771
    @classmethod
 
1772
    def get_format_string(cls):
 
1773
        """See BzrDirFormat.get_format_string()."""
 
1774
        return "Bazaar meta directory, format 1 (with colocated branches)\n"
 
1775
 
 
1776
    def get_format_description(self):
 
1777
        """See BzrDirFormat.get_format_description()."""
 
1778
        return "Meta directory format 1 with support for colocated branches"
 
1779
 
 
1780
    def _open(self, transport):
 
1781
        """See BzrDirFormat._open."""
 
1782
        # Create a new format instance because otherwise initialisation of new
 
1783
        # metadirs share the global default format object leading to alias
 
1784
        # problems.
 
1785
        format = BzrDirMetaFormat1Colo()
 
1786
        self._supply_sub_formats_to(format)
 
1787
        return BzrDirMeta1(transport, format)
 
1788
 
 
1789
 
 
1790
BzrProber.formats.register(BzrDirMetaFormat1Colo.get_format_string(),
 
1791
    BzrDirMetaFormat1Colo)
 
1792
 
 
1793
 
1833
1794
class ConvertMetaToMeta(controldir.Converter):
1834
1795
    """Converts the components of metadirs."""
1835
1796
 
1854
1815
        else:
1855
1816
            if not isinstance(repo._format, self.target_format.repository_format.__class__):
1856
1817
                from bzrlib.repository import CopyConverter
1857
 
                ui.ui_factory.note('starting repository conversion')
 
1818
                ui.ui_factory.note(gettext('starting repository conversion'))
1858
1819
                converter = CopyConverter(self.target_format.repository_format)
1859
1820
                converter.convert(repo, pb)
1860
1821
        for branch in self.bzrdir.list_branches():
1908
1869
        return to_convert
1909
1870
 
1910
1871
 
 
1872
class ConvertMetaToColo(controldir.Converter):
 
1873
    """Add colocated branch support."""
 
1874
 
 
1875
    def __init__(self, target_format):
 
1876
        """Create a converter.that upgrades a metadir to the colo format.
 
1877
 
 
1878
        :param target_format: The final metadir format that is desired.
 
1879
        """
 
1880
        self.target_format = target_format
 
1881
 
 
1882
    def convert(self, to_convert, pb):
 
1883
        """See Converter.convert()."""
 
1884
        to_convert.transport.put_bytes('branch-format',
 
1885
            self.target_format.as_string())
 
1886
        return BzrDir.open_from_transport(to_convert.root_transport)
 
1887
 
 
1888
 
 
1889
class ConvertMetaToColo(controldir.Converter):
 
1890
    """Convert a 'development-colo' bzrdir to a '2a' bzrdir."""
 
1891
 
 
1892
    def __init__(self, target_format):
 
1893
        """Create a converter that converts a 'development-colo' metadir
 
1894
        to a '2a' metadir.
 
1895
 
 
1896
        :param target_format: The final metadir format that is desired.
 
1897
        """
 
1898
        self.target_format = target_format
 
1899
 
 
1900
    def convert(self, to_convert, pb):
 
1901
        """See Converter.convert()."""
 
1902
        to_convert.transport.put_bytes('branch-format',
 
1903
            self.target_format.as_string())
 
1904
        return BzrDir.open_from_transport(to_convert.root_transport)
 
1905
 
 
1906
 
1911
1907
controldir.ControlDirFormat.register_server_prober(RemoteBzrProber)
1912
1908
 
1913
1909
 
1990
1986
        else:
1991
1987
            self._require_stacking = True
1992
1988
 
1993
 
    def acquire_repository(self, make_working_trees=None, shared=False):
 
1989
    def acquire_repository(self, make_working_trees=None, shared=False,
 
1990
            possible_transports=None):
1994
1991
        """Acquire a repository for this bzrdir.
1995
1992
 
1996
1993
        Implementations may create a new repository or use a pre-exising
2002
1999
        :return: A repository, is_new_flag (True if the repository was
2003
2000
            created).
2004
2001
        """
2005
 
        raise NotImplemented(RepositoryAcquisitionPolicy.acquire_repository)
 
2002
        raise NotImplementedError(RepositoryAcquisitionPolicy.acquire_repository)
2006
2003
 
2007
2004
 
2008
2005
class CreateRepository(RepositoryAcquisitionPolicy):
2021
2018
                                             require_stacking)
2022
2019
        self._bzrdir = bzrdir
2023
2020
 
2024
 
    def acquire_repository(self, make_working_trees=None, shared=False):
 
2021
    def acquire_repository(self, make_working_trees=None, shared=False,
 
2022
            possible_transports=None):
2025
2023
        """Implementation of RepositoryAcquisitionPolicy.acquire_repository
2026
2024
 
2027
2025
        Creates the desired repository in the bzrdir we already have.
2028
2026
        """
 
2027
        if possible_transports is None:
 
2028
            possible_transports = []
 
2029
        else:
 
2030
            possible_transports = list(possible_transports)
 
2031
        possible_transports.append(self._bzrdir.root_transport)
2029
2032
        stack_on = self._get_full_stack_on()
2030
2033
        if stack_on:
2031
2034
            format = self._bzrdir._format
2032
2035
            format.require_stacking(stack_on=stack_on,
2033
 
                                    possible_transports=[self._bzrdir.root_transport])
 
2036
                                    possible_transports=possible_transports)
2034
2037
            if not self._require_stacking:
2035
2038
                # We have picked up automatic stacking somewhere.
2036
 
                note('Using default stacking branch %s at %s', self._stack_on,
2037
 
                    self._stack_on_pwd)
 
2039
                note(gettext('Using default stacking branch {0} at {1}').format(
 
2040
                    self._stack_on, self._stack_on_pwd))
2038
2041
        repository = self._bzrdir.create_repository(shared=shared)
2039
2042
        self._add_fallback(repository,
2040
 
                           possible_transports=[self._bzrdir.transport])
 
2043
                           possible_transports=possible_transports)
2041
2044
        if make_working_trees is not None:
2042
2045
            repository.set_make_working_trees(make_working_trees)
2043
2046
        return repository, True
2059
2062
                                             require_stacking)
2060
2063
        self._repository = repository
2061
2064
 
2062
 
    def acquire_repository(self, make_working_trees=None, shared=False):
 
2065
    def acquire_repository(self, make_working_trees=None, shared=False,
 
2066
            possible_transports=None):
2063
2067
        """Implementation of RepositoryAcquisitionPolicy.acquire_repository
2064
2068
 
2065
2069
        Returns an existing repository to use.
2066
2070
        """
 
2071
        if possible_transports is None:
 
2072
            possible_transports = []
 
2073
        else:
 
2074
            possible_transports = list(possible_transports)
 
2075
        possible_transports.append(self._repository.bzrdir.transport)
2067
2076
        self._add_fallback(self._repository,
2068
 
                       possible_transports=[self._repository.bzrdir.transport])
 
2077
                       possible_transports=possible_transports)
2069
2078
        return self._repository, False
2070
2079
 
2071
2080
 
2075
2084
         tree_format=None,
2076
2085
         hidden=False,
2077
2086
         experimental=False,
2078
 
         alias=False):
 
2087
         alias=False, bzrdir_format=None):
2079
2088
    """Register a metadir subformat.
2080
2089
 
2081
 
    These all use a BzrDirMetaFormat1 bzrdir, but can be parameterized
2082
 
    by the Repository/Branch/WorkingTreeformats.
 
2090
    These all use a meta bzrdir, but can be parameterized by the
 
2091
    Repository/Branch/WorkingTreeformats.
2083
2092
 
2084
2093
    :param repository_format: The fully-qualified repository format class
2085
2094
        name as a string.
2088
2097
    :param tree_format: Fully-qualified tree format class name as
2089
2098
        a string.
2090
2099
    """
 
2100
    if bzrdir_format is None:
 
2101
        bzrdir_format = BzrDirMetaFormat1
2091
2102
    # This should be expanded to support setting WorkingTree and Branch
2092
 
    # formats, once BzrDirMetaFormat1 supports that.
 
2103
    # formats, once the API supports that.
2093
2104
    def _load(full_name):
2094
2105
        mod_name, factory_name = full_name.rsplit('.', 1)
2095
2106
        try:
2102
2113
        return factory()
2103
2114
 
2104
2115
    def helper():
2105
 
        bd = BzrDirMetaFormat1()
 
2116
        bd = bzrdir_format()
2106
2117
        if branch_format is not None:
2107
2118
            bd.set_branch_format(_load(branch_format))
2108
2119
        if tree_format is not None:
2122
2133
    deprecated=True)
2123
2134
register_metadir(controldir.format_registry, 'dirstate',
2124
2135
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
2125
 
    help='New in 0.15: Fast local operations. Compatible with bzr 0.8 and '
2126
 
        'above when accessed over the network.',
 
2136
    help='Format using dirstate for working trees. '
 
2137
        'Compatible with bzr 0.8 and '
 
2138
        'above when accessed over the network. Introduced in bzr 0.15.',
2127
2139
    branch_format='bzrlib.branch.BzrBranchFormat5',
2128
2140
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2129
2141
    hidden=True,
2130
2142
    deprecated=True)
2131
2143
register_metadir(controldir.format_registry, 'dirstate-tags',
2132
2144
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
2133
 
    help='New in 0.15: Fast local operations and improved scaling for '
2134
 
        'network operations. Additionally adds support for tags.'
2135
 
        ' Incompatible with bzr < 0.15.',
 
2145
    help='Variant of dirstate with support for tags. '
 
2146
        'Introduced in bzr 0.15.',
2136
2147
    branch_format='bzrlib.branch.BzrBranchFormat6',
2137
2148
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2138
2149
    hidden=True,
2139
2150
    deprecated=True)
2140
2151
register_metadir(controldir.format_registry, 'rich-root',
2141
2152
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit4',
2142
 
    help='New in 1.0.  Better handling of tree roots.  Incompatible with'
2143
 
        ' bzr < 1.0.',
 
2153
    help='Variant of dirstate with better handling of tree roots. '
 
2154
        'Introduced in bzr 1.0',
2144
2155
    branch_format='bzrlib.branch.BzrBranchFormat6',
2145
2156
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2146
2157
    hidden=True,
2147
2158
    deprecated=True)
2148
2159
register_metadir(controldir.format_registry, 'dirstate-with-subtree',
2149
2160
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
2150
 
    help='New in 0.15: Fast local operations and improved scaling for '
2151
 
        'network operations. Additionally adds support for versioning nested '
2152
 
        'bzr branches. Incompatible with bzr < 0.15.',
 
2161
    help='Variant of dirstate with support for nested trees. '
 
2162
         'Introduced in 0.15.',
2153
2163
    branch_format='bzrlib.branch.BzrBranchFormat6',
2154
2164
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2155
2165
    experimental=True,
2157
2167
    )
2158
2168
register_metadir(controldir.format_registry, 'pack-0.92',
2159
2169
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack1',
2160
 
    help='New in 0.92: Pack-based format with data compatible with '
2161
 
        'dirstate-tags format repositories. Interoperates with '
2162
 
        'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
 
2170
    help='Pack-based format used in 1.x series. Introduced in 0.92. '
 
2171
        'Interoperates with bzr repositories before 0.92 but cannot be '
 
2172
        'read by bzr < 0.92. '
2163
2173
        ,
2164
2174
    branch_format='bzrlib.branch.BzrBranchFormat6',
2165
2175
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
 
2176
    deprecated=True,
2166
2177
    )
2167
2178
register_metadir(controldir.format_registry, 'pack-0.92-subtree',
2168
2179
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack3',
2169
 
    help='New in 0.92: Pack-based format with data compatible with '
2170
 
        'dirstate-with-subtree format repositories. Interoperates with '
 
2180
    help='Pack-based format used in 1.x series, with subtree support. '
 
2181
        'Introduced in 0.92. Interoperates with '
2171
2182
        'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
2172
2183
        ,
2173
2184
    branch_format='bzrlib.branch.BzrBranchFormat6',
2174
2185
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2175
2186
    hidden=True,
 
2187
    deprecated=True,
2176
2188
    experimental=True,
2177
2189
    )
2178
2190
register_metadir(controldir.format_registry, 'rich-root-pack',
2179
2191
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack4',
2180
 
    help='New in 1.0: A variant of pack-0.92 that supports rich-root data '
2181
 
         '(needed for bzr-svn and bzr-git).',
 
2192
    help='A variant of pack-0.92 that supports rich-root data '
 
2193
         '(needed for bzr-svn and bzr-git). Introduced in 1.0.',
2182
2194
    branch_format='bzrlib.branch.BzrBranchFormat6',
2183
2195
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2184
2196
    hidden=True,
 
2197
    deprecated=True,
2185
2198
    )
2186
2199
register_metadir(controldir.format_registry, '1.6',
2187
2200
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack5',
2191
2204
    branch_format='bzrlib.branch.BzrBranchFormat7',
2192
2205
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2193
2206
    hidden=True,
 
2207
    deprecated=True,
2194
2208
    )
2195
2209
register_metadir(controldir.format_registry, '1.6.1-rich-root',
2196
2210
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack5RichRoot',
2199
2213
    branch_format='bzrlib.branch.BzrBranchFormat7',
2200
2214
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2201
2215
    hidden=True,
 
2216
    deprecated=True,
2202
2217
    )
2203
2218
register_metadir(controldir.format_registry, '1.9',
2204
2219
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack6',
2208
2223
    branch_format='bzrlib.branch.BzrBranchFormat7',
2209
2224
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2210
2225
    hidden=True,
 
2226
    deprecated=True,
2211
2227
    )
2212
2228
register_metadir(controldir.format_registry, '1.9-rich-root',
2213
2229
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack6RichRoot',
2216
2232
    branch_format='bzrlib.branch.BzrBranchFormat7',
2217
2233
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2218
2234
    hidden=True,
 
2235
    deprecated=True,
2219
2236
    )
2220
2237
register_metadir(controldir.format_registry, '1.14',
2221
2238
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack6',
2222
2239
    help='A working-tree format that supports content filtering.',
2223
2240
    branch_format='bzrlib.branch.BzrBranchFormat7',
2224
2241
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat5',
 
2242
    hidden=True,
 
2243
    deprecated=True,
2225
2244
    )
2226
2245
register_metadir(controldir.format_registry, '1.14-rich-root',
2227
2246
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack6RichRoot',
2229
2248
         '(needed for bzr-svn and bzr-git).',
2230
2249
    branch_format='bzrlib.branch.BzrBranchFormat7',
2231
2250
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat5',
 
2251
    hidden=True,
 
2252
    deprecated=True,
2232
2253
    )
2233
2254
# The following un-numbered 'development' formats should always just be aliases.
2234
2255
register_metadir(controldir.format_registry, 'development-subtree',
2262
2283
    alias=False,
2263
2284
    )
2264
2285
 
 
2286
register_metadir(controldir.format_registry, 'development-colo',
 
2287
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2a',
 
2288
    help='The 2a format with experimental support for colocated branches.\n',
 
2289
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
2290
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat6',
 
2291
    experimental=True,
 
2292
    bzrdir_format=BzrDirMetaFormat1Colo,
 
2293
    )
 
2294
 
 
2295
 
2265
2296
# And the development formats above will have aliased one of the following:
2266
2297
 
2267
2298
# Finally, the current format.
2268
2299
register_metadir(controldir.format_registry, '2a',
2269
2300
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2a',
2270
 
    help='First format for bzr 2.0 series.\n'
 
2301
    help='Format for the bzr 2.0 series.\n'
2271
2302
        'Uses group-compress storage.\n'
2272
2303
        'Provides rich roots which are a one-way transition.\n',
2273
2304
        # 'storage in packs, 255-way hashed CHK inventory, bencode revision, group compress, '