~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

  • Committer: Tarmac
  • Author(s): Vincent Ladeuil
  • Date: 2017-01-30 14:42:05 UTC
  • mfrom: (6620.1.1 trunk)
  • Revision ID: tarmac-20170130144205-r8fh2xpmiuxyozpv
Merge  2.7 into trunk including fix for bug #1657238 [r=vila]

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,
52
55
    )
 
56
from bzrlib.branchfmt import fullhistory as fullhistorybranch
53
57
from bzrlib.repofmt import knitpack_repo
54
58
from bzrlib.transport import (
55
59
    do_catching_redirections,
56
60
    local,
57
61
    )
 
62
from bzrlib.i18n import gettext
58
63
""")
59
64
 
60
65
from bzrlib.trace import (
65
70
from bzrlib import (
66
71
    config,
67
72
    controldir,
68
 
    hooks,
69
73
    registry,
70
74
    )
71
75
from bzrlib.symbol_versioning import (
200
204
                if (result_repo.user_url == result.user_url
201
205
                    and not require_stacking and
202
206
                    revision_id is not None):
203
 
                    fetch_spec = graph.PendingAncestryResult(
 
207
                    fetch_spec = vf_search.PendingAncestryResult(
204
208
                        [revision_id], local_repo)
205
209
                    result_repo.fetch(local_repo, fetch_spec=fetch_spec)
206
210
                else:
221
225
            # the tree and fail.
222
226
            result.root_transport.local_abspath('.')
223
227
            if result_repo is None or result_repo.make_working_trees():
224
 
                self.open_workingtree().clone(result)
 
228
                self.open_workingtree().clone(result, revision_id=revision_id)
225
229
        except (errors.NoWorkingTree, errors.NotLocalUrl):
226
230
            pass
227
231
        return result
232
236
        t = _mod_transport.get_transport(url)
233
237
        t.ensure_base()
234
238
 
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
239
    def determine_repository_policy(self, force_new_repo=False, stack_on=None,
327
240
                                    stack_on_pwd=None, require_stacking=False):
328
241
        """Return an object representing a policy to use.
443
356
            location of this control directory.
444
357
        :param create_tree_if_local: If true, a working-tree will be created
445
358
            when working locally.
 
359
        :return: The created control directory
446
360
        """
447
361
        operation = cleanup.OperationWithCleanups(self._sprout)
448
362
        return operation.run(url, revision_id=revision_id,
461
375
        if revision_id is not None:
462
376
            fetch_spec_factory.add_revision_ids([revision_id])
463
377
            fetch_spec_factory.source_branch_stop_revision_id = revision_id
 
378
        if possible_transports is None:
 
379
            possible_transports = []
 
380
        else:
 
381
            possible_transports = list(possible_transports) + [
 
382
                self.root_transport]
464
383
        target_transport = _mod_transport.get_transport(url,
465
384
            possible_transports)
466
385
        target_transport.ensure_base()
467
386
        cloning_format = self.cloning_metadir(stacked)
468
387
        # Create/update the result branch
469
 
        result = cloning_format.initialize_on_transport(target_transport)
 
388
        try:
 
389
            result = controldir.ControlDir.open_from_transport(target_transport)
 
390
        except errors.NotBranchError:
 
391
            result = cloning_format.initialize_on_transport(target_transport)
470
392
        source_branch, source_repository = self._find_source_repo(
471
393
            add_cleanup, source_branch)
472
394
        fetch_spec_factory.source_branch = source_branch
478
400
            stacked_branch_url = None
479
401
        repository_policy = result.determine_repository_policy(
480
402
            force_new_repo, stacked_branch_url, require_stacking=stacked)
481
 
        result_repo, is_new_repo = repository_policy.acquire_repository()
 
403
        result_repo, is_new_repo = repository_policy.acquire_repository(
 
404
            possible_transports=possible_transports)
482
405
        add_cleanup(result_repo.lock_write().unlock)
483
406
        fetch_spec_factory.source_repo = source_repository
484
407
        fetch_spec_factory.target_repo = result_repo
505
428
        mutter("created new branch %r" % (result_branch,))
506
429
 
507
430
        # Create/update the result working tree
508
 
        if (create_tree_if_local and
 
431
        if (create_tree_if_local and not result.has_workingtree() and
509
432
            isinstance(target_transport, local.LocalTransport) and
510
433
            (result_repo is None or result_repo.make_working_trees())):
511
434
            wt = result.create_workingtree(accelerator_tree=accelerator_tree,
543
466
                    stacked=stacked)
544
467
        return result
545
468
 
546
 
    @staticmethod
547
 
    def create_branch_convenience(base, force_new_repo=False,
548
 
                                  force_new_tree=None, format=None,
549
 
                                  possible_transports=None):
550
 
        """Create a new BzrDir, Branch and Repository at the url 'base'.
551
 
 
552
 
        This is a convenience function - it will use an existing repository
553
 
        if possible, can be told explicitly whether to create a working tree or
554
 
        not.
555
 
 
556
 
        This will use the current default BzrDirFormat unless one is
557
 
        specified, and use whatever
558
 
        repository format that that uses via bzrdir.create_branch and
559
 
        create_repository. If a shared repository is available that is used
560
 
        preferentially. Whatever repository is used, its tree creation policy
561
 
        is followed.
562
 
 
563
 
        The created Branch object is returned.
564
 
        If a working tree cannot be made due to base not being a file:// url,
565
 
        no error is raised unless force_new_tree is True, in which case no
566
 
        data is created on disk and NotLocalUrl is raised.
567
 
 
568
 
        :param base: The URL to create the branch at.
569
 
        :param force_new_repo: If True a new repository is always created.
570
 
        :param force_new_tree: If True or False force creation of a tree or
571
 
                               prevent such creation respectively.
572
 
        :param format: Override for the bzrdir format to create.
573
 
        :param possible_transports: An optional reusable transports list.
574
 
        """
575
 
        if force_new_tree:
576
 
            # check for non local urls
577
 
            t = _mod_transport.get_transport(base, possible_transports)
578
 
            if not isinstance(t, local.LocalTransport):
579
 
                raise errors.NotLocalUrl(base)
580
 
        bzrdir = BzrDir.create(base, format, possible_transports)
581
 
        repo = bzrdir._find_or_create_repository(force_new_repo)
582
 
        result = bzrdir.create_branch()
583
 
        if force_new_tree or (repo.make_working_trees() and
584
 
                              force_new_tree is None):
585
 
            try:
586
 
                bzrdir.create_workingtree()
587
 
            except errors.NotLocalUrl:
588
 
                pass
589
 
        return result
590
 
 
591
 
    @staticmethod
592
 
    def create_standalone_workingtree(base, format=None):
593
 
        """Create a new BzrDir, WorkingTree, Branch and Repository at 'base'.
594
 
 
595
 
        'base' must be a local path or a file:// url.
596
 
 
597
 
        This will use the current default BzrDirFormat unless one is
598
 
        specified, and use whatever
599
 
        repository format that that uses for bzrdirformat.create_workingtree,
600
 
        create_branch and create_repository.
601
 
 
602
 
        :param format: Override for the bzrdir format to create.
603
 
        :return: The WorkingTree object.
604
 
        """
605
 
        t = _mod_transport.get_transport(base)
606
 
        if not isinstance(t, local.LocalTransport):
607
 
            raise errors.NotLocalUrl(base)
608
 
        bzrdir = BzrDir.create_branch_and_repo(base,
609
 
                                               force_new_repo=True,
610
 
                                               format=format).bzrdir
611
 
        return bzrdir.create_workingtree()
612
 
 
613
 
    @deprecated_method(deprecated_in((2, 3, 0)))
614
 
    def generate_backup_name(self, base):
615
 
        return self._available_backup_name(base)
616
 
 
617
469
    def _available_backup_name(self, base):
618
470
        """Find a non-existing backup file name based on base.
619
471
 
632
484
            old_path = self.root_transport.abspath('.bzr')
633
485
            backup_dir = self._available_backup_name('backup.bzr')
634
486
            new_path = self.root_transport.abspath(backup_dir)
635
 
            ui.ui_factory.note('making backup of %s\n  to %s' % (
 
487
            ui.ui_factory.note(gettext('making backup of {0}\n  to {1}').format(
636
488
                urlutils.unescape_for_display(old_path, 'utf-8'),
637
489
                urlutils.unescape_for_display(new_path, 'utf-8')))
638
490
            self.root_transport.copy_tree('.bzr', backup_dir)
655
507
            try:
656
508
                to_path = '.bzr.retired.%d' % i
657
509
                self.root_transport.rename('.bzr', to_path)
658
 
                note("renamed %s to %s"
659
 
                    % (self.root_transport.abspath('.bzr'), to_path))
 
510
                note(gettext("renamed {0} to {1}").format(
 
511
                    self.root_transport.abspath('.bzr'), to_path))
660
512
                return
661
513
            except (errors.TransportError, IOError, errors.PathError):
662
514
                i += 1
689
541
                return None
690
542
            # find the next containing bzrdir
691
543
            try:
692
 
                found_bzrdir = BzrDir.open_containing_from_transport(
 
544
                found_bzrdir = self.open_containing_from_transport(
693
545
                    next_transport)[0]
694
546
            except errors.NotBranchError:
695
547
                return None
812
664
        # add new tests for it to the appropriate place.
813
665
        return filename == '.bzr' or filename.startswith('.bzr/')
814
666
 
815
 
    @staticmethod
816
 
    def open_unsupported(base):
817
 
        """Open a branch which is not supported."""
818
 
        return BzrDir.open(base, _unsupported=True)
819
 
 
820
 
    @staticmethod
821
 
    def open(base, _unsupported=False, possible_transports=None):
822
 
        """Open an existing bzrdir, rooted at 'base' (url).
823
 
 
824
 
        :param _unsupported: a private parameter to the BzrDir class.
825
 
        """
826
 
        t = _mod_transport.get_transport(base, possible_transports)
827
 
        return BzrDir.open_from_transport(t, _unsupported=_unsupported)
828
 
 
829
 
    @staticmethod
830
 
    def open_from_transport(transport, _unsupported=False,
831
 
                            _server_formats=True):
832
 
        """Open a bzrdir within a particular directory.
833
 
 
834
 
        :param transport: Transport containing the bzrdir.
835
 
        :param _unsupported: private.
836
 
        """
837
 
        for hook in BzrDir.hooks['pre_open']:
838
 
            hook(transport)
839
 
        # Keep initial base since 'transport' may be modified while following
840
 
        # the redirections.
841
 
        base = transport.base
842
 
        def find_format(transport):
843
 
            return transport, controldir.ControlDirFormat.find_format(
844
 
                transport, _server_formats=_server_formats)
845
 
 
846
 
        def redirected(transport, e, redirection_notice):
847
 
            redirected_transport = transport._redirected_to(e.source, e.target)
848
 
            if redirected_transport is None:
849
 
                raise errors.NotBranchError(base)
850
 
            note('%s is%s redirected to %s',
851
 
                 transport.base, e.permanently, redirected_transport.base)
852
 
            return redirected_transport
853
 
 
854
 
        try:
855
 
            transport, format = do_catching_redirections(find_format,
856
 
                                                         transport,
857
 
                                                         redirected)
858
 
        except errors.TooManyRedirections:
859
 
            raise errors.NotBranchError(base)
860
 
 
861
 
        format.check_support_status(_unsupported)
862
 
        return format.open(transport, _found=True)
863
 
 
864
 
    @staticmethod
865
 
    def open_containing(url, possible_transports=None):
866
 
        """Open an existing branch which contains url.
867
 
 
868
 
        :param url: url to search from.
869
 
 
870
 
        See open_containing_from_transport for more detail.
871
 
        """
872
 
        transport = _mod_transport.get_transport(url, possible_transports)
873
 
        return BzrDir.open_containing_from_transport(transport)
874
 
 
875
 
    @staticmethod
876
 
    def open_containing_from_transport(a_transport):
877
 
        """Open an existing branch which contains a_transport.base.
878
 
 
879
 
        This probes for a branch at a_transport, and searches upwards from there.
880
 
 
881
 
        Basically we keep looking up until we find the control directory or
882
 
        run into the root.  If there isn't one, raises NotBranchError.
883
 
        If there is one and it is either an unrecognised format or an unsupported
884
 
        format, UnknownFormatError or UnsupportedFormatError are raised.
885
 
        If there is one, it is returned, along with the unused portion of url.
886
 
 
887
 
        :return: The BzrDir that contains the path, and a Unicode path
888
 
                for the rest of the URL.
889
 
        """
890
 
        # this gets the normalised url back. I.e. '.' -> the full path.
891
 
        url = a_transport.base
892
 
        while True:
893
 
            try:
894
 
                result = BzrDir.open_from_transport(a_transport)
895
 
                return result, urlutils.unescape(a_transport.relpath(url))
896
 
            except errors.NotBranchError, e:
897
 
                pass
898
 
            try:
899
 
                new_t = a_transport.clone('..')
900
 
            except errors.InvalidURLJoin:
901
 
                # reached the root, whatever that may be
902
 
                raise errors.NotBranchError(path=url)
903
 
            if new_t.base == a_transport.base:
904
 
                # reached the root, whatever that may be
905
 
                raise errors.NotBranchError(path=url)
906
 
            a_transport = new_t
907
 
 
908
 
    @classmethod
909
 
    def open_tree_or_branch(klass, location):
910
 
        """Return the branch and working tree at a location.
911
 
 
912
 
        If there is no tree at the location, tree will be None.
913
 
        If there is no branch at the location, an exception will be
914
 
        raised
915
 
        :return: (tree, branch)
916
 
        """
917
 
        bzrdir = klass.open(location)
918
 
        return bzrdir._get_tree_branch()
919
 
 
920
 
    @classmethod
921
 
    def open_containing_tree_or_branch(klass, location):
922
 
        """Return the branch and working tree contained by a location.
923
 
 
924
 
        Returns (tree, branch, relpath).
925
 
        If there is no tree at containing the location, tree will be None.
926
 
        If there is no branch containing the location, an exception will be
927
 
        raised
928
 
        relpath is the portion of the path that is contained by the branch.
929
 
        """
930
 
        bzrdir, relpath = klass.open_containing(location)
931
 
        tree, branch = bzrdir._get_tree_branch()
932
 
        return tree, branch, relpath
933
 
 
934
 
    @classmethod
935
 
    def open_containing_tree_branch_or_repository(klass, location):
936
 
        """Return the working tree, branch and repo contained by a location.
937
 
 
938
 
        Returns (tree, branch, repository, relpath).
939
 
        If there is no tree containing the location, tree will be None.
940
 
        If there is no branch containing the location, branch will be None.
941
 
        If there is no repository containing the location, repository will be
942
 
        None.
943
 
        relpath is the portion of the path that is contained by the innermost
944
 
        BzrDir.
945
 
 
946
 
        If no tree, branch or repository is found, a NotBranchError is raised.
947
 
        """
948
 
        bzrdir, relpath = klass.open_containing(location)
949
 
        try:
950
 
            tree, branch = bzrdir._get_tree_branch()
951
 
        except errors.NotBranchError:
952
 
            try:
953
 
                repo = bzrdir.find_repository()
954
 
                return None, None, repo, relpath
955
 
            except (errors.NoRepositoryPresent):
956
 
                raise errors.NotBranchError(location)
957
 
        return tree, branch, branch.repository, relpath
958
 
 
959
667
    def _cloning_metadir(self):
960
668
        """Produce a metadir suitable for cloning with.
961
669
 
1001
709
 
1002
710
        :require_stacking: If True, non-stackable formats will be upgraded
1003
711
            to similar stackable formats.
1004
 
        :returns: a BzrDirFormat with all component formats either set
 
712
        :returns: a ControlDirFormat with all component formats either set
1005
713
            appropriately or set to None if that component should not be
1006
714
            created.
1007
715
        """
1019
727
            format.require_stacking()
1020
728
        return format
1021
729
 
1022
 
    @classmethod
1023
 
    def create(cls, base, format=None, possible_transports=None):
1024
 
        """Create a new BzrDir at the url 'base'.
1025
 
 
1026
 
        :param format: If supplied, the format of branch to create.  If not
1027
 
            supplied, the default is used.
1028
 
        :param possible_transports: If supplied, a list of transports that
1029
 
            can be reused to share a remote connection.
1030
 
        """
1031
 
        if cls is not BzrDir:
1032
 
            raise AssertionError("BzrDir.create always creates the"
1033
 
                "default format, not one of %r" % cls)
1034
 
        t = _mod_transport.get_transport(base, possible_transports)
1035
 
        t.ensure_base()
1036
 
        if format is None:
1037
 
            format = controldir.ControlDirFormat.get_default_format()
1038
 
        return format.initialize_on_transport(t)
1039
 
 
1040
730
    def get_branch_transport(self, branch_format, name=None):
1041
731
        """Get the transport for use by branch format in this BzrDir.
1042
732
 
1076
766
        """
1077
767
        raise NotImplementedError(self.get_workingtree_transport)
1078
768
 
1079
 
 
1080
 
class BzrDirHooks(hooks.Hooks):
1081
 
    """Hooks for BzrDir operations."""
1082
 
 
1083
 
    def __init__(self):
1084
 
        """Create the default hooks."""
1085
 
        hooks.Hooks.__init__(self, "bzrlib.bzrdir", "BzrDir.hooks")
1086
 
        self.add_hook('pre_open',
1087
 
            "Invoked before attempting to open a BzrDir with the transport "
1088
 
            "that the open will use.", (1, 14))
1089
 
        self.add_hook('post_repo_init',
1090
 
            "Invoked after a repository has been initialized. "
1091
 
            "post_repo_init is called with a "
1092
 
            "bzrlib.bzrdir.RepoInitHookParams.",
1093
 
            (2, 2))
1094
 
 
1095
 
# install the default hooks
1096
 
BzrDir.hooks = BzrDirHooks()
1097
 
 
1098
 
 
1099
 
class RepoInitHookParams(object):
1100
 
    """Object holding parameters passed to `*_repo_init` hooks.
1101
 
 
1102
 
    There are 4 fields that hooks may wish to access:
1103
 
 
1104
 
    :ivar repository: Repository created
1105
 
    :ivar format: Repository format
1106
 
    :ivar bzrdir: The bzrdir for the repository
1107
 
    :ivar shared: The repository is shared
1108
 
    """
1109
 
 
1110
 
    def __init__(self, repository, format, a_bzrdir, shared):
1111
 
        """Create a group of RepoInitHook parameters.
1112
 
 
1113
 
        :param repository: Repository created
1114
 
        :param format: Repository format
1115
 
        :param bzrdir: The bzrdir for the repository
1116
 
        :param shared: The repository is shared
 
769
    @classmethod
 
770
    def create(cls, base, format=None, possible_transports=None):
 
771
        """Create a new BzrDir at the url 'base'.
 
772
 
 
773
        :param format: If supplied, the format of branch to create.  If not
 
774
            supplied, the default is used.
 
775
        :param possible_transports: If supplied, a list of transports that
 
776
            can be reused to share a remote connection.
1117
777
        """
1118
 
        self.repository = repository
1119
 
        self.format = format
1120
 
        self.bzrdir = a_bzrdir
1121
 
        self.shared = shared
1122
 
 
1123
 
    def __eq__(self, other):
1124
 
        return self.__dict__ == other.__dict__
 
778
        if cls is not BzrDir:
 
779
            raise AssertionError("BzrDir.create always creates the "
 
780
                "default format, not one of %r" % cls)
 
781
        return controldir.ControlDir.create(base, format=format,
 
782
                possible_transports=possible_transports)
1125
783
 
1126
784
    def __repr__(self):
1127
 
        if self.repository:
1128
 
            return "<%s for %s>" % (self.__class__.__name__,
1129
 
                self.repository)
1130
 
        else:
1131
 
            return "<%s for %s>" % (self.__class__.__name__,
1132
 
                self.bzrdir)
 
785
        return "<%s at %r>" % (self.__class__.__name__, self.user_url)
 
786
 
 
787
    def update_feature_flags(self, updated_flags):
 
788
        """Update the features required by this bzrdir.
 
789
 
 
790
        :param updated_flags: Dictionary mapping feature names to necessities
 
791
            A necessity can be None to indicate the feature should be removed
 
792
        """
 
793
        self.control_files.lock_write()
 
794
        try:
 
795
            self._format._update_feature_flags(updated_flags)
 
796
            self.transport.put_bytes('branch-format', self._format.as_string())
 
797
        finally:
 
798
            self.control_files.unlock()
1133
799
 
1134
800
 
1135
801
class BzrDirMeta1(BzrDir):
1141
807
    present within a BzrDir.
1142
808
    """
1143
809
 
 
810
    def _get_branch_path(self, name):
 
811
        """Obtain the branch path to use.
 
812
 
 
813
        This uses the API specified branch name first, and then falls back to
 
814
        the branch name specified in the URL. If neither of those is specified,
 
815
        it uses the default branch.
 
816
 
 
817
        :param name: Optional branch name to use
 
818
        :return: Relative path to branch
 
819
        """
 
820
        if name == "":
 
821
            return 'branch'
 
822
        return urlutils.join('branches', name.encode("utf-8"))
 
823
 
 
824
    def _read_branch_list(self):
 
825
        """Read the branch list.
 
826
 
 
827
        :return: List of utf-8 encoded branch names.
 
828
        """
 
829
        try:
 
830
            f = self.control_transport.get('branch-list')
 
831
        except errors.NoSuchFile:
 
832
            return []
 
833
 
 
834
        ret = []
 
835
        try:
 
836
            for name in f:
 
837
                ret.append(name.rstrip("\n"))
 
838
        finally:
 
839
            f.close()
 
840
        return ret
 
841
 
 
842
    def _write_branch_list(self, branches):
 
843
        """Write out the branch list.
 
844
 
 
845
        :param branches: List of utf-8 branch names to write
 
846
        """
 
847
        self.transport.put_bytes('branch-list',
 
848
            "".join([name+"\n" for name in branches]))
 
849
 
 
850
    def __init__(self, _transport, _format):
 
851
        super(BzrDirMeta1, self).__init__(_transport, _format)
 
852
        self.control_files = lockable_files.LockableFiles(
 
853
            self.control_transport, self._format._lock_file_name,
 
854
            self._format._lock_class)
 
855
 
1144
856
    def can_convert_format(self):
1145
857
        """See BzrDir.can_convert_format()."""
1146
858
        return True
1147
859
 
1148
860
    def create_branch(self, name=None, repository=None,
1149
861
            append_revisions_only=None):
1150
 
        """See BzrDir.create_branch."""
 
862
        """See ControlDir.create_branch."""
 
863
        if name is None:
 
864
            name = self._get_selected_branch()
1151
865
        return self._format.get_branch_format().initialize(self, name=name,
1152
866
                repository=repository,
1153
867
                append_revisions_only=append_revisions_only)
1154
868
 
1155
869
    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')
 
870
        """See ControlDir.destroy_branch."""
 
871
        if name is None:
 
872
            name = self._get_selected_branch()
 
873
        path = self._get_branch_path(name)
 
874
        if name != "":
 
875
            self.control_files.lock_write()
 
876
            try:
 
877
                branches = self._read_branch_list()
 
878
                try:
 
879
                    branches.remove(name.encode("utf-8"))
 
880
                except ValueError:
 
881
                    raise errors.NotBranchError(name)
 
882
                self._write_branch_list(branches)
 
883
            finally:
 
884
                self.control_files.unlock()
 
885
        try:
 
886
            self.transport.delete_tree(path)
 
887
        except errors.NoSuchFile:
 
888
            raise errors.NotBranchError(path=urlutils.join(self.transport.base,
 
889
                path), bzrdir=self)
1160
890
 
1161
891
    def create_repository(self, shared=False):
1162
892
        """See BzrDir.create_repository."""
1164
894
 
1165
895
    def destroy_repository(self):
1166
896
        """See BzrDir.destroy_repository."""
1167
 
        self.transport.delete_tree('repository')
 
897
        try:
 
898
            self.transport.delete_tree('repository')
 
899
        except errors.NoSuchFile:
 
900
            raise errors.NoRepositoryPresent(self)
1168
901
 
1169
902
    def create_workingtree(self, revision_id=None, from_branch=None,
1170
903
                           accelerator_tree=None, hardlink=False):
1192
925
 
1193
926
        This might be a synthetic object for e.g. RemoteBranch and SVN.
1194
927
        """
1195
 
        from bzrlib.branch import BranchFormat
1196
 
        return BranchFormat.find_format(self, name=name)
 
928
        from bzrlib.branch import BranchFormatMetadir
 
929
        return BranchFormatMetadir.find_format(self, name=name)
1197
930
 
1198
931
    def _get_mkdir_mode(self):
1199
932
        """Figure out the mode to use when creating a bzrdir subdir."""
1203
936
 
1204
937
    def get_branch_reference(self, name=None):
1205
938
        """See BzrDir.get_branch_reference()."""
1206
 
        from bzrlib.branch import BranchFormat
1207
 
        format = BranchFormat.find_format(self, name=name)
 
939
        from bzrlib.branch import BranchFormatMetadir
 
940
        format = BranchFormatMetadir.find_format(self, name=name)
1208
941
        return format.get_reference(self, name=name)
1209
942
 
 
943
    def set_branch_reference(self, target_branch, name=None):
 
944
        format = _mod_branch.BranchReferenceFormat()
 
945
        return format.initialize(self, target_branch=target_branch, name=name)
 
946
 
1210
947
    def get_branch_transport(self, branch_format, name=None):
1211
948
        """See BzrDir.get_branch_transport()."""
1212
 
        if name is not None:
1213
 
            raise errors.NoColocatedBranchSupport(self)
 
949
        if name is None:
 
950
            name = self._get_selected_branch()
 
951
        path = self._get_branch_path(name)
1214
952
        # XXX: this shouldn't implicitly create the directory if it's just
1215
953
        # promising to get a transport -- mbp 20090727
1216
954
        if branch_format is None:
1217
 
            return self.transport.clone('branch')
 
955
            return self.transport.clone(path)
1218
956
        try:
1219
957
            branch_format.get_format_string()
1220
958
        except NotImplementedError:
1221
959
            raise errors.IncompatibleFormat(branch_format, self._format)
 
960
        if name != "":
 
961
            branches = self._read_branch_list()
 
962
            utf8_name = name.encode("utf-8")
 
963
            if not utf8_name in branches:
 
964
                self.control_files.lock_write()
 
965
                try:
 
966
                    branches = self._read_branch_list()
 
967
                    dirname = urlutils.dirname(utf8_name)
 
968
                    if dirname != "" and dirname in branches:
 
969
                        raise errors.ParentBranchExists(name)
 
970
                    child_branches = [
 
971
                        b.startswith(utf8_name+"/") for b in branches]
 
972
                    if any(child_branches):
 
973
                        raise errors.AlreadyBranchError(name)
 
974
                    branches.append(utf8_name)
 
975
                    self._write_branch_list(branches)
 
976
                finally:
 
977
                    self.control_files.unlock()
 
978
        branch_transport = self.transport.clone(path)
 
979
        mode = self._get_mkdir_mode()
 
980
        branch_transport.create_prefix(mode=mode)
1222
981
        try:
1223
 
            self.transport.mkdir('branch', mode=self._get_mkdir_mode())
 
982
            self.transport.mkdir(path, mode=mode)
1224
983
        except errors.FileExists:
1225
984
            pass
1226
 
        return self.transport.clone('branch')
 
985
        return self.transport.clone(path)
1227
986
 
1228
987
    def get_repository_transport(self, repository_format):
1229
988
        """See BzrDir.get_repository_transport()."""
1253
1012
            pass
1254
1013
        return self.transport.clone('checkout')
1255
1014
 
 
1015
    def get_branches(self):
 
1016
        """See ControlDir.get_branches."""
 
1017
        ret = {}
 
1018
        try:
 
1019
            ret[""] = self.open_branch(name="")
 
1020
        except (errors.NotBranchError, errors.NoRepositoryPresent):
 
1021
            pass
 
1022
 
 
1023
        for name in self._read_branch_list():
 
1024
            ret[name] = self.open_branch(name=name.decode('utf-8'))
 
1025
 
 
1026
        return ret
 
1027
 
1256
1028
    def has_workingtree(self):
1257
1029
        """Tell if this bzrdir contains a working tree.
1258
1030
 
1259
1031
        Note: if you're going to open the working tree, you should just go
1260
1032
        ahead and try, and not ask permission first.
1261
1033
        """
1262
 
        from bzrlib.workingtree import WorkingTreeFormat
 
1034
        from bzrlib.workingtree import WorkingTreeFormatMetaDir
1263
1035
        try:
1264
 
            WorkingTreeFormat.find_format_string(self)
 
1036
            WorkingTreeFormatMetaDir.find_format_string(self)
1265
1037
        except errors.NoWorkingTree:
1266
1038
            return False
1267
1039
        return True
1268
1040
 
1269
1041
    def needs_format_conversion(self, format):
1270
1042
        """See BzrDir.needs_format_conversion()."""
1271
 
        if not isinstance(self._format, format.__class__):
 
1043
        if (not isinstance(self._format, format.__class__) or
 
1044
            self._format.get_format_string() != format.get_format_string()):
1272
1045
            # it is not a meta dir format, conversion is needed.
1273
1046
            return True
1274
1047
        # we might want to push this down to the repository?
1295
1068
        return False
1296
1069
 
1297
1070
    def open_branch(self, name=None, unsupported=False,
1298
 
                    ignore_fallbacks=False):
1299
 
        """See BzrDir.open_branch."""
 
1071
                    ignore_fallbacks=False, possible_transports=None):
 
1072
        """See ControlDir.open_branch."""
 
1073
        if name is None:
 
1074
            name = self._get_selected_branch()
1300
1075
        format = self.find_branch_format(name=name)
1301
1076
        format.check_support_status(unsupported)
1302
1077
        return format.open(self, name=name,
1303
 
            _found=True, ignore_fallbacks=ignore_fallbacks)
 
1078
            _found=True, ignore_fallbacks=ignore_fallbacks,
 
1079
            possible_transports=possible_transports)
1304
1080
 
1305
1081
    def open_repository(self, unsupported=False):
1306
1082
        """See BzrDir.open_repository."""
1307
 
        from bzrlib.repository import RepositoryFormat
1308
 
        format = RepositoryFormat.find_format(self)
 
1083
        from bzrlib.repository import RepositoryFormatMetaDir
 
1084
        format = RepositoryFormatMetaDir.find_format(self)
1309
1085
        format.check_support_status(unsupported)
1310
1086
        return format.open(self, _found=True)
1311
1087
 
1312
1088
    def open_workingtree(self, unsupported=False,
1313
1089
            recommend_upgrade=True):
1314
1090
        """See BzrDir.open_workingtree."""
1315
 
        from bzrlib.workingtree import WorkingTreeFormat
1316
 
        format = WorkingTreeFormat.find_format(self)
 
1091
        from bzrlib.workingtree import WorkingTreeFormatMetaDir
 
1092
        format = WorkingTreeFormatMetaDir.find_format(self)
1317
1093
        format.check_support_status(unsupported, recommend_upgrade,
1318
1094
            basedir=self.root_transport.base)
1319
1095
        return format.open(self, _found=True)
1322
1098
        return config.TransportConfig(self.transport, 'control.conf')
1323
1099
 
1324
1100
 
 
1101
class BzrFormat(object):
 
1102
    """Base class for all formats of things living in metadirs.
 
1103
 
 
1104
    This class manages the format string that is stored in the 'format'
 
1105
    or 'branch-format' file.
 
1106
 
 
1107
    All classes for (branch-, repository-, workingtree-) formats that
 
1108
    live in meta directories and have their own 'format' file
 
1109
    (i.e. different from .bzr/branch-format) derive from this class,
 
1110
    as well as the relevant base class for their kind
 
1111
    (BranchFormat, WorkingTreeFormat, RepositoryFormat).
 
1112
 
 
1113
    Each format is identified by a "format" or "branch-format" file with a
 
1114
    single line containing the base format name and then an optional list of
 
1115
    feature flags.
 
1116
 
 
1117
    Feature flags are supported as of bzr 2.5. Setting feature flags on formats
 
1118
    will render them inaccessible to older versions of bzr.
 
1119
 
 
1120
    :ivar features: Dictionary mapping feature names to their necessity
 
1121
    """
 
1122
 
 
1123
    _present_features = set()
 
1124
 
 
1125
    def __init__(self):
 
1126
        self.features = {}
 
1127
 
 
1128
    @classmethod
 
1129
    def register_feature(cls, name):
 
1130
        """Register a feature as being present.
 
1131
 
 
1132
        :param name: Name of the feature
 
1133
        """
 
1134
        if " " in name:
 
1135
            raise ValueError("spaces are not allowed in feature names")
 
1136
        if name in cls._present_features:
 
1137
            raise errors.FeatureAlreadyRegistered(name)
 
1138
        cls._present_features.add(name)
 
1139
 
 
1140
    @classmethod
 
1141
    def unregister_feature(cls, name):
 
1142
        """Unregister a feature."""
 
1143
        cls._present_features.remove(name)
 
1144
 
 
1145
    def check_support_status(self, allow_unsupported, recommend_upgrade=True,
 
1146
            basedir=None):
 
1147
        for name, necessity in self.features.iteritems():
 
1148
            if name in self._present_features:
 
1149
                continue
 
1150
            if necessity == "optional":
 
1151
                mutter("ignoring optional missing feature %s", name)
 
1152
                continue
 
1153
            elif necessity == "required":
 
1154
                raise errors.MissingFeature(name)
 
1155
            else:
 
1156
                mutter("treating unknown necessity as require for %s",
 
1157
                       name)
 
1158
                raise errors.MissingFeature(name)
 
1159
 
 
1160
    @classmethod
 
1161
    def get_format_string(cls):
 
1162
        """Return the ASCII format string that identifies this format."""
 
1163
        raise NotImplementedError(cls.get_format_string)
 
1164
 
 
1165
    @classmethod
 
1166
    def from_string(cls, text):
 
1167
        format_string = cls.get_format_string()
 
1168
        if not text.startswith(format_string):
 
1169
            raise AssertionError("Invalid format header %r for %r" % (text, cls))
 
1170
        lines = text[len(format_string):].splitlines()
 
1171
        ret = cls()
 
1172
        for lineno, line in enumerate(lines):
 
1173
            try:
 
1174
                (necessity, feature) = line.split(" ", 1)
 
1175
            except ValueError:
 
1176
                raise errors.ParseFormatError(format=cls, lineno=lineno+2,
 
1177
                    line=line, text=text)
 
1178
            ret.features[feature] = necessity
 
1179
        return ret
 
1180
 
 
1181
    def as_string(self):
 
1182
        """Return the string representation of this format.
 
1183
        """
 
1184
        lines = [self.get_format_string()]
 
1185
        lines.extend([("%s %s\n" % (item[1], item[0])) for item in
 
1186
            self.features.iteritems()])
 
1187
        return "".join(lines)
 
1188
 
 
1189
    @classmethod
 
1190
    def _find_format(klass, registry, kind, format_string):
 
1191
        try:
 
1192
            first_line = format_string[:format_string.index("\n")+1]
 
1193
        except ValueError:
 
1194
            first_line = format_string
 
1195
        try:
 
1196
            cls = registry.get(first_line)
 
1197
        except KeyError:
 
1198
            raise errors.UnknownFormatError(format=first_line, kind=kind)
 
1199
        return cls.from_string(format_string)
 
1200
 
 
1201
    def network_name(self):
 
1202
        """A simple byte string uniquely identifying this format for RPC calls.
 
1203
 
 
1204
        Metadir branch formats use their format string.
 
1205
        """
 
1206
        return self.as_string()
 
1207
 
 
1208
    def __eq__(self, other):
 
1209
        return (self.__class__ is other.__class__ and
 
1210
                self.features == other.features)
 
1211
 
 
1212
    def _update_feature_flags(self, updated_flags):
 
1213
        """Update the feature flags in this format.
 
1214
 
 
1215
        :param updated_flags: Updated feature flags
 
1216
        """
 
1217
        for name, necessity in updated_flags.iteritems():
 
1218
            if necessity is None:
 
1219
                try:
 
1220
                    del self.features[name]
 
1221
                except KeyError:
 
1222
                    pass
 
1223
            else:
 
1224
                self.features[name] = necessity
 
1225
 
 
1226
 
1325
1227
class BzrProber(controldir.Prober):
1326
1228
    """Prober for formats that use a .bzr/ control directory."""
1327
1229
 
1329
1231
    """The known .bzr formats."""
1330
1232
 
1331
1233
    @classmethod
1332
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1333
 
    def register_bzrdir_format(klass, format):
1334
 
        klass.formats.register(format.get_format_string(), format)
1335
 
 
1336
 
    @classmethod
1337
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1338
 
    def unregister_bzrdir_format(klass, format):
1339
 
        klass.formats.remove(format.get_format_string())
1340
 
 
1341
 
    @classmethod
1342
1234
    def probe_transport(klass, transport):
1343
1235
        """Return the .bzrdir style format present in a directory."""
1344
1236
        try:
1346
1238
        except errors.NoSuchFile:
1347
1239
            raise errors.NotBranchError(path=transport.base)
1348
1240
        try:
1349
 
            return klass.formats.get(format_string)
 
1241
            first_line = format_string[:format_string.index("\n")+1]
 
1242
        except ValueError:
 
1243
            first_line = format_string
 
1244
        try:
 
1245
            cls = klass.formats.get(first_line)
1350
1246
        except KeyError:
1351
 
            raise errors.UnknownFormatError(format=format_string, kind='bzrdir')
 
1247
            raise errors.UnknownFormatError(format=first_line, kind='bzrdir')
 
1248
        return cls.from_string(format_string)
1352
1249
 
1353
1250
    @classmethod
1354
1251
    def known_formats(cls):
1397
1294
        return set([RemoteBzrDirFormat()])
1398
1295
 
1399
1296
 
1400
 
class BzrDirFormat(controldir.ControlDirFormat):
 
1297
class BzrDirFormat(BzrFormat, controldir.ControlDirFormat):
1401
1298
    """ControlDirFormat base class for .bzr/ directories.
1402
1299
 
1403
1300
    Formats are placed in a dict by their format string for reference
1414
1311
    # _lock_class must be set in subclasses to the lock type, typ.
1415
1312
    # TransportLock or LockDir
1416
1313
 
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
1314
    def initialize_on_transport(self, transport):
1423
1315
        """Initialize a new bzrdir in the base directory of a Transport."""
1424
1316
        try:
1465
1357
        :param shared_repo: Control whether made repositories are shared or
1466
1358
            not.
1467
1359
        :param vfs_only: If True do not attempt to use a smart server
1468
 
        :return: repo, bzrdir, require_stacking, repository_policy. repo is
 
1360
        :return: repo, controldir, require_stacking, repository_policy. repo is
1469
1361
            None if none was created or found, bzrdir is always valid.
1470
1362
            require_stacking is the result of examining the stacked_on
1471
1363
            parameter and any stacking policy found for the target.
1546
1438
        # mode from the root directory
1547
1439
        temp_control = lockable_files.LockableFiles(transport,
1548
1440
                            '', 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)
 
1441
        try:
 
1442
            temp_control._transport.mkdir('.bzr',
 
1443
                # FIXME: RBC 20060121 don't peek under
 
1444
                # the covers
 
1445
                mode=temp_control._dir_mode)
 
1446
        except errors.FileExists:
 
1447
            raise errors.AlreadyControlDirError(transport.base)
1553
1448
        if sys.platform == 'win32' and isinstance(transport, local.LocalTransport):
1554
1449
            win32utils.set_file_attr_hidden(transport._abspath('.bzr'))
1555
1450
        file_mode = temp_control._file_mode
1559
1454
                       "This is a Bazaar control directory.\n"
1560
1455
                       "Do not change any files in this directory.\n"
1561
1456
                       "See http://bazaar.canonical.com/ for more information about Bazaar.\n"),
1562
 
                      ('branch-format', self.get_format_string()),
 
1457
                      ('branch-format', self.as_string()),
1563
1458
                      ]
1564
1459
        # NB: no need to escape relative paths that are url safe.
1565
1460
        control_files = lockable_files.LockableFiles(bzrdir_transport,
1609
1504
            compatible with whatever sub formats are supported by self.
1610
1505
        :return: None.
1611
1506
        """
 
1507
        other_format.features = dict(self.features)
 
1508
 
 
1509
    def supports_transport(self, transport):
 
1510
        # bzr formats can be opened over all known transports
 
1511
        return True
 
1512
 
 
1513
    def check_support_status(self, allow_unsupported, recommend_upgrade=True,
 
1514
            basedir=None):
 
1515
        controldir.ControlDirFormat.check_support_status(self,
 
1516
            allow_unsupported=allow_unsupported, recommend_upgrade=recommend_upgrade,
 
1517
            basedir=basedir)
 
1518
        BzrFormat.check_support_status(self, allow_unsupported=allow_unsupported,
 
1519
            recommend_upgrade=recommend_upgrade, basedir=basedir)
1612
1520
 
1613
1521
 
1614
1522
class BzrDirMetaFormat1(BzrDirFormat):
1628
1536
 
1629
1537
    fixed_components = False
1630
1538
 
 
1539
    colocated_branches = True
 
1540
 
1631
1541
    def __init__(self):
 
1542
        BzrDirFormat.__init__(self)
1632
1543
        self._workingtree_format = None
1633
1544
        self._branch_format = None
1634
1545
        self._repository_format = None
1640
1551
            return False
1641
1552
        if other.workingtree_format != self.workingtree_format:
1642
1553
            return False
 
1554
        if other.features != self.features:
 
1555
            return False
1643
1556
        return True
1644
1557
 
1645
1558
    def __ne__(self, other):
1723
1636
                    new_repo_format = None
1724
1637
            if new_repo_format is not None:
1725
1638
                self.repository_format = new_repo_format
1726
 
                note('Source repository format does not support stacking,'
1727
 
                     ' using format:\n  %s',
 
1639
                note(gettext('Source repository format does not support stacking,'
 
1640
                     ' using format:\n  %s'),
1728
1641
                     new_repo_format.get_format_description())
1729
1642
 
1730
1643
        if not self.get_branch_format().supports_stacking():
1743
1656
            if new_branch_format is not None:
1744
1657
                # Does support stacking, use its format.
1745
1658
                self.set_branch_format(new_branch_format)
1746
 
                note('Source branch format does not support stacking,'
1747
 
                     ' using format:\n  %s',
 
1659
                note(gettext('Source branch format does not support stacking,'
 
1660
                     ' using format:\n  %s'),
1748
1661
                     new_branch_format.get_format_description())
1749
1662
 
1750
1663
    def get_converter(self, format=None):
1751
1664
        """See BzrDirFormat.get_converter()."""
1752
1665
        if format is None:
1753
1666
            format = BzrDirFormat.get_default_format()
 
1667
        if (type(self) is BzrDirMetaFormat1 and
 
1668
            type(format) is BzrDirMetaFormat1Colo):
 
1669
            return ConvertMetaToColo(format)
 
1670
        if (type(self) is BzrDirMetaFormat1Colo and
 
1671
            type(format) is BzrDirMetaFormat1):
 
1672
            return ConvertMetaToColo(format)
1754
1673
        if not isinstance(self, format.__class__):
1755
1674
            # converting away from metadir is not implemented
1756
1675
            raise NotImplementedError(self.get_converter)
1765
1684
        """See BzrDirFormat.get_format_description()."""
1766
1685
        return "Meta directory format 1"
1767
1686
 
1768
 
    def network_name(self):
1769
 
        return self.get_format_string()
1770
 
 
1771
1687
    def _open(self, transport):
1772
1688
        """See BzrDirFormat._open."""
1773
1689
        # Create a new format instance because otherwise initialisation of new
1802
1718
            compatible with whatever sub formats are supported by self.
1803
1719
        :return: None.
1804
1720
        """
 
1721
        super(BzrDirMetaFormat1, self)._supply_sub_formats_to(other_format)
1805
1722
        if getattr(self, '_repository_format', None) is not None:
1806
1723
            other_format.repository_format = self.repository_format
1807
1724
        if self._branch_format is not None:
1820
1737
    def __set_workingtree_format(self, wt_format):
1821
1738
        self._workingtree_format = wt_format
1822
1739
 
 
1740
    def __repr__(self):
 
1741
        return "<%r>" % (self.__class__.__name__,)
 
1742
 
1823
1743
    workingtree_format = property(__get_workingtree_format,
1824
1744
                                  __set_workingtree_format)
1825
1745
 
1830
1750
controldir.ControlDirFormat._default_format = BzrDirMetaFormat1()
1831
1751
 
1832
1752
 
 
1753
class BzrDirMetaFormat1Colo(BzrDirMetaFormat1):
 
1754
    """BzrDirMeta1 format with support for colocated branches."""
 
1755
 
 
1756
    colocated_branches = True
 
1757
 
 
1758
    @classmethod
 
1759
    def get_format_string(cls):
 
1760
        """See BzrDirFormat.get_format_string()."""
 
1761
        return "Bazaar meta directory, format 1 (with colocated branches)\n"
 
1762
 
 
1763
    def get_format_description(self):
 
1764
        """See BzrDirFormat.get_format_description()."""
 
1765
        return "Meta directory format 1 with support for colocated branches"
 
1766
 
 
1767
    def _open(self, transport):
 
1768
        """See BzrDirFormat._open."""
 
1769
        # Create a new format instance because otherwise initialisation of new
 
1770
        # metadirs share the global default format object leading to alias
 
1771
        # problems.
 
1772
        format = BzrDirMetaFormat1Colo()
 
1773
        self._supply_sub_formats_to(format)
 
1774
        return BzrDirMeta1(transport, format)
 
1775
 
 
1776
 
 
1777
BzrProber.formats.register(BzrDirMetaFormat1Colo.get_format_string(),
 
1778
    BzrDirMetaFormat1Colo)
 
1779
 
 
1780
 
1833
1781
class ConvertMetaToMeta(controldir.Converter):
1834
1782
    """Converts the components of metadirs."""
1835
1783
 
1854
1802
        else:
1855
1803
            if not isinstance(repo._format, self.target_format.repository_format.__class__):
1856
1804
                from bzrlib.repository import CopyConverter
1857
 
                ui.ui_factory.note('starting repository conversion')
 
1805
                ui.ui_factory.note(gettext('starting repository conversion'))
1858
1806
                converter = CopyConverter(self.target_format.repository_format)
1859
1807
                converter.convert(repo, pb)
1860
1808
        for branch in self.bzrdir.list_branches():
1864
1812
            old = branch._format.__class__
1865
1813
            new = self.target_format.get_branch_format().__class__
1866
1814
            while old != new:
1867
 
                if (old == _mod_branch.BzrBranchFormat5 and
 
1815
                if (old == fullhistorybranch.BzrBranchFormat5 and
1868
1816
                    new in (_mod_branch.BzrBranchFormat6,
1869
1817
                        _mod_branch.BzrBranchFormat7,
1870
1818
                        _mod_branch.BzrBranchFormat8)):
1908
1856
        return to_convert
1909
1857
 
1910
1858
 
 
1859
class ConvertMetaToColo(controldir.Converter):
 
1860
    """Add colocated branch support."""
 
1861
 
 
1862
    def __init__(self, target_format):
 
1863
        """Create a converter.that upgrades a metadir to the colo format.
 
1864
 
 
1865
        :param target_format: The final metadir format that is desired.
 
1866
        """
 
1867
        self.target_format = target_format
 
1868
 
 
1869
    def convert(self, to_convert, pb):
 
1870
        """See Converter.convert()."""
 
1871
        to_convert.transport.put_bytes('branch-format',
 
1872
            self.target_format.as_string())
 
1873
        return BzrDir.open_from_transport(to_convert.root_transport)
 
1874
 
 
1875
 
 
1876
class ConvertMetaToColo(controldir.Converter):
 
1877
    """Convert a 'development-colo' bzrdir to a '2a' bzrdir."""
 
1878
 
 
1879
    def __init__(self, target_format):
 
1880
        """Create a converter that converts a 'development-colo' metadir
 
1881
        to a '2a' metadir.
 
1882
 
 
1883
        :param target_format: The final metadir format that is desired.
 
1884
        """
 
1885
        self.target_format = target_format
 
1886
 
 
1887
    def convert(self, to_convert, pb):
 
1888
        """See Converter.convert()."""
 
1889
        to_convert.transport.put_bytes('branch-format',
 
1890
            self.target_format.as_string())
 
1891
        return BzrDir.open_from_transport(to_convert.root_transport)
 
1892
 
 
1893
 
1911
1894
controldir.ControlDirFormat.register_server_prober(RemoteBzrProber)
1912
1895
 
1913
1896
 
1990
1973
        else:
1991
1974
            self._require_stacking = True
1992
1975
 
1993
 
    def acquire_repository(self, make_working_trees=None, shared=False):
 
1976
    def acquire_repository(self, make_working_trees=None, shared=False,
 
1977
            possible_transports=None):
1994
1978
        """Acquire a repository for this bzrdir.
1995
1979
 
1996
1980
        Implementations may create a new repository or use a pre-exising
2002
1986
        :return: A repository, is_new_flag (True if the repository was
2003
1987
            created).
2004
1988
        """
2005
 
        raise NotImplemented(RepositoryAcquisitionPolicy.acquire_repository)
 
1989
        raise NotImplementedError(RepositoryAcquisitionPolicy.acquire_repository)
2006
1990
 
2007
1991
 
2008
1992
class CreateRepository(RepositoryAcquisitionPolicy):
2021
2005
                                             require_stacking)
2022
2006
        self._bzrdir = bzrdir
2023
2007
 
2024
 
    def acquire_repository(self, make_working_trees=None, shared=False):
 
2008
    def acquire_repository(self, make_working_trees=None, shared=False,
 
2009
            possible_transports=None):
2025
2010
        """Implementation of RepositoryAcquisitionPolicy.acquire_repository
2026
2011
 
2027
2012
        Creates the desired repository in the bzrdir we already have.
2028
2013
        """
 
2014
        if possible_transports is None:
 
2015
            possible_transports = []
 
2016
        else:
 
2017
            possible_transports = list(possible_transports)
 
2018
        possible_transports.append(self._bzrdir.root_transport)
2029
2019
        stack_on = self._get_full_stack_on()
2030
2020
        if stack_on:
2031
2021
            format = self._bzrdir._format
2032
2022
            format.require_stacking(stack_on=stack_on,
2033
 
                                    possible_transports=[self._bzrdir.root_transport])
 
2023
                                    possible_transports=possible_transports)
2034
2024
            if not self._require_stacking:
2035
2025
                # We have picked up automatic stacking somewhere.
2036
 
                note('Using default stacking branch %s at %s', self._stack_on,
2037
 
                    self._stack_on_pwd)
 
2026
                note(gettext('Using default stacking branch {0} at {1}').format(
 
2027
                    self._stack_on, self._stack_on_pwd))
2038
2028
        repository = self._bzrdir.create_repository(shared=shared)
2039
2029
        self._add_fallback(repository,
2040
 
                           possible_transports=[self._bzrdir.transport])
 
2030
                           possible_transports=possible_transports)
2041
2031
        if make_working_trees is not None:
2042
2032
            repository.set_make_working_trees(make_working_trees)
2043
2033
        return repository, True
2059
2049
                                             require_stacking)
2060
2050
        self._repository = repository
2061
2051
 
2062
 
    def acquire_repository(self, make_working_trees=None, shared=False):
 
2052
    def acquire_repository(self, make_working_trees=None, shared=False,
 
2053
            possible_transports=None):
2063
2054
        """Implementation of RepositoryAcquisitionPolicy.acquire_repository
2064
2055
 
2065
2056
        Returns an existing repository to use.
2066
2057
        """
 
2058
        if possible_transports is None:
 
2059
            possible_transports = []
 
2060
        else:
 
2061
            possible_transports = list(possible_transports)
 
2062
        possible_transports.append(self._repository.bzrdir.transport)
2067
2063
        self._add_fallback(self._repository,
2068
 
                       possible_transports=[self._repository.bzrdir.transport])
 
2064
                       possible_transports=possible_transports)
2069
2065
        return self._repository, False
2070
2066
 
2071
2067
 
2075
2071
         tree_format=None,
2076
2072
         hidden=False,
2077
2073
         experimental=False,
2078
 
         alias=False):
 
2074
         alias=False, bzrdir_format=None):
2079
2075
    """Register a metadir subformat.
2080
2076
 
2081
 
    These all use a BzrDirMetaFormat1 bzrdir, but can be parameterized
2082
 
    by the Repository/Branch/WorkingTreeformats.
 
2077
    These all use a meta bzrdir, but can be parameterized by the
 
2078
    Repository/Branch/WorkingTreeformats.
2083
2079
 
2084
2080
    :param repository_format: The fully-qualified repository format class
2085
2081
        name as a string.
2088
2084
    :param tree_format: Fully-qualified tree format class name as
2089
2085
        a string.
2090
2086
    """
 
2087
    if bzrdir_format is None:
 
2088
        bzrdir_format = BzrDirMetaFormat1
2091
2089
    # This should be expanded to support setting WorkingTree and Branch
2092
 
    # formats, once BzrDirMetaFormat1 supports that.
 
2090
    # formats, once the API supports that.
2093
2091
    def _load(full_name):
2094
2092
        mod_name, factory_name = full_name.rsplit('.', 1)
2095
2093
        try:
2102
2100
        return factory()
2103
2101
 
2104
2102
    def helper():
2105
 
        bd = BzrDirMetaFormat1()
 
2103
        bd = bzrdir_format()
2106
2104
        if branch_format is not None:
2107
2105
            bd.set_branch_format(_load(branch_format))
2108
2106
        if tree_format is not None:
2116
2114
register_metadir(controldir.format_registry, 'knit',
2117
2115
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
2118
2116
    'Format using knits.  Recommended for interoperation with bzr <= 0.14.',
2119
 
    branch_format='bzrlib.branch.BzrBranchFormat5',
 
2117
    branch_format='bzrlib.branchfmt.fullhistory.BzrBranchFormat5',
2120
2118
    tree_format='bzrlib.workingtree_3.WorkingTreeFormat3',
2121
2119
    hidden=True,
2122
2120
    deprecated=True)
2123
2121
register_metadir(controldir.format_registry, 'dirstate',
2124
2122
    '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.',
2127
 
    branch_format='bzrlib.branch.BzrBranchFormat5',
 
2123
    help='Format using dirstate for working trees. '
 
2124
        'Compatible with bzr 0.8 and '
 
2125
        'above when accessed over the network. Introduced in bzr 0.15.',
 
2126
    branch_format='bzrlib.branchfmt.fullhistory.BzrBranchFormat5',
2128
2127
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2129
2128
    hidden=True,
2130
2129
    deprecated=True)
2131
2130
register_metadir(controldir.format_registry, 'dirstate-tags',
2132
2131
    '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.',
 
2132
    help='Variant of dirstate with support for tags. '
 
2133
        'Introduced in bzr 0.15.',
2136
2134
    branch_format='bzrlib.branch.BzrBranchFormat6',
2137
2135
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2138
2136
    hidden=True,
2139
2137
    deprecated=True)
2140
2138
register_metadir(controldir.format_registry, 'rich-root',
2141
2139
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit4',
2142
 
    help='New in 1.0.  Better handling of tree roots.  Incompatible with'
2143
 
        ' bzr < 1.0.',
 
2140
    help='Variant of dirstate with better handling of tree roots. '
 
2141
        'Introduced in bzr 1.0',
2144
2142
    branch_format='bzrlib.branch.BzrBranchFormat6',
2145
2143
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2146
2144
    hidden=True,
2147
2145
    deprecated=True)
2148
2146
register_metadir(controldir.format_registry, 'dirstate-with-subtree',
2149
2147
    '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.',
 
2148
    help='Variant of dirstate with support for nested trees. '
 
2149
         'Introduced in 0.15.',
2153
2150
    branch_format='bzrlib.branch.BzrBranchFormat6',
2154
2151
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2155
2152
    experimental=True,
2157
2154
    )
2158
2155
register_metadir(controldir.format_registry, 'pack-0.92',
2159
2156
    '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. '
 
2157
    help='Pack-based format used in 1.x series. Introduced in 0.92. '
 
2158
        'Interoperates with bzr repositories before 0.92 but cannot be '
 
2159
        'read by bzr < 0.92. '
2163
2160
        ,
2164
2161
    branch_format='bzrlib.branch.BzrBranchFormat6',
2165
2162
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
 
2163
    deprecated=True,
2166
2164
    )
2167
2165
register_metadir(controldir.format_registry, 'pack-0.92-subtree',
2168
2166
    '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 '
 
2167
    help='Pack-based format used in 1.x series, with subtree support. '
 
2168
        'Introduced in 0.92. Interoperates with '
2171
2169
        'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
2172
2170
        ,
2173
2171
    branch_format='bzrlib.branch.BzrBranchFormat6',
2174
2172
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2175
2173
    hidden=True,
 
2174
    deprecated=True,
2176
2175
    experimental=True,
2177
2176
    )
2178
2177
register_metadir(controldir.format_registry, 'rich-root-pack',
2179
2178
    '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).',
 
2179
    help='A variant of pack-0.92 that supports rich-root data '
 
2180
         '(needed for bzr-svn and bzr-git). Introduced in 1.0.',
2182
2181
    branch_format='bzrlib.branch.BzrBranchFormat6',
2183
2182
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2184
2183
    hidden=True,
 
2184
    deprecated=True,
2185
2185
    )
2186
2186
register_metadir(controldir.format_registry, '1.6',
2187
2187
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack5',
2191
2191
    branch_format='bzrlib.branch.BzrBranchFormat7',
2192
2192
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2193
2193
    hidden=True,
 
2194
    deprecated=True,
2194
2195
    )
2195
2196
register_metadir(controldir.format_registry, '1.6.1-rich-root',
2196
2197
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack5RichRoot',
2199
2200
    branch_format='bzrlib.branch.BzrBranchFormat7',
2200
2201
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2201
2202
    hidden=True,
 
2203
    deprecated=True,
2202
2204
    )
2203
2205
register_metadir(controldir.format_registry, '1.9',
2204
2206
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack6',
2208
2210
    branch_format='bzrlib.branch.BzrBranchFormat7',
2209
2211
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2210
2212
    hidden=True,
 
2213
    deprecated=True,
2211
2214
    )
2212
2215
register_metadir(controldir.format_registry, '1.9-rich-root',
2213
2216
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack6RichRoot',
2216
2219
    branch_format='bzrlib.branch.BzrBranchFormat7',
2217
2220
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2218
2221
    hidden=True,
 
2222
    deprecated=True,
2219
2223
    )
2220
2224
register_metadir(controldir.format_registry, '1.14',
2221
2225
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack6',
2222
2226
    help='A working-tree format that supports content filtering.',
2223
2227
    branch_format='bzrlib.branch.BzrBranchFormat7',
2224
2228
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat5',
 
2229
    hidden=True,
 
2230
    deprecated=True,
2225
2231
    )
2226
2232
register_metadir(controldir.format_registry, '1.14-rich-root',
2227
2233
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack6RichRoot',
2229
2235
         '(needed for bzr-svn and bzr-git).',
2230
2236
    branch_format='bzrlib.branch.BzrBranchFormat7',
2231
2237
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat5',
 
2238
    hidden=True,
 
2239
    deprecated=True,
2232
2240
    )
2233
2241
# The following un-numbered 'development' formats should always just be aliases.
2234
2242
register_metadir(controldir.format_registry, 'development-subtree',
2262
2270
    alias=False,
2263
2271
    )
2264
2272
 
 
2273
register_metadir(controldir.format_registry, 'development-colo',
 
2274
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2a',
 
2275
    help='The 2a format with experimental support for colocated branches.\n',
 
2276
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
2277
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat6',
 
2278
    experimental=True,
 
2279
    bzrdir_format=BzrDirMetaFormat1Colo,
 
2280
    )
 
2281
 
 
2282
 
2265
2283
# And the development formats above will have aliased one of the following:
2266
2284
 
2267
2285
# Finally, the current format.
2268
2286
register_metadir(controldir.format_registry, '2a',
2269
2287
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2a',
2270
 
    help='First format for bzr 2.0 series.\n'
 
2288
    help='Format for the bzr 2.0 series.\n'
2271
2289
        'Uses group-compress storage.\n'
2272
2290
        'Provides rich roots which are a one-way transition.\n',
2273
2291
        # 'storage in packs, 255-way hashed CHK inventory, bencode revision, group compress, '