~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2011-05-11 15:04:23 UTC
  • mfrom: (5848.1.1 2.4-cython-first)
  • Revision ID: pqm@pqm.ubuntu.com-20110511150423-tpm1ablukqalkvim
(jameinel) Default to using Cython for compiling code,
 rather than Pyrex. (John A Meinel)

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
 
 
30
28
import sys
31
29
 
32
30
from bzrlib.lazy_import import lazy_import
35
33
from bzrlib import (
36
34
    branch as _mod_branch,
37
35
    cleanup,
 
36
    config,
 
37
    controldir,
38
38
    errors,
39
39
    fetch,
40
40
    graph,
48
48
    transport as _mod_transport,
49
49
    ui,
50
50
    urlutils,
51
 
    vf_search,
52
51
    win32utils,
53
52
    workingtree_3,
54
53
    workingtree_4,
55
54
    )
56
 
from bzrlib.branchfmt import fullhistory as fullhistorybranch
57
55
from bzrlib.repofmt import knitpack_repo
58
56
from bzrlib.transport import (
59
57
    do_catching_redirections,
60
58
    local,
61
59
    )
62
 
from bzrlib.i18n import gettext
63
60
""")
64
61
 
65
62
from bzrlib.trace import (
68
65
    )
69
66
 
70
67
from bzrlib import (
71
 
    config,
72
 
    controldir,
 
68
    hooks,
73
69
    registry,
74
70
    )
75
71
from bzrlib.symbol_versioning import (
204
200
                if (result_repo.user_url == result.user_url
205
201
                    and not require_stacking and
206
202
                    revision_id is not None):
207
 
                    fetch_spec = vf_search.PendingAncestryResult(
 
203
                    fetch_spec = graph.PendingAncestryResult(
208
204
                        [revision_id], local_repo)
209
205
                    result_repo.fetch(local_repo, fetch_spec=fetch_spec)
210
206
                else:
225
221
            # the tree and fail.
226
222
            result.root_transport.local_abspath('.')
227
223
            if result_repo is None or result_repo.make_working_trees():
228
 
                self.open_workingtree().clone(result, revision_id=revision_id)
 
224
                self.open_workingtree().clone(result)
229
225
        except (errors.NoWorkingTree, errors.NotLocalUrl):
230
226
            pass
231
227
        return result
236
232
        t = _mod_transport.get_transport(url)
237
233
        t.ensure_base()
238
234
 
 
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
        :param evaluate: An optional callable that yields recurse, value,
 
243
            where recurse controls whether this bzrdir is recursed into
 
244
            and value is the value to yield.  By default, all bzrdirs
 
245
            are recursed into, and the return value is the bzrdir.
 
246
        :param list_current: if supplied, use this function to list the current
 
247
            directory, instead of Transport.list_dir
 
248
        :return: a generator of found bzrdirs, or whatever evaluate returns.
 
249
        """
 
250
        if list_current is None:
 
251
            def list_current(transport):
 
252
                return transport.list_dir('')
 
253
        if evaluate is None:
 
254
            def evaluate(bzrdir):
 
255
                return True, bzrdir
 
256
 
 
257
        pending = [transport]
 
258
        while len(pending) > 0:
 
259
            current_transport = pending.pop()
 
260
            recurse = True
 
261
            try:
 
262
                bzrdir = BzrDir.open_from_transport(current_transport)
 
263
            except (errors.NotBranchError, errors.PermissionDenied):
 
264
                pass
 
265
            else:
 
266
                recurse, value = evaluate(bzrdir)
 
267
                yield value
 
268
            try:
 
269
                subdirs = list_current(current_transport)
 
270
            except (errors.NoSuchFile, errors.PermissionDenied):
 
271
                continue
 
272
            if recurse:
 
273
                for subdir in sorted(subdirs, reverse=True):
 
274
                    pending.append(current_transport.clone(subdir))
 
275
 
 
276
    @staticmethod
 
277
    def find_branches(transport):
 
278
        """Find all branches under a transport.
 
279
 
 
280
        This will find all branches below the transport, including branches
 
281
        inside other branches.  Where possible, it will use
 
282
        Repository.find_branches.
 
283
 
 
284
        To list all the branches that use a particular Repository, see
 
285
        Repository.find_branches
 
286
        """
 
287
        def evaluate(bzrdir):
 
288
            try:
 
289
                repository = bzrdir.open_repository()
 
290
            except errors.NoRepositoryPresent:
 
291
                pass
 
292
            else:
 
293
                return False, ([], repository)
 
294
            return True, (bzrdir.list_branches(), None)
 
295
        ret = []
 
296
        for branches, repo in BzrDir.find_bzrdirs(transport,
 
297
                                                  evaluate=evaluate):
 
298
            if repo is not None:
 
299
                ret.extend(repo.find_branches())
 
300
            if branches is not None:
 
301
                ret.extend(branches)
 
302
        return ret
 
303
 
 
304
    @staticmethod
 
305
    def create_branch_and_repo(base, force_new_repo=False, format=None):
 
306
        """Create a new BzrDir, Branch and Repository at the url 'base'.
 
307
 
 
308
        This will use the current default BzrDirFormat unless one is
 
309
        specified, and use whatever
 
310
        repository format that that uses via bzrdir.create_branch and
 
311
        create_repository. If a shared repository is available that is used
 
312
        preferentially.
 
313
 
 
314
        The created Branch object is returned.
 
315
 
 
316
        :param base: The URL to create the branch at.
 
317
        :param force_new_repo: If True a new repository is always created.
 
318
        :param format: If supplied, the format of branch to create.  If not
 
319
            supplied, the default is used.
 
320
        """
 
321
        bzrdir = BzrDir.create(base, format)
 
322
        bzrdir._find_or_create_repository(force_new_repo)
 
323
        return bzrdir.create_branch()
 
324
 
239
325
    def determine_repository_policy(self, force_new_repo=False, stack_on=None,
240
326
                                    stack_on_pwd=None, require_stacking=False):
241
327
        """Return an object representing a policy to use.
345
431
 
346
432
        if revision_id is not None, then the clone operation may tune
347
433
            itself to download less data.
348
 
 
349
434
        :param accelerator_tree: A tree which can be used for retrieving file
350
435
            contents more quickly than the revision tree, i.e. a workingtree.
351
436
            The revision tree will be used for cases where accelerator_tree's
356
441
            location of this control directory.
357
442
        :param create_tree_if_local: If true, a working-tree will be created
358
443
            when working locally.
359
 
        :return: The created control directory
360
444
        """
361
445
        operation = cleanup.OperationWithCleanups(self._sprout)
362
446
        return operation.run(url, revision_id=revision_id,
375
459
        if revision_id is not None:
376
460
            fetch_spec_factory.add_revision_ids([revision_id])
377
461
            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]
383
462
        target_transport = _mod_transport.get_transport(url,
384
463
            possible_transports)
385
464
        target_transport.ensure_base()
386
465
        cloning_format = self.cloning_metadir(stacked)
387
466
        # Create/update the result branch
388
 
        try:
389
 
            result = controldir.ControlDir.open_from_transport(target_transport)
390
 
        except errors.NotBranchError:
391
 
            result = cloning_format.initialize_on_transport(target_transport)
 
467
        result = cloning_format.initialize_on_transport(target_transport)
392
468
        source_branch, source_repository = self._find_source_repo(
393
469
            add_cleanup, source_branch)
394
470
        fetch_spec_factory.source_branch = source_branch
400
476
            stacked_branch_url = None
401
477
        repository_policy = result.determine_repository_policy(
402
478
            force_new_repo, stacked_branch_url, require_stacking=stacked)
403
 
        result_repo, is_new_repo = repository_policy.acquire_repository(
404
 
            possible_transports=possible_transports)
 
479
        result_repo, is_new_repo = repository_policy.acquire_repository()
405
480
        add_cleanup(result_repo.lock_write().unlock)
406
481
        fetch_spec_factory.source_repo = source_repository
407
482
        fetch_spec_factory.target_repo = result_repo
428
503
        mutter("created new branch %r" % (result_branch,))
429
504
 
430
505
        # Create/update the result working tree
431
 
        if (create_tree_if_local and not result.has_workingtree() and
 
506
        if (create_tree_if_local and
432
507
            isinstance(target_transport, local.LocalTransport) and
433
508
            (result_repo is None or result_repo.make_working_trees())):
434
509
            wt = result.create_workingtree(accelerator_tree=accelerator_tree,
466
541
                    stacked=stacked)
467
542
        return result
468
543
 
 
544
 
 
545
 
 
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
 
469
617
    def _available_backup_name(self, base):
470
618
        """Find a non-existing backup file name based on base.
471
619
 
484
632
            old_path = self.root_transport.abspath('.bzr')
485
633
            backup_dir = self._available_backup_name('backup.bzr')
486
634
            new_path = self.root_transport.abspath(backup_dir)
487
 
            ui.ui_factory.note(gettext('making backup of {0}\n  to {1}').format(
488
 
                urlutils.unescape_for_display(old_path, 'utf-8'),
489
 
                urlutils.unescape_for_display(new_path, 'utf-8')))
 
635
            ui.ui_factory.note('making backup of %s\n  to %s'
 
636
                               % (old_path, new_path,))
490
637
            self.root_transport.copy_tree('.bzr', backup_dir)
491
638
            return (old_path, new_path)
492
639
        finally:
507
654
            try:
508
655
                to_path = '.bzr.retired.%d' % i
509
656
                self.root_transport.rename('.bzr', to_path)
510
 
                note(gettext("renamed {0} to {1}").format(
511
 
                    self.root_transport.abspath('.bzr'), to_path))
 
657
                note("renamed %s to %s"
 
658
                    % (self.root_transport.abspath('.bzr'), to_path))
512
659
                return
513
660
            except (errors.TransportError, IOError, errors.PathError):
514
661
                i += 1
541
688
                return None
542
689
            # find the next containing bzrdir
543
690
            try:
544
 
                found_bzrdir = self.open_containing_from_transport(
 
691
                found_bzrdir = BzrDir.open_containing_from_transport(
545
692
                    next_transport)[0]
546
693
            except errors.NotBranchError:
547
694
                return None
664
811
        # add new tests for it to the appropriate place.
665
812
        return filename == '.bzr' or filename.startswith('.bzr/')
666
813
 
 
814
    @staticmethod
 
815
    def open_unsupported(base):
 
816
        """Open a branch which is not supported."""
 
817
        return BzrDir.open(base, _unsupported=True)
 
818
 
 
819
    @staticmethod
 
820
    def open(base, _unsupported=False, possible_transports=None):
 
821
        """Open an existing bzrdir, rooted at 'base' (url).
 
822
 
 
823
        :param _unsupported: a private parameter to the BzrDir class.
 
824
        """
 
825
        t = _mod_transport.get_transport(base, possible_transports)
 
826
        return BzrDir.open_from_transport(t, _unsupported=_unsupported)
 
827
 
 
828
    @staticmethod
 
829
    def open_from_transport(transport, _unsupported=False,
 
830
                            _server_formats=True):
 
831
        """Open a bzrdir within a particular directory.
 
832
 
 
833
        :param transport: Transport containing the bzrdir.
 
834
        :param _unsupported: private.
 
835
        """
 
836
        for hook in BzrDir.hooks['pre_open']:
 
837
            hook(transport)
 
838
        # Keep initial base since 'transport' may be modified while following
 
839
        # the redirections.
 
840
        base = transport.base
 
841
        def find_format(transport):
 
842
            return transport, controldir.ControlDirFormat.find_format(
 
843
                transport, _server_formats=_server_formats)
 
844
 
 
845
        def redirected(transport, e, redirection_notice):
 
846
            redirected_transport = transport._redirected_to(e.source, e.target)
 
847
            if redirected_transport is None:
 
848
                raise errors.NotBranchError(base)
 
849
            note('%s is%s redirected to %s',
 
850
                 transport.base, e.permanently, redirected_transport.base)
 
851
            return redirected_transport
 
852
 
 
853
        try:
 
854
            transport, format = do_catching_redirections(find_format,
 
855
                                                         transport,
 
856
                                                         redirected)
 
857
        except errors.TooManyRedirections:
 
858
            raise errors.NotBranchError(base)
 
859
 
 
860
        format.check_support_status(_unsupported)
 
861
        return format.open(transport, _found=True)
 
862
 
 
863
    @staticmethod
 
864
    def open_containing(url, possible_transports=None):
 
865
        """Open an existing branch which contains url.
 
866
 
 
867
        :param url: url to search from.
 
868
        See open_containing_from_transport for more detail.
 
869
        """
 
870
        transport = _mod_transport.get_transport(url, possible_transports)
 
871
        return BzrDir.open_containing_from_transport(transport)
 
872
 
 
873
    @staticmethod
 
874
    def open_containing_from_transport(a_transport):
 
875
        """Open an existing branch which contains a_transport.base.
 
876
 
 
877
        This probes for a branch at a_transport, and searches upwards from there.
 
878
 
 
879
        Basically we keep looking up until we find the control directory or
 
880
        run into the root.  If there isn't one, raises NotBranchError.
 
881
        If there is one and it is either an unrecognised format or an unsupported
 
882
        format, UnknownFormatError or UnsupportedFormatError are raised.
 
883
        If there is one, it is returned, along with the unused portion of url.
 
884
 
 
885
        :return: The BzrDir that contains the path, and a Unicode path
 
886
                for the rest of the URL.
 
887
        """
 
888
        # this gets the normalised url back. I.e. '.' -> the full path.
 
889
        url = a_transport.base
 
890
        while True:
 
891
            try:
 
892
                result = BzrDir.open_from_transport(a_transport)
 
893
                return result, urlutils.unescape(a_transport.relpath(url))
 
894
            except errors.NotBranchError, e:
 
895
                pass
 
896
            try:
 
897
                new_t = a_transport.clone('..')
 
898
            except errors.InvalidURLJoin:
 
899
                # reached the root, whatever that may be
 
900
                raise errors.NotBranchError(path=url)
 
901
            if new_t.base == a_transport.base:
 
902
                # reached the root, whatever that may be
 
903
                raise errors.NotBranchError(path=url)
 
904
            a_transport = new_t
 
905
 
 
906
    @classmethod
 
907
    def open_tree_or_branch(klass, location):
 
908
        """Return the branch and working tree at a location.
 
909
 
 
910
        If there is no tree at the location, tree will be None.
 
911
        If there is no branch at the location, an exception will be
 
912
        raised
 
913
        :return: (tree, branch)
 
914
        """
 
915
        bzrdir = klass.open(location)
 
916
        return bzrdir._get_tree_branch()
 
917
 
 
918
    @classmethod
 
919
    def open_containing_tree_or_branch(klass, location):
 
920
        """Return the branch and working tree contained by a location.
 
921
 
 
922
        Returns (tree, branch, relpath).
 
923
        If there is no tree at containing the location, tree will be None.
 
924
        If there is no branch containing the location, an exception will be
 
925
        raised
 
926
        relpath is the portion of the path that is contained by the branch.
 
927
        """
 
928
        bzrdir, relpath = klass.open_containing(location)
 
929
        tree, branch = bzrdir._get_tree_branch()
 
930
        return tree, branch, relpath
 
931
 
 
932
    @classmethod
 
933
    def open_containing_tree_branch_or_repository(klass, location):
 
934
        """Return the working tree, branch and repo contained by a location.
 
935
 
 
936
        Returns (tree, branch, repository, relpath).
 
937
        If there is no tree containing the location, tree will be None.
 
938
        If there is no branch containing the location, branch will be None.
 
939
        If there is no repository containing the location, repository will be
 
940
        None.
 
941
        relpath is the portion of the path that is contained by the innermost
 
942
        BzrDir.
 
943
 
 
944
        If no tree, branch or repository is found, a NotBranchError is raised.
 
945
        """
 
946
        bzrdir, relpath = klass.open_containing(location)
 
947
        try:
 
948
            tree, branch = bzrdir._get_tree_branch()
 
949
        except errors.NotBranchError:
 
950
            try:
 
951
                repo = bzrdir.find_repository()
 
952
                return None, None, repo, relpath
 
953
            except (errors.NoRepositoryPresent):
 
954
                raise errors.NotBranchError(location)
 
955
        return tree, branch, branch.repository, relpath
 
956
 
667
957
    def _cloning_metadir(self):
668
958
        """Produce a metadir suitable for cloning with.
669
959
 
709
999
 
710
1000
        :require_stacking: If True, non-stackable formats will be upgraded
711
1001
            to similar stackable formats.
712
 
        :returns: a ControlDirFormat with all component formats either set
 
1002
        :returns: a BzrDirFormat with all component formats either set
713
1003
            appropriately or set to None if that component should not be
714
1004
            created.
715
1005
        """
727
1017
            format.require_stacking()
728
1018
        return format
729
1019
 
 
1020
    @classmethod
 
1021
    def create(cls, base, format=None, possible_transports=None):
 
1022
        """Create a new BzrDir at the url 'base'.
 
1023
 
 
1024
        :param format: If supplied, the format of branch to create.  If not
 
1025
            supplied, the default is used.
 
1026
        :param possible_transports: If supplied, a list of transports that
 
1027
            can be reused to share a remote connection.
 
1028
        """
 
1029
        if cls is not BzrDir:
 
1030
            raise AssertionError("BzrDir.create always creates the"
 
1031
                "default format, not one of %r" % cls)
 
1032
        t = _mod_transport.get_transport(base, possible_transports)
 
1033
        t.ensure_base()
 
1034
        if format is None:
 
1035
            format = controldir.ControlDirFormat.get_default_format()
 
1036
        return format.initialize_on_transport(t)
 
1037
 
730
1038
    def get_branch_transport(self, branch_format, name=None):
731
1039
        """Get the transport for use by branch format in this BzrDir.
732
1040
 
766
1074
        """
767
1075
        raise NotImplementedError(self.get_workingtree_transport)
768
1076
 
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.
 
1077
 
 
1078
class BzrDirHooks(hooks.Hooks):
 
1079
    """Hooks for BzrDir operations."""
 
1080
 
 
1081
    def __init__(self):
 
1082
        """Create the default hooks."""
 
1083
        hooks.Hooks.__init__(self, "bzrlib.bzrdir", "BzrDir.hooks")
 
1084
        self.add_hook('pre_open',
 
1085
            "Invoked before attempting to open a BzrDir with the transport "
 
1086
            "that the open will use.", (1, 14))
 
1087
        self.add_hook('post_repo_init',
 
1088
            "Invoked after a repository has been initialized. "
 
1089
            "post_repo_init is called with a "
 
1090
            "bzrlib.bzrdir.RepoInitHookParams.",
 
1091
            (2, 2))
 
1092
 
 
1093
# install the default hooks
 
1094
BzrDir.hooks = BzrDirHooks()
 
1095
 
 
1096
 
 
1097
class RepoInitHookParams(object):
 
1098
    """Object holding parameters passed to *_repo_init hooks.
 
1099
 
 
1100
    There are 4 fields that hooks may wish to access:
 
1101
 
 
1102
    :ivar repository: Repository created
 
1103
    :ivar format: Repository format
 
1104
    :ivar bzrdir: The bzrdir for the repository
 
1105
    :ivar shared: The repository is shared
 
1106
    """
 
1107
 
 
1108
    def __init__(self, repository, format, a_bzrdir, shared):
 
1109
        """Create a group of RepoInitHook parameters.
 
1110
 
 
1111
        :param repository: Repository created
 
1112
        :param format: Repository format
 
1113
        :param bzrdir: The bzrdir for the repository
 
1114
        :param shared: The repository is shared
777
1115
        """
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)
 
1116
        self.repository = repository
 
1117
        self.format = format
 
1118
        self.bzrdir = a_bzrdir
 
1119
        self.shared = shared
 
1120
 
 
1121
    def __eq__(self, other):
 
1122
        return self.__dict__ == other.__dict__
783
1123
 
784
1124
    def __repr__(self):
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()
 
1125
        if self.repository:
 
1126
            return "<%s for %s>" % (self.__class__.__name__,
 
1127
                self.repository)
 
1128
        else:
 
1129
            return "<%s for %s>" % (self.__class__.__name__,
 
1130
                self.bzrdir)
799
1131
 
800
1132
 
801
1133
class BzrDirMeta1(BzrDir):
807
1139
    present within a BzrDir.
808
1140
    """
809
1141
 
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
 
 
856
1142
    def can_convert_format(self):
857
1143
        """See BzrDir.can_convert_format()."""
858
1144
        return True
859
1145
 
860
 
    def create_branch(self, name=None, repository=None,
861
 
            append_revisions_only=None):
862
 
        """See ControlDir.create_branch."""
863
 
        if name is None:
864
 
            name = self._get_selected_branch()
 
1146
    def create_branch(self, name=None, repository=None):
 
1147
        """See BzrDir.create_branch."""
865
1148
        return self._format.get_branch_format().initialize(self, name=name,
866
 
                repository=repository,
867
 
                append_revisions_only=append_revisions_only)
 
1149
                repository=repository)
868
1150
 
869
1151
    def destroy_branch(self, name=None):
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)
 
1152
        """See BzrDir.create_branch."""
 
1153
        if name is not None:
 
1154
            raise errors.NoColocatedBranchSupport(self)
 
1155
        self.transport.delete_tree('branch')
890
1156
 
891
1157
    def create_repository(self, shared=False):
892
1158
        """See BzrDir.create_repository."""
894
1160
 
895
1161
    def destroy_repository(self):
896
1162
        """See BzrDir.destroy_repository."""
897
 
        try:
898
 
            self.transport.delete_tree('repository')
899
 
        except errors.NoSuchFile:
900
 
            raise errors.NoRepositoryPresent(self)
 
1163
        self.transport.delete_tree('repository')
901
1164
 
902
1165
    def create_workingtree(self, revision_id=None, from_branch=None,
903
1166
                           accelerator_tree=None, hardlink=False):
925
1188
 
926
1189
        This might be a synthetic object for e.g. RemoteBranch and SVN.
927
1190
        """
928
 
        from bzrlib.branch import BranchFormatMetadir
929
 
        return BranchFormatMetadir.find_format(self, name=name)
 
1191
        from bzrlib.branch import BranchFormat
 
1192
        return BranchFormat.find_format(self, name=name)
930
1193
 
931
1194
    def _get_mkdir_mode(self):
932
1195
        """Figure out the mode to use when creating a bzrdir subdir."""
936
1199
 
937
1200
    def get_branch_reference(self, name=None):
938
1201
        """See BzrDir.get_branch_reference()."""
939
 
        from bzrlib.branch import BranchFormatMetadir
940
 
        format = BranchFormatMetadir.find_format(self, name=name)
 
1202
        from bzrlib.branch import BranchFormat
 
1203
        format = BranchFormat.find_format(self, name=name)
941
1204
        return format.get_reference(self, name=name)
942
1205
 
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
 
 
947
1206
    def get_branch_transport(self, branch_format, name=None):
948
1207
        """See BzrDir.get_branch_transport()."""
949
 
        if name is None:
950
 
            name = self._get_selected_branch()
951
 
        path = self._get_branch_path(name)
 
1208
        if name is not None:
 
1209
            raise errors.NoColocatedBranchSupport(self)
952
1210
        # XXX: this shouldn't implicitly create the directory if it's just
953
1211
        # promising to get a transport -- mbp 20090727
954
1212
        if branch_format is None:
955
 
            return self.transport.clone(path)
 
1213
            return self.transport.clone('branch')
956
1214
        try:
957
1215
            branch_format.get_format_string()
958
1216
        except NotImplementedError:
959
1217
            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)
981
1218
        try:
982
 
            self.transport.mkdir(path, mode=mode)
 
1219
            self.transport.mkdir('branch', mode=self._get_mkdir_mode())
983
1220
        except errors.FileExists:
984
1221
            pass
985
 
        return self.transport.clone(path)
 
1222
        return self.transport.clone('branch')
986
1223
 
987
1224
    def get_repository_transport(self, repository_format):
988
1225
        """See BzrDir.get_repository_transport()."""
1012
1249
            pass
1013
1250
        return self.transport.clone('checkout')
1014
1251
 
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
 
 
1028
1252
    def has_workingtree(self):
1029
1253
        """Tell if this bzrdir contains a working tree.
1030
1254
 
1031
1255
        Note: if you're going to open the working tree, you should just go
1032
1256
        ahead and try, and not ask permission first.
1033
1257
        """
1034
 
        from bzrlib.workingtree import WorkingTreeFormatMetaDir
 
1258
        from bzrlib.workingtree import WorkingTreeFormat
1035
1259
        try:
1036
 
            WorkingTreeFormatMetaDir.find_format_string(self)
 
1260
            WorkingTreeFormat.find_format_string(self)
1037
1261
        except errors.NoWorkingTree:
1038
1262
            return False
1039
1263
        return True
1040
1264
 
1041
1265
    def needs_format_conversion(self, format):
1042
1266
        """See BzrDir.needs_format_conversion()."""
1043
 
        if (not isinstance(self._format, format.__class__) or
1044
 
            self._format.get_format_string() != format.get_format_string()):
 
1267
        if not isinstance(self._format, format.__class__):
1045
1268
            # it is not a meta dir format, conversion is needed.
1046
1269
            return True
1047
1270
        # we might want to push this down to the repository?
1068
1291
        return False
1069
1292
 
1070
1293
    def open_branch(self, name=None, unsupported=False,
1071
 
                    ignore_fallbacks=False, possible_transports=None):
1072
 
        """See ControlDir.open_branch."""
1073
 
        if name is None:
1074
 
            name = self._get_selected_branch()
 
1294
                    ignore_fallbacks=False):
 
1295
        """See BzrDir.open_branch."""
1075
1296
        format = self.find_branch_format(name=name)
1076
1297
        format.check_support_status(unsupported)
1077
1298
        return format.open(self, name=name,
1078
 
            _found=True, ignore_fallbacks=ignore_fallbacks,
1079
 
            possible_transports=possible_transports)
 
1299
            _found=True, ignore_fallbacks=ignore_fallbacks)
1080
1300
 
1081
1301
    def open_repository(self, unsupported=False):
1082
1302
        """See BzrDir.open_repository."""
1083
 
        from bzrlib.repository import RepositoryFormatMetaDir
1084
 
        format = RepositoryFormatMetaDir.find_format(self)
 
1303
        from bzrlib.repository import RepositoryFormat
 
1304
        format = RepositoryFormat.find_format(self)
1085
1305
        format.check_support_status(unsupported)
1086
1306
        return format.open(self, _found=True)
1087
1307
 
1088
1308
    def open_workingtree(self, unsupported=False,
1089
1309
            recommend_upgrade=True):
1090
1310
        """See BzrDir.open_workingtree."""
1091
 
        from bzrlib.workingtree import WorkingTreeFormatMetaDir
1092
 
        format = WorkingTreeFormatMetaDir.find_format(self)
 
1311
        from bzrlib.workingtree import WorkingTreeFormat
 
1312
        format = WorkingTreeFormat.find_format(self)
1093
1313
        format.check_support_status(unsupported, recommend_upgrade,
1094
1314
            basedir=self.root_transport.base)
1095
1315
        return format.open(self, _found=True)
1098
1318
        return config.TransportConfig(self.transport, 'control.conf')
1099
1319
 
1100
1320
 
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
 
 
1227
1321
class BzrProber(controldir.Prober):
1228
1322
    """Prober for formats that use a .bzr/ control directory."""
1229
1323
 
1231
1325
    """The known .bzr formats."""
1232
1326
 
1233
1327
    @classmethod
 
1328
    @deprecated_method(deprecated_in((2, 4, 0)))
 
1329
    def register_bzrdir_format(klass, format):
 
1330
        klass.formats.register(format.get_format_string(), format)
 
1331
 
 
1332
    @classmethod
 
1333
    @deprecated_method(deprecated_in((2, 4, 0)))
 
1334
    def unregister_bzrdir_format(klass, format):
 
1335
        klass.formats.remove(format.get_format_string())
 
1336
 
 
1337
    @classmethod
1234
1338
    def probe_transport(klass, transport):
1235
1339
        """Return the .bzrdir style format present in a directory."""
1236
1340
        try:
1238
1342
        except errors.NoSuchFile:
1239
1343
            raise errors.NotBranchError(path=transport.base)
1240
1344
        try:
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)
 
1345
            return klass.formats.get(format_string)
1246
1346
        except KeyError:
1247
 
            raise errors.UnknownFormatError(format=first_line, kind='bzrdir')
1248
 
        return cls.from_string(format_string)
 
1347
            raise errors.UnknownFormatError(format=format_string, kind='bzrdir')
1249
1348
 
1250
1349
    @classmethod
1251
1350
    def known_formats(cls):
1294
1393
        return set([RemoteBzrDirFormat()])
1295
1394
 
1296
1395
 
1297
 
class BzrDirFormat(BzrFormat, controldir.ControlDirFormat):
 
1396
class BzrDirFormat(controldir.ControlDirFormat):
1298
1397
    """ControlDirFormat base class for .bzr/ directories.
1299
1398
 
1300
1399
    Formats are placed in a dict by their format string for reference
1311
1410
    # _lock_class must be set in subclasses to the lock type, typ.
1312
1411
    # TransportLock or LockDir
1313
1412
 
 
1413
    @classmethod
 
1414
    def get_format_string(cls):
 
1415
        """Return the ASCII format string that identifies this format."""
 
1416
        raise NotImplementedError(self.get_format_string)
 
1417
 
1314
1418
    def initialize_on_transport(self, transport):
1315
1419
        """Initialize a new bzrdir in the base directory of a Transport."""
1316
1420
        try:
1357
1461
        :param shared_repo: Control whether made repositories are shared or
1358
1462
            not.
1359
1463
        :param vfs_only: If True do not attempt to use a smart server
1360
 
        :return: repo, controldir, require_stacking, repository_policy. repo is
 
1464
        :return: repo, bzrdir, require_stacking, repository_policy. repo is
1361
1465
            None if none was created or found, bzrdir is always valid.
1362
1466
            require_stacking is the result of examining the stacked_on
1363
1467
            parameter and any stacking policy found for the target.
1438
1542
        # mode from the root directory
1439
1543
        temp_control = lockable_files.LockableFiles(transport,
1440
1544
                            '', lockable_files.TransportLock)
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)
 
1545
        temp_control._transport.mkdir('.bzr',
 
1546
                                      # FIXME: RBC 20060121 don't peek under
 
1547
                                      # the covers
 
1548
                                      mode=temp_control._dir_mode)
1448
1549
        if sys.platform == 'win32' and isinstance(transport, local.LocalTransport):
1449
1550
            win32utils.set_file_attr_hidden(transport._abspath('.bzr'))
1450
1551
        file_mode = temp_control._file_mode
1454
1555
                       "This is a Bazaar control directory.\n"
1455
1556
                       "Do not change any files in this directory.\n"
1456
1557
                       "See http://bazaar.canonical.com/ for more information about Bazaar.\n"),
1457
 
                      ('branch-format', self.as_string()),
 
1558
                      ('branch-format', self.get_format_string()),
1458
1559
                      ]
1459
1560
        # NB: no need to escape relative paths that are url safe.
1460
1561
        control_files = lockable_files.LockableFiles(bzrdir_transport,
1504
1605
            compatible with whatever sub formats are supported by self.
1505
1606
        :return: None.
1506
1607
        """
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)
1520
1608
 
1521
1609
 
1522
1610
class BzrDirMetaFormat1(BzrDirFormat):
1524
1612
 
1525
1613
    This is the first format with split out working tree, branch and repository
1526
1614
    disk storage.
1527
 
 
1528
1615
    It has:
1529
 
 
1530
 
    - Format 3 working trees [optional]
1531
 
    - Format 5 branches [optional]
1532
 
    - Format 7 repositories [optional]
 
1616
     - Format 3 working trees [optional]
 
1617
     - Format 5 branches [optional]
 
1618
     - Format 7 repositories [optional]
1533
1619
    """
1534
1620
 
1535
1621
    _lock_class = lockdir.LockDir
1536
1622
 
1537
1623
    fixed_components = False
1538
1624
 
1539
 
    colocated_branches = True
1540
 
 
1541
1625
    def __init__(self):
1542
 
        BzrDirFormat.__init__(self)
1543
1626
        self._workingtree_format = None
1544
1627
        self._branch_format = None
1545
1628
        self._repository_format = None
1551
1634
            return False
1552
1635
        if other.workingtree_format != self.workingtree_format:
1553
1636
            return False
1554
 
        if other.features != self.features:
1555
 
            return False
1556
1637
        return True
1557
1638
 
1558
1639
    def __ne__(self, other):
1636
1717
                    new_repo_format = None
1637
1718
            if new_repo_format is not None:
1638
1719
                self.repository_format = new_repo_format
1639
 
                note(gettext('Source repository format does not support stacking,'
1640
 
                     ' using format:\n  %s'),
 
1720
                note('Source repository format does not support stacking,'
 
1721
                     ' using format:\n  %s',
1641
1722
                     new_repo_format.get_format_description())
1642
1723
 
1643
1724
        if not self.get_branch_format().supports_stacking():
1656
1737
            if new_branch_format is not None:
1657
1738
                # Does support stacking, use its format.
1658
1739
                self.set_branch_format(new_branch_format)
1659
 
                note(gettext('Source branch format does not support stacking,'
1660
 
                     ' using format:\n  %s'),
 
1740
                note('Source branch format does not support stacking,'
 
1741
                     ' using format:\n  %s',
1661
1742
                     new_branch_format.get_format_description())
1662
1743
 
1663
1744
    def get_converter(self, format=None):
1664
1745
        """See BzrDirFormat.get_converter()."""
1665
1746
        if format is None:
1666
1747
            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)
1673
1748
        if not isinstance(self, format.__class__):
1674
1749
            # converting away from metadir is not implemented
1675
1750
            raise NotImplementedError(self.get_converter)
1684
1759
        """See BzrDirFormat.get_format_description()."""
1685
1760
        return "Meta directory format 1"
1686
1761
 
 
1762
    def network_name(self):
 
1763
        return self.get_format_string()
 
1764
 
1687
1765
    def _open(self, transport):
1688
1766
        """See BzrDirFormat._open."""
1689
1767
        # Create a new format instance because otherwise initialisation of new
1718
1796
            compatible with whatever sub formats are supported by self.
1719
1797
        :return: None.
1720
1798
        """
1721
 
        super(BzrDirMetaFormat1, self)._supply_sub_formats_to(other_format)
1722
1799
        if getattr(self, '_repository_format', None) is not None:
1723
1800
            other_format.repository_format = self.repository_format
1724
1801
        if self._branch_format is not None:
1737
1814
    def __set_workingtree_format(self, wt_format):
1738
1815
        self._workingtree_format = wt_format
1739
1816
 
1740
 
    def __repr__(self):
1741
 
        return "<%r>" % (self.__class__.__name__,)
1742
 
 
1743
1817
    workingtree_format = property(__get_workingtree_format,
1744
1818
                                  __set_workingtree_format)
1745
1819
 
1750
1824
controldir.ControlDirFormat._default_format = BzrDirMetaFormat1()
1751
1825
 
1752
1826
 
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
 
 
1781
1827
class ConvertMetaToMeta(controldir.Converter):
1782
1828
    """Converts the components of metadirs."""
1783
1829
 
1802
1848
        else:
1803
1849
            if not isinstance(repo._format, self.target_format.repository_format.__class__):
1804
1850
                from bzrlib.repository import CopyConverter
1805
 
                ui.ui_factory.note(gettext('starting repository conversion'))
 
1851
                ui.ui_factory.note('starting repository conversion')
1806
1852
                converter = CopyConverter(self.target_format.repository_format)
1807
1853
                converter.convert(repo, pb)
1808
1854
        for branch in self.bzrdir.list_branches():
1812
1858
            old = branch._format.__class__
1813
1859
            new = self.target_format.get_branch_format().__class__
1814
1860
            while old != new:
1815
 
                if (old == fullhistorybranch.BzrBranchFormat5 and
 
1861
                if (old == _mod_branch.BzrBranchFormat5 and
1816
1862
                    new in (_mod_branch.BzrBranchFormat6,
1817
1863
                        _mod_branch.BzrBranchFormat7,
1818
1864
                        _mod_branch.BzrBranchFormat8)):
1856
1902
        return to_convert
1857
1903
 
1858
1904
 
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
 
 
1894
1905
controldir.ControlDirFormat.register_server_prober(RemoteBzrProber)
1895
1906
 
1896
1907
 
1973
1984
        else:
1974
1985
            self._require_stacking = True
1975
1986
 
1976
 
    def acquire_repository(self, make_working_trees=None, shared=False,
1977
 
            possible_transports=None):
 
1987
    def acquire_repository(self, make_working_trees=None, shared=False):
1978
1988
        """Acquire a repository for this bzrdir.
1979
1989
 
1980
1990
        Implementations may create a new repository or use a pre-exising
1981
1991
        repository.
1982
 
 
1983
1992
        :param make_working_trees: If creating a repository, set
1984
1993
            make_working_trees to this value (if non-None)
1985
1994
        :param shared: If creating a repository, make it shared if True
1986
1995
        :return: A repository, is_new_flag (True if the repository was
1987
1996
            created).
1988
1997
        """
1989
 
        raise NotImplementedError(RepositoryAcquisitionPolicy.acquire_repository)
 
1998
        raise NotImplemented(RepositoryAcquisitionPolicy.acquire_repository)
1990
1999
 
1991
2000
 
1992
2001
class CreateRepository(RepositoryAcquisitionPolicy):
1994
2003
 
1995
2004
    def __init__(self, bzrdir, stack_on=None, stack_on_pwd=None,
1996
2005
                 require_stacking=False):
1997
 
        """Constructor.
1998
 
 
 
2006
        """
 
2007
        Constructor.
1999
2008
        :param bzrdir: The bzrdir to create the repository on.
2000
2009
        :param stack_on: A location to stack on
2001
2010
        :param stack_on_pwd: If stack_on is relative, the location it is
2005
2014
                                             require_stacking)
2006
2015
        self._bzrdir = bzrdir
2007
2016
 
2008
 
    def acquire_repository(self, make_working_trees=None, shared=False,
2009
 
            possible_transports=None):
 
2017
    def acquire_repository(self, make_working_trees=None, shared=False):
2010
2018
        """Implementation of RepositoryAcquisitionPolicy.acquire_repository
2011
2019
 
2012
2020
        Creates the desired repository in the bzrdir we already have.
2013
2021
        """
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)
2019
2022
        stack_on = self._get_full_stack_on()
2020
2023
        if stack_on:
2021
2024
            format = self._bzrdir._format
2022
2025
            format.require_stacking(stack_on=stack_on,
2023
 
                                    possible_transports=possible_transports)
 
2026
                                    possible_transports=[self._bzrdir.root_transport])
2024
2027
            if not self._require_stacking:
2025
2028
                # We have picked up automatic stacking somewhere.
2026
 
                note(gettext('Using default stacking branch {0} at {1}').format(
2027
 
                    self._stack_on, self._stack_on_pwd))
 
2029
                note('Using default stacking branch %s at %s', self._stack_on,
 
2030
                    self._stack_on_pwd)
2028
2031
        repository = self._bzrdir.create_repository(shared=shared)
2029
2032
        self._add_fallback(repository,
2030
 
                           possible_transports=possible_transports)
 
2033
                           possible_transports=[self._bzrdir.transport])
2031
2034
        if make_working_trees is not None:
2032
2035
            repository.set_make_working_trees(make_working_trees)
2033
2036
        return repository, True
2049
2052
                                             require_stacking)
2050
2053
        self._repository = repository
2051
2054
 
2052
 
    def acquire_repository(self, make_working_trees=None, shared=False,
2053
 
            possible_transports=None):
 
2055
    def acquire_repository(self, make_working_trees=None, shared=False):
2054
2056
        """Implementation of RepositoryAcquisitionPolicy.acquire_repository
2055
2057
 
2056
2058
        Returns an existing repository to use.
2057
2059
        """
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)
2063
2060
        self._add_fallback(self._repository,
2064
 
                       possible_transports=possible_transports)
 
2061
                       possible_transports=[self._repository.bzrdir.transport])
2065
2062
        return self._repository, False
2066
2063
 
2067
2064
 
2071
2068
         tree_format=None,
2072
2069
         hidden=False,
2073
2070
         experimental=False,
2074
 
         alias=False, bzrdir_format=None):
 
2071
         alias=False):
2075
2072
    """Register a metadir subformat.
2076
2073
 
2077
 
    These all use a meta bzrdir, but can be parameterized by the
2078
 
    Repository/Branch/WorkingTreeformats.
 
2074
    These all use a BzrDirMetaFormat1 bzrdir, but can be parameterized
 
2075
    by the Repository/Branch/WorkingTreeformats.
2079
2076
 
2080
2077
    :param repository_format: The fully-qualified repository format class
2081
2078
        name as a string.
2084
2081
    :param tree_format: Fully-qualified tree format class name as
2085
2082
        a string.
2086
2083
    """
2087
 
    if bzrdir_format is None:
2088
 
        bzrdir_format = BzrDirMetaFormat1
2089
2084
    # This should be expanded to support setting WorkingTree and Branch
2090
 
    # formats, once the API supports that.
 
2085
    # formats, once BzrDirMetaFormat1 supports that.
2091
2086
    def _load(full_name):
2092
2087
        mod_name, factory_name = full_name.rsplit('.', 1)
2093
2088
        try:
2100
2095
        return factory()
2101
2096
 
2102
2097
    def helper():
2103
 
        bd = bzrdir_format()
 
2098
        bd = BzrDirMetaFormat1()
2104
2099
        if branch_format is not None:
2105
2100
            bd.set_branch_format(_load(branch_format))
2106
2101
        if tree_format is not None:
2114
2109
register_metadir(controldir.format_registry, 'knit',
2115
2110
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
2116
2111
    'Format using knits.  Recommended for interoperation with bzr <= 0.14.',
2117
 
    branch_format='bzrlib.branchfmt.fullhistory.BzrBranchFormat5',
 
2112
    branch_format='bzrlib.branch.BzrBranchFormat5',
2118
2113
    tree_format='bzrlib.workingtree_3.WorkingTreeFormat3',
2119
2114
    hidden=True,
2120
2115
    deprecated=True)
2121
2116
register_metadir(controldir.format_registry, 'dirstate',
2122
2117
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
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',
 
2118
    help='New in 0.15: Fast local operations. Compatible with bzr 0.8 and '
 
2119
        'above when accessed over the network.',
 
2120
    branch_format='bzrlib.branch.BzrBranchFormat5',
2127
2121
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2128
2122
    hidden=True,
2129
2123
    deprecated=True)
2130
2124
register_metadir(controldir.format_registry, 'dirstate-tags',
2131
2125
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
2132
 
    help='Variant of dirstate with support for tags. '
2133
 
        'Introduced in bzr 0.15.',
 
2126
    help='New in 0.15: Fast local operations and improved scaling for '
 
2127
        'network operations. Additionally adds support for tags.'
 
2128
        ' Incompatible with bzr < 0.15.',
2134
2129
    branch_format='bzrlib.branch.BzrBranchFormat6',
2135
2130
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2136
2131
    hidden=True,
2137
2132
    deprecated=True)
2138
2133
register_metadir(controldir.format_registry, 'rich-root',
2139
2134
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit4',
2140
 
    help='Variant of dirstate with better handling of tree roots. '
2141
 
        'Introduced in bzr 1.0',
 
2135
    help='New in 1.0.  Better handling of tree roots.  Incompatible with'
 
2136
        ' bzr < 1.0.',
2142
2137
    branch_format='bzrlib.branch.BzrBranchFormat6',
2143
2138
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2144
2139
    hidden=True,
2145
2140
    deprecated=True)
2146
2141
register_metadir(controldir.format_registry, 'dirstate-with-subtree',
2147
2142
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
2148
 
    help='Variant of dirstate with support for nested trees. '
2149
 
         'Introduced in 0.15.',
 
2143
    help='New in 0.15: Fast local operations and improved scaling for '
 
2144
        'network operations. Additionally adds support for versioning nested '
 
2145
        'bzr branches. Incompatible with bzr < 0.15.',
2150
2146
    branch_format='bzrlib.branch.BzrBranchFormat6',
2151
2147
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2152
2148
    experimental=True,
2154
2150
    )
2155
2151
register_metadir(controldir.format_registry, 'pack-0.92',
2156
2152
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack1',
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. '
 
2153
    help='New in 0.92: Pack-based format with data compatible with '
 
2154
        'dirstate-tags format repositories. Interoperates with '
 
2155
        'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
2160
2156
        ,
2161
2157
    branch_format='bzrlib.branch.BzrBranchFormat6',
2162
2158
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2163
 
    deprecated=True,
2164
2159
    )
2165
2160
register_metadir(controldir.format_registry, 'pack-0.92-subtree',
2166
2161
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack3',
2167
 
    help='Pack-based format used in 1.x series, with subtree support. '
2168
 
        'Introduced in 0.92. Interoperates with '
 
2162
    help='New in 0.92: Pack-based format with data compatible with '
 
2163
        'dirstate-with-subtree format repositories. Interoperates with '
2169
2164
        'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
2170
2165
        ,
2171
2166
    branch_format='bzrlib.branch.BzrBranchFormat6',
2172
2167
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2173
2168
    hidden=True,
2174
 
    deprecated=True,
2175
2169
    experimental=True,
2176
2170
    )
2177
2171
register_metadir(controldir.format_registry, 'rich-root-pack',
2178
2172
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack4',
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.',
 
2173
    help='New in 1.0: A variant of pack-0.92 that supports rich-root data '
 
2174
         '(needed for bzr-svn and bzr-git).',
2181
2175
    branch_format='bzrlib.branch.BzrBranchFormat6',
2182
2176
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2183
2177
    hidden=True,
2184
 
    deprecated=True,
2185
2178
    )
2186
2179
register_metadir(controldir.format_registry, '1.6',
2187
2180
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack5',
2191
2184
    branch_format='bzrlib.branch.BzrBranchFormat7',
2192
2185
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2193
2186
    hidden=True,
2194
 
    deprecated=True,
2195
2187
    )
2196
2188
register_metadir(controldir.format_registry, '1.6.1-rich-root',
2197
2189
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack5RichRoot',
2200
2192
    branch_format='bzrlib.branch.BzrBranchFormat7',
2201
2193
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2202
2194
    hidden=True,
2203
 
    deprecated=True,
2204
2195
    )
2205
2196
register_metadir(controldir.format_registry, '1.9',
2206
2197
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack6',
2210
2201
    branch_format='bzrlib.branch.BzrBranchFormat7',
2211
2202
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2212
2203
    hidden=True,
2213
 
    deprecated=True,
2214
2204
    )
2215
2205
register_metadir(controldir.format_registry, '1.9-rich-root',
2216
2206
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack6RichRoot',
2219
2209
    branch_format='bzrlib.branch.BzrBranchFormat7',
2220
2210
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat4',
2221
2211
    hidden=True,
2222
 
    deprecated=True,
2223
2212
    )
2224
2213
register_metadir(controldir.format_registry, '1.14',
2225
2214
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack6',
2226
2215
    help='A working-tree format that supports content filtering.',
2227
2216
    branch_format='bzrlib.branch.BzrBranchFormat7',
2228
2217
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat5',
2229
 
    hidden=True,
2230
 
    deprecated=True,
2231
2218
    )
2232
2219
register_metadir(controldir.format_registry, '1.14-rich-root',
2233
2220
    'bzrlib.repofmt.knitpack_repo.RepositoryFormatKnitPack6RichRoot',
2235
2222
         '(needed for bzr-svn and bzr-git).',
2236
2223
    branch_format='bzrlib.branch.BzrBranchFormat7',
2237
2224
    tree_format='bzrlib.workingtree_4.WorkingTreeFormat5',
2238
 
    hidden=True,
2239
 
    deprecated=True,
2240
2225
    )
2241
2226
# The following un-numbered 'development' formats should always just be aliases.
2242
2227
register_metadir(controldir.format_registry, 'development-subtree',
2270
2255
    alias=False,
2271
2256
    )
2272
2257
 
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
 
 
2283
2258
# And the development formats above will have aliased one of the following:
2284
2259
 
2285
2260
# Finally, the current format.
2286
2261
register_metadir(controldir.format_registry, '2a',
2287
2262
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2a',
2288
 
    help='Format for the bzr 2.0 series.\n'
 
2263
    help='First format for bzr 2.0 series.\n'
2289
2264
        'Uses group-compress storage.\n'
2290
2265
        'Provides rich roots which are a one-way transition.\n',
2291
2266
        # 'storage in packs, 255-way hashed CHK inventory, bencode revision, group compress, '
2306
2281
    help='Same as 2a.')
2307
2282
 
2308
2283
# The current format that is made on 'bzr init'.
2309
 
format_name = config.GlobalStack().get('default_format')
2310
 
controldir.format_registry.set_default(format_name)
 
2284
format_name = config.GlobalConfig().get_user_option('default_format')
 
2285
if format_name is None:
 
2286
    controldir.format_registry.set_default('2a')
 
2287
else:
 
2288
    controldir.format_registry.set_default(format_name)
2311
2289
 
2312
2290
# XXX 2010-08-20 JRV: There is still a lot of code relying on
2313
2291
# bzrlib.bzrdir.format_registry existing. When BzrDir.create/BzrDir.open/etc