~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

  • Committer: Patch Queue Manager
  • Date: 2012-03-28 16:13:49 UTC
  • mfrom: (6499.2.3 948339-config-caching)
  • Revision ID: pqm@pqm.ubuntu.com-20120328161349-2gsc0g11fcu43hlc
(vila) Properly share mutable config sections and save the branch config
 only during the final unlock (Vincent Ladeuil)

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