~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/bzrdir.py

  • Committer: John Arbash Meinel
  • Date: 2010-08-24 19:21:32 UTC
  • mto: This revision was merged to the branch mainline in revision 5390.
  • Revision ID: john@arbash-meinel.com-20100824192132-2ktt5adkbk5bk1ct
Handle test_source and extensions. Also define an 'extern' protocol, to allow
the test suite to recognize that returning an object of that type is a Python object.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
 
1
# Copyright (C) 2006-2010 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
29
29
 
30
30
import os
31
31
import sys
 
32
import warnings
32
33
 
33
34
from bzrlib.lazy_import import lazy_import
34
35
lazy_import(globals(), """
85
86
    registry,
86
87
    symbol_versioning,
87
88
    )
88
 
 
89
 
 
90
 
class BzrDir(object):
 
89
    
 
90
    
 
91
class ControlComponent(object):
 
92
    """Abstract base class for control directory components.
 
93
    
 
94
    This provides interfaces that are common across bzrdirs, 
 
95
    repositories, branches, and workingtree control directories.
 
96
    
 
97
    They all expose two urls and transports: the *user* URL is the 
 
98
    one that stops above the control directory (eg .bzr) and that 
 
99
    should normally be used in messages, and the *control* URL is
 
100
    under that in eg .bzr/checkout and is used to read the control
 
101
    files.
 
102
    
 
103
    This can be used as a mixin and is intended to fit with 
 
104
    foreign formats.
 
105
    """
 
106
    
 
107
    @property
 
108
    def control_transport(self):
 
109
        raise NotImplementedError
 
110
   
 
111
    @property
 
112
    def control_url(self):
 
113
        return self.control_transport.base
 
114
    
 
115
    @property
 
116
    def user_transport(self):
 
117
        raise NotImplementedError
 
118
        
 
119
    @property
 
120
    def user_url(self):
 
121
        return self.user_transport.base
 
122
    
 
123
 
 
124
class BzrDir(ControlComponent):
91
125
    """A .bzr control diretory.
92
126
 
93
127
    BzrDir instances let you create or open any of the things that can be
129
163
        return True
130
164
 
131
165
    def check_conversion_target(self, target_format):
 
166
        """Check that a bzrdir as a whole can be converted to a new format."""
 
167
        # The only current restriction is that the repository content can be 
 
168
        # fetched compatibly with the target.
132
169
        target_repo_format = target_format.repository_format
133
 
        source_repo_format = self._format.repository_format
134
 
        source_repo_format.check_conversion_target(target_repo_format)
 
170
        try:
 
171
            self.open_repository()._format.check_conversion_target(
 
172
                target_repo_format)
 
173
        except errors.NoRepositoryPresent:
 
174
            # No repo, no problem.
 
175
            pass
135
176
 
136
177
    @staticmethod
137
178
    def _check_supported(format, allow_unsupported,
253
294
                # copied, and finally if we are copying up to a specific
254
295
                # revision_id then we can use the pending-ancestry-result which
255
296
                # does not require traversing all of history to describe it.
256
 
                if (result_repo.bzrdir.root_transport.base ==
257
 
                    result.root_transport.base and not require_stacking and
 
297
                if (result_repo.user_url == result.user_url
 
298
                    and not require_stacking and
258
299
                    revision_id is not None):
259
300
                    fetch_spec = graph.PendingAncestryResult(
260
301
                        [revision_id], local_repo)
334
375
            recurse = True
335
376
            try:
336
377
                bzrdir = BzrDir.open_from_transport(current_transport)
337
 
            except errors.NotBranchError:
 
378
            except (errors.NotBranchError, errors.PermissionDenied):
338
379
                pass
339
380
            else:
340
381
                recurse, value = evaluate(bzrdir)
341
382
                yield value
342
383
            try:
343
384
                subdirs = list_current(current_transport)
344
 
            except errors.NoSuchFile:
 
385
            except (errors.NoSuchFile, errors.PermissionDenied):
345
386
                continue
346
387
            if recurse:
347
388
                for subdir in sorted(subdirs, reverse=True):
348
389
                    pending.append(current_transport.clone(subdir))
349
390
 
 
391
    def list_branches(self):
 
392
        """Return a sequence of all branches local to this control directory.
 
393
 
 
394
        """
 
395
        try:
 
396
            return [self.open_branch()]
 
397
        except (errors.NotBranchError, errors.NoRepositoryPresent):
 
398
            return []
 
399
 
350
400
    @staticmethod
351
401
    def find_branches(transport):
352
402
        """Find all branches under a transport.
364
414
            except errors.NoRepositoryPresent:
365
415
                pass
366
416
            else:
367
 
                return False, (None, repository)
368
 
            try:
369
 
                branch = bzrdir.open_branch()
370
 
            except errors.NotBranchError:
371
 
                return True, (None, None)
372
 
            else:
373
 
                return True, (branch, None)
374
 
        branches = []
375
 
        for branch, repo in BzrDir.find_bzrdirs(transport, evaluate=evaluate):
 
417
                return False, ([], repository)
 
418
            return True, (bzrdir.list_branches(), None)
 
419
        ret = []
 
420
        for branches, repo in BzrDir.find_bzrdirs(transport,
 
421
                                                  evaluate=evaluate):
376
422
            if repo is not None:
377
 
                branches.extend(repo.find_branches())
378
 
            if branch is not None:
379
 
                branches.append(branch)
380
 
        return branches
 
423
                ret.extend(repo.find_branches())
 
424
            if branches is not None:
 
425
                ret.extend(branches)
 
426
        return ret
381
427
 
382
428
    def destroy_repository(self):
383
429
        """Destroy the repository in this BzrDir"""
384
430
        raise NotImplementedError(self.destroy_repository)
385
431
 
386
 
    def create_branch(self):
 
432
    def create_branch(self, name=None):
387
433
        """Create a branch in this BzrDir.
388
434
 
 
435
        :param name: Name of the colocated branch to create, None for
 
436
            the default branch.
 
437
 
389
438
        The bzrdir's format will control what branch format is created.
390
439
        For more control see BranchFormatXX.create(a_bzrdir).
391
440
        """
392
441
        raise NotImplementedError(self.create_branch)
393
442
 
394
 
    def destroy_branch(self):
395
 
        """Destroy the branch in this BzrDir"""
 
443
    def destroy_branch(self, name=None):
 
444
        """Destroy a branch in this BzrDir.
 
445
        
 
446
        :param name: Name of the branch to destroy, None for the default 
 
447
            branch.
 
448
        """
396
449
        raise NotImplementedError(self.destroy_branch)
397
450
 
398
451
    @staticmethod
438
491
            stop = False
439
492
            stack_on = config.get_default_stack_on()
440
493
            if stack_on is not None:
441
 
                stack_on_pwd = found_bzrdir.root_transport.base
 
494
                stack_on_pwd = found_bzrdir.user_url
442
495
                stop = True
443
496
            # does it have a repository ?
444
497
            try:
446
499
            except errors.NoRepositoryPresent:
447
500
                repository = None
448
501
            else:
449
 
                if ((found_bzrdir.root_transport.base !=
450
 
                     self.root_transport.base) and not repository.is_shared()):
 
502
                if (found_bzrdir.user_url != self.user_url 
 
503
                    and not repository.is_shared()):
451
504
                    # Don't look higher, can't use a higher shared repo.
452
505
                    repository = None
453
506
                    stop = True
562
615
        """
563
616
        raise NotImplementedError(self.create_workingtree)
564
617
 
 
618
    def generate_backup_name(self, base):
 
619
        """Generate a non-existing backup file name based on base."""
 
620
        counter = 1
 
621
        name = "%s.~%d~" % (base, counter)
 
622
        while self.root_transport.has(name):
 
623
            counter += 1
 
624
            name = "%s.~%d~" % (base, counter)
 
625
        return name
 
626
 
565
627
    def backup_bzrdir(self):
566
628
        """Backup this bzr control directory.
567
629
 
568
630
        :return: Tuple with old path name and new path name
569
631
        """
 
632
 
 
633
        backup_dir=self.generate_backup_name('backup.bzr')
570
634
        pb = ui.ui_factory.nested_progress_bar()
571
635
        try:
572
636
            # FIXME: bug 300001 -- the backup fails if the backup directory
573
637
            # already exists, but it should instead either remove it or make
574
638
            # a new backup directory.
575
639
            #
576
 
            # FIXME: bug 262450 -- the backup directory should have the same
577
 
            # permissions as the .bzr directory (probably a bug in copy_tree)
578
640
            old_path = self.root_transport.abspath('.bzr')
579
 
            new_path = self.root_transport.abspath('backup.bzr')
580
 
            pb.note('making backup of %s' % (old_path,))
581
 
            pb.note('  to %s' % (new_path,))
582
 
            self.root_transport.copy_tree('.bzr', 'backup.bzr')
 
641
            new_path = self.root_transport.abspath(backup_dir)
 
642
            ui.ui_factory.note('making backup of %s\n  to %s' % (old_path, new_path,))
 
643
            self.root_transport.copy_tree('.bzr', backup_dir)
583
644
            return (old_path, new_path)
584
645
        finally:
585
646
            pb.finished()
643
704
            if stop:
644
705
                return result
645
706
            next_transport = found_bzrdir.root_transport.clone('..')
646
 
            if (found_bzrdir.root_transport.base == next_transport.base):
 
707
            if (found_bzrdir.user_url == next_transport.base):
647
708
                # top of the file system
648
709
                return None
649
710
            # find the next containing bzrdir
666
727
                repository = found_bzrdir.open_repository()
667
728
            except errors.NoRepositoryPresent:
668
729
                return None, False
669
 
            if found_bzrdir.root_transport.base == self.root_transport.base:
 
730
            if found_bzrdir.user_url == self.user_url:
670
731
                return repository, True
671
732
            elif repository.is_shared():
672
733
                return repository, True
678
739
            raise errors.NoRepositoryPresent(self)
679
740
        return found_repo
680
741
 
681
 
    def get_branch_reference(self):
 
742
    def get_branch_reference(self, name=None):
682
743
        """Return the referenced URL for the branch in this bzrdir.
683
744
 
 
745
        :param name: Optional colocated branch name
684
746
        :raises NotBranchError: If there is no Branch.
 
747
        :raises NoColocatedBranchSupport: If a branch name was specified
 
748
            but colocated branches are not supported.
685
749
        :return: The URL the branch in this bzrdir references if it is a
686
750
            reference branch, or None for regular branches.
687
751
        """
 
752
        if name is not None:
 
753
            raise errors.NoColocatedBranchSupport(self)
688
754
        return None
689
755
 
690
 
    def get_branch_transport(self, branch_format):
 
756
    def get_branch_transport(self, branch_format, name=None):
691
757
        """Get the transport for use by branch format in this BzrDir.
692
758
 
693
759
        Note that bzr dirs that do not support format strings will raise
788
854
        :param _transport: the transport this dir is based at.
789
855
        """
790
856
        self._format = _format
 
857
        # these are also under the more standard names of 
 
858
        # control_transport and user_transport
791
859
        self.transport = _transport.clone('.bzr')
792
860
        self.root_transport = _transport
793
861
        self._mode_check_done = False
 
862
        
 
863
    @property 
 
864
    def user_transport(self):
 
865
        return self.root_transport
 
866
        
 
867
    @property
 
868
    def control_transport(self):
 
869
        return self.transport
794
870
 
795
871
    def is_control_filename(self, filename):
796
872
        """True if filename is the name of a path which is reserved for bzrdir's.
871
947
        BzrDir._check_supported(format, _unsupported)
872
948
        return format.open(transport, _found=True)
873
949
 
874
 
    def open_branch(self, unsupported=False, ignore_fallbacks=False):
 
950
    def open_branch(self, name=None, unsupported=False,
 
951
                    ignore_fallbacks=False):
875
952
        """Open the branch object at this BzrDir if one is present.
876
953
 
877
954
        If unsupported is True, then no longer supported branch formats can
924
1001
                raise errors.NotBranchError(path=url)
925
1002
            a_transport = new_t
926
1003
 
927
 
    def _get_tree_branch(self):
 
1004
    def _get_tree_branch(self, name=None):
928
1005
        """Return the branch and tree, if any, for this bzrdir.
929
1006
 
 
1007
        :param name: Name of colocated branch to open.
 
1008
 
930
1009
        Return None for tree if not present or inaccessible.
931
1010
        Raise NotBranchError if no branch is present.
932
1011
        :return: (tree, branch)
935
1014
            tree = self.open_workingtree()
936
1015
        except (errors.NoWorkingTree, errors.NotLocalUrl):
937
1016
            tree = None
938
 
            branch = self.open_branch()
 
1017
            branch = self.open_branch(name=name)
939
1018
        else:
940
 
            branch = tree.branch
 
1019
            if name is not None:
 
1020
                branch = self.open_branch(name=name)
 
1021
            else:
 
1022
                branch = tree.branch
941
1023
        return tree, branch
942
1024
 
943
1025
    @classmethod
1015
1097
        """
1016
1098
        raise NotImplementedError(self.open_workingtree)
1017
1099
 
1018
 
    def has_branch(self):
 
1100
    def has_branch(self, name=None):
1019
1101
        """Tell if this bzrdir contains a branch.
1020
1102
 
1021
1103
        Note: if you're going to open the branch, you should just go ahead
1023
1105
        branch and discards it, and that's somewhat expensive.)
1024
1106
        """
1025
1107
        try:
1026
 
            self.open_branch()
 
1108
            self.open_branch(name)
1027
1109
            return True
1028
1110
        except errors.NotBranchError:
1029
1111
            return False
1164
1246
        repository_policy = result.determine_repository_policy(
1165
1247
            force_new_repo, stacked_branch_url, require_stacking=stacked)
1166
1248
        result_repo, is_new_repo = repository_policy.acquire_repository()
1167
 
        if is_new_repo and revision_id is not None and not stacked:
 
1249
        is_stacked = stacked or (len(result_repo._fallback_repositories) != 0)
 
1250
        if is_new_repo and revision_id is not None and not is_stacked:
1168
1251
            fetch_spec = graph.PendingAncestryResult(
1169
1252
                [revision_id], source_repository)
1170
1253
        else:
1303
1386
        self.create_hook(hooks.HookPoint('pre_open',
1304
1387
            "Invoked before attempting to open a BzrDir with the transport "
1305
1388
            "that the open will use.", (1, 14), None))
 
1389
        self.create_hook(hooks.HookPoint('post_repo_init',
 
1390
            "Invoked after a repository has been initialized. "
 
1391
            "post_repo_init is called with a "
 
1392
            "bzrlib.bzrdir.RepoInitHookParams.",
 
1393
            (2, 2), None))
1306
1394
 
1307
1395
# install the default hooks
1308
1396
BzrDir.hooks = BzrDirHooks()
1309
1397
 
1310
1398
 
 
1399
class RepoInitHookParams(object):
 
1400
    """Object holding parameters passed to *_repo_init hooks.
 
1401
 
 
1402
    There are 4 fields that hooks may wish to access:
 
1403
 
 
1404
    :ivar repository: Repository created
 
1405
    :ivar format: Repository format
 
1406
    :ivar bzrdir: The bzrdir for the repository
 
1407
    :ivar shared: The repository is shared
 
1408
    """
 
1409
 
 
1410
    def __init__(self, repository, format, a_bzrdir, shared):
 
1411
        """Create a group of RepoInitHook parameters.
 
1412
 
 
1413
        :param repository: Repository created
 
1414
        :param format: Repository format
 
1415
        :param bzrdir: The bzrdir for the repository
 
1416
        :param shared: The repository is shared
 
1417
        """
 
1418
        self.repository = repository
 
1419
        self.format = format
 
1420
        self.bzrdir = a_bzrdir
 
1421
        self.shared = shared
 
1422
 
 
1423
    def __eq__(self, other):
 
1424
        return self.__dict__ == other.__dict__
 
1425
 
 
1426
    def __repr__(self):
 
1427
        if self.repository:
 
1428
            return "<%s for %s>" % (self.__class__.__name__,
 
1429
                self.repository)
 
1430
        else:
 
1431
            return "<%s for %s>" % (self.__class__.__name__,
 
1432
                self.bzrdir)
 
1433
 
 
1434
 
1311
1435
class BzrDirPreSplitOut(BzrDir):
1312
1436
    """A common class for the all-in-one formats."""
1313
1437
 
1352
1476
            tree.clone(result)
1353
1477
        return result
1354
1478
 
1355
 
    def create_branch(self):
 
1479
    def create_branch(self, name=None):
1356
1480
        """See BzrDir.create_branch."""
1357
 
        return self._format.get_branch_format().initialize(self)
 
1481
        return self._format.get_branch_format().initialize(self, name=name)
1358
1482
 
1359
 
    def destroy_branch(self):
 
1483
    def destroy_branch(self, name=None):
1360
1484
        """See BzrDir.destroy_branch."""
1361
1485
        raise errors.UnsupportedOperation(self.destroy_branch, self)
1362
1486
 
1418
1542
        raise errors.UnsupportedOperation(self.destroy_workingtree_metadata,
1419
1543
                                          self)
1420
1544
 
1421
 
    def get_branch_transport(self, branch_format):
 
1545
    def get_branch_transport(self, branch_format, name=None):
1422
1546
        """See BzrDir.get_branch_transport()."""
 
1547
        if name is not None:
 
1548
            raise errors.NoColocatedBranchSupport(self)
1423
1549
        if branch_format is None:
1424
1550
            return self.transport
1425
1551
        try:
1458
1584
            format = BzrDirFormat.get_default_format()
1459
1585
        return not isinstance(self._format, format.__class__)
1460
1586
 
1461
 
    def open_branch(self, unsupported=False, ignore_fallbacks=False):
 
1587
    def open_branch(self, name=None, unsupported=False,
 
1588
                    ignore_fallbacks=False):
1462
1589
        """See BzrDir.open_branch."""
1463
1590
        from bzrlib.branch import BzrBranchFormat4
1464
1591
        format = BzrBranchFormat4()
1465
1592
        self._check_supported(format, unsupported)
1466
 
        return format.open(self, _found=True)
 
1593
        return format.open(self, name, _found=True)
1467
1594
 
1468
1595
    def sprout(self, url, revision_id=None, force_new_repo=False,
1469
1596
               possible_transports=None, accelerator_tree=None,
1530
1657
    This is a deprecated format and may be removed after sept 2006.
1531
1658
    """
1532
1659
 
 
1660
    def has_workingtree(self):
 
1661
        """See BzrDir.has_workingtree."""
 
1662
        return True
 
1663
    
1533
1664
    def open_repository(self):
1534
1665
        """See BzrDir.open_repository."""
1535
1666
        from bzrlib.repofmt.weaverepo import RepositoryFormat5
1551
1682
    This is a deprecated format and may be removed after sept 2006.
1552
1683
    """
1553
1684
 
 
1685
    def has_workingtree(self):
 
1686
        """See BzrDir.has_workingtree."""
 
1687
        return True
 
1688
    
1554
1689
    def open_repository(self):
1555
1690
        """See BzrDir.open_repository."""
1556
1691
        from bzrlib.repofmt.weaverepo import RepositoryFormat6
1578
1713
        """See BzrDir.can_convert_format()."""
1579
1714
        return True
1580
1715
 
1581
 
    def create_branch(self):
 
1716
    def create_branch(self, name=None):
1582
1717
        """See BzrDir.create_branch."""
1583
 
        return self._format.get_branch_format().initialize(self)
 
1718
        return self._format.get_branch_format().initialize(self, name=name)
1584
1719
 
1585
 
    def destroy_branch(self):
 
1720
    def destroy_branch(self, name=None):
1586
1721
        """See BzrDir.create_branch."""
 
1722
        if name is not None:
 
1723
            raise errors.NoColocatedBranchSupport(self)
1587
1724
        self.transport.delete_tree('branch')
1588
1725
 
1589
1726
    def create_repository(self, shared=False):
1612
1749
    def destroy_workingtree_metadata(self):
1613
1750
        self.transport.delete_tree('checkout')
1614
1751
 
1615
 
    def find_branch_format(self):
 
1752
    def find_branch_format(self, name=None):
1616
1753
        """Find the branch 'format' for this bzrdir.
1617
1754
 
1618
1755
        This might be a synthetic object for e.g. RemoteBranch and SVN.
1619
1756
        """
1620
1757
        from bzrlib.branch import BranchFormat
1621
 
        return BranchFormat.find_format(self)
 
1758
        return BranchFormat.find_format(self, name=name)
1622
1759
 
1623
1760
    def _get_mkdir_mode(self):
1624
1761
        """Figure out the mode to use when creating a bzrdir subdir."""
1626
1763
                                     lockable_files.TransportLock)
1627
1764
        return temp_control._dir_mode
1628
1765
 
1629
 
    def get_branch_reference(self):
 
1766
    def get_branch_reference(self, name=None):
1630
1767
        """See BzrDir.get_branch_reference()."""
1631
1768
        from bzrlib.branch import BranchFormat
1632
 
        format = BranchFormat.find_format(self)
1633
 
        return format.get_reference(self)
 
1769
        format = BranchFormat.find_format(self, name=name)
 
1770
        return format.get_reference(self, name=name)
1634
1771
 
1635
 
    def get_branch_transport(self, branch_format):
 
1772
    def get_branch_transport(self, branch_format, name=None):
1636
1773
        """See BzrDir.get_branch_transport()."""
 
1774
        if name is not None:
 
1775
            raise errors.NoColocatedBranchSupport(self)
1637
1776
        # XXX: this shouldn't implicitly create the directory if it's just
1638
1777
        # promising to get a transport -- mbp 20090727
1639
1778
        if branch_format is None:
1676
1815
            pass
1677
1816
        return self.transport.clone('checkout')
1678
1817
 
 
1818
    def has_workingtree(self):
 
1819
        """Tell if this bzrdir contains a working tree.
 
1820
 
 
1821
        This will still raise an exception if the bzrdir has a workingtree that
 
1822
        is remote & inaccessible.
 
1823
 
 
1824
        Note: if you're going to open the working tree, you should just go
 
1825
        ahead and try, and not ask permission first.
 
1826
        """
 
1827
        from bzrlib.workingtree import WorkingTreeFormat
 
1828
        try:
 
1829
            WorkingTreeFormat.find_format(self)
 
1830
        except errors.NoWorkingTree:
 
1831
            return False
 
1832
        return True
 
1833
 
1679
1834
    def needs_format_conversion(self, format=None):
1680
1835
        """See BzrDir.needs_format_conversion()."""
1681
1836
        if format is None:
1694
1849
                return True
1695
1850
        except errors.NoRepositoryPresent:
1696
1851
            pass
1697
 
        try:
1698
 
            if not isinstance(self.open_branch()._format,
 
1852
        for branch in self.list_branches():
 
1853
            if not isinstance(branch._format,
1699
1854
                              format.get_branch_format().__class__):
1700
1855
                # the branch needs an upgrade.
1701
1856
                return True
1702
 
        except errors.NotBranchError:
1703
 
            pass
1704
1857
        try:
1705
1858
            my_wt = self.open_workingtree(recommend_upgrade=False)
1706
1859
            if not isinstance(my_wt._format,
1711
1864
            pass
1712
1865
        return False
1713
1866
 
1714
 
    def open_branch(self, unsupported=False, ignore_fallbacks=False):
 
1867
    def open_branch(self, name=None, unsupported=False,
 
1868
                    ignore_fallbacks=False):
1715
1869
        """See BzrDir.open_branch."""
1716
 
        format = self.find_branch_format()
 
1870
        format = self.find_branch_format(name=name)
1717
1871
        self._check_supported(format, unsupported)
1718
 
        return format.open(self, _found=True, ignore_fallbacks=ignore_fallbacks)
 
1872
        return format.open(self, name=name,
 
1873
            _found=True, ignore_fallbacks=ignore_fallbacks)
1719
1874
 
1720
1875
    def open_repository(self, unsupported=False):
1721
1876
        """See BzrDir.open_repository."""
1753
1908
    Once a format is deprecated, just deprecate the initialize and open
1754
1909
    methods on the format class. Do not deprecate the object, as the
1755
1910
    object will be created every system load.
 
1911
 
 
1912
    :cvar colocated_branches: Whether this formats supports colocated branches.
1756
1913
    """
1757
1914
 
1758
1915
    _default_format = None
1775
1932
 
1776
1933
    _lock_file_name = 'branch-lock'
1777
1934
 
 
1935
    colocated_branches = False
 
1936
    """Whether co-located branches are supported for this control dir format.
 
1937
    """
 
1938
 
1778
1939
    # _lock_class must be set in subclasses to the lock type, typ.
1779
1940
    # TransportLock or LockDir
1780
1941
 
1797
1958
    def probe_transport(klass, transport):
1798
1959
        """Return the .bzrdir style format present in a directory."""
1799
1960
        try:
1800
 
            format_string = transport.get(".bzr/branch-format").read()
 
1961
            format_string = transport.get_bytes(".bzr/branch-format")
1801
1962
        except errors.NoSuchFile:
1802
1963
            raise errors.NotBranchError(path=transport.base)
1803
 
 
1804
1964
        try:
1805
1965
            return klass._formats[format_string]
1806
1966
        except KeyError:
2579
2739
    def convert(self, to_convert, pb):
2580
2740
        """See Converter.convert()."""
2581
2741
        self.bzrdir = to_convert
2582
 
        self.pb = pb
2583
 
        self.pb.note('starting upgrade from format 4 to 5')
2584
 
        if isinstance(self.bzrdir.transport, local.LocalTransport):
2585
 
            self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
2586
 
        self._convert_to_weaves()
2587
 
        return BzrDir.open(self.bzrdir.root_transport.base)
 
2742
        if pb is not None:
 
2743
            warnings.warn("pb parameter to convert() is deprecated")
 
2744
        self.pb = ui.ui_factory.nested_progress_bar()
 
2745
        try:
 
2746
            ui.ui_factory.note('starting upgrade from format 4 to 5')
 
2747
            if isinstance(self.bzrdir.transport, local.LocalTransport):
 
2748
                self.bzrdir.get_workingtree_transport(None).delete('stat-cache')
 
2749
            self._convert_to_weaves()
 
2750
            return BzrDir.open(self.bzrdir.user_url)
 
2751
        finally:
 
2752
            self.pb.finished()
2588
2753
 
2589
2754
    def _convert_to_weaves(self):
2590
 
        self.pb.note('note: upgrade may be faster if all store files are ungzipped first')
 
2755
        ui.ui_factory.note('note: upgrade may be faster if all store files are ungzipped first')
2591
2756
        try:
2592
2757
            # TODO permissions
2593
2758
            stat = self.bzrdir.transport.stat('weaves')
2621
2786
        self.pb.clear()
2622
2787
        self._write_all_weaves()
2623
2788
        self._write_all_revs()
2624
 
        self.pb.note('upgraded to weaves:')
2625
 
        self.pb.note('  %6d revisions and inventories', len(self.revisions))
2626
 
        self.pb.note('  %6d revisions not present', len(self.absent_revisions))
2627
 
        self.pb.note('  %6d texts', self.text_count)
 
2789
        ui.ui_factory.note('upgraded to weaves:')
 
2790
        ui.ui_factory.note('  %6d revisions and inventories' % len(self.revisions))
 
2791
        ui.ui_factory.note('  %6d revisions not present' % len(self.absent_revisions))
 
2792
        ui.ui_factory.note('  %6d texts' % self.text_count)
2628
2793
        self._cleanup_spare_files_after_format4()
2629
2794
        self.branch._transport.put_bytes(
2630
2795
            'branch-format',
2698
2863
                       len(self.known_revisions))
2699
2864
        if not self.branch.repository.has_revision(rev_id):
2700
2865
            self.pb.clear()
2701
 
            self.pb.note('revision {%s} not present in branch; '
2702
 
                         'will be converted as a ghost',
 
2866
            ui.ui_factory.note('revision {%s} not present in branch; '
 
2867
                         'will be converted as a ghost' %
2703
2868
                         rev_id)
2704
2869
            self.absent_revisions.add(rev_id)
2705
2870
        else:
2710
2875
            self.revisions[rev_id] = rev
2711
2876
 
2712
2877
    def _load_old_inventory(self, rev_id):
2713
 
        old_inv_xml = self.branch.repository.inventory_store.get(rev_id).read()
 
2878
        f = self.branch.repository.inventory_store.get(rev_id)
 
2879
        try:
 
2880
            old_inv_xml = f.read()
 
2881
        finally:
 
2882
            f.close()
2714
2883
        inv = xml4.serializer_v4.read_inventory_from_string(old_inv_xml)
2715
2884
        inv.revision_id = rev_id
2716
2885
        rev = self.revisions[rev_id]
2772
2941
        previous_entries = dict((head, parent_candiate_entries[head]) for head
2773
2942
            in heads)
2774
2943
        self.snapshot_ie(previous_entries, ie, w, rev_id)
2775
 
        del ie.text_id
2776
2944
 
2777
2945
    def get_parent_map(self, revision_ids):
2778
2946
        """See graph.StackedParentsProvider.get_parent_map"""
2794
2962
                ie.revision = previous_ie.revision
2795
2963
                return
2796
2964
        if ie.has_text():
2797
 
            text = self.branch.repository._text_store.get(ie.text_id)
2798
 
            file_lines = text.readlines()
 
2965
            f = self.branch.repository._text_store.get(ie.text_id)
 
2966
            try:
 
2967
                file_lines = f.readlines()
 
2968
            finally:
 
2969
                f.close()
2799
2970
            w.add_lines(rev_id, previous_revisions, file_lines)
2800
2971
            self.text_count += 1
2801
2972
        else:
2831
3002
    def convert(self, to_convert, pb):
2832
3003
        """See Converter.convert()."""
2833
3004
        self.bzrdir = to_convert
2834
 
        self.pb = pb
2835
 
        self.pb.note('starting upgrade from format 5 to 6')
2836
 
        self._convert_to_prefixed()
2837
 
        return BzrDir.open(self.bzrdir.root_transport.base)
 
3005
        pb = ui.ui_factory.nested_progress_bar()
 
3006
        try:
 
3007
            ui.ui_factory.note('starting upgrade from format 5 to 6')
 
3008
            self._convert_to_prefixed()
 
3009
            return BzrDir.open(self.bzrdir.user_url)
 
3010
        finally:
 
3011
            pb.finished()
2838
3012
 
2839
3013
    def _convert_to_prefixed(self):
2840
3014
        from bzrlib.store import TransportStore
2841
3015
        self.bzrdir.transport.delete('branch-format')
2842
3016
        for store_name in ["weaves", "revision-store"]:
2843
 
            self.pb.note("adding prefixes to %s" % store_name)
 
3017
            ui.ui_factory.note("adding prefixes to %s" % store_name)
2844
3018
            store_transport = self.bzrdir.transport.clone(store_name)
2845
3019
            store = TransportStore(store_transport, prefixed=True)
2846
3020
            for urlfilename in store_transport.list_dir('.'):
2873
3047
        from bzrlib.repofmt.weaverepo import RepositoryFormat7
2874
3048
        from bzrlib.branch import BzrBranchFormat5
2875
3049
        self.bzrdir = to_convert
2876
 
        self.pb = pb
 
3050
        self.pb = ui.ui_factory.nested_progress_bar()
2877
3051
        self.count = 0
2878
3052
        self.total = 20 # the steps we know about
2879
3053
        self.garbage_inventories = []
2880
3054
        self.dir_mode = self.bzrdir._get_dir_mode()
2881
3055
        self.file_mode = self.bzrdir._get_file_mode()
2882
3056
 
2883
 
        self.pb.note('starting upgrade from format 6 to metadir')
 
3057
        ui.ui_factory.note('starting upgrade from format 6 to metadir')
2884
3058
        self.bzrdir.transport.put_bytes(
2885
3059
                'branch-format',
2886
3060
                "Converting to format 6",
2936
3110
        else:
2937
3111
            has_checkout = True
2938
3112
        if not has_checkout:
2939
 
            self.pb.note('No working tree.')
 
3113
            ui.ui_factory.note('No working tree.')
2940
3114
            # If some checkout files are there, we may as well get rid of them.
2941
3115
            for name, mandatory in checkout_files:
2942
3116
                if name in bzrcontents:
2959
3133
            'branch-format',
2960
3134
            BzrDirMetaFormat1().get_format_string(),
2961
3135
            mode=self.file_mode)
2962
 
        return BzrDir.open(self.bzrdir.root_transport.base)
 
3136
        self.pb.finished()
 
3137
        return BzrDir.open(self.bzrdir.user_url)
2963
3138
 
2964
3139
    def make_lock(self, name):
2965
3140
        """Make a lock for the new control dir name."""
3000
3175
    def convert(self, to_convert, pb):
3001
3176
        """See Converter.convert()."""
3002
3177
        self.bzrdir = to_convert
3003
 
        self.pb = pb
 
3178
        self.pb = ui.ui_factory.nested_progress_bar()
3004
3179
        self.count = 0
3005
3180
        self.total = 1
3006
3181
        self.step('checking repository format')
3011
3186
        else:
3012
3187
            if not isinstance(repo._format, self.target_format.repository_format.__class__):
3013
3188
                from bzrlib.repository import CopyConverter
3014
 
                self.pb.note('starting repository conversion')
 
3189
                ui.ui_factory.note('starting repository conversion')
3015
3190
                converter = CopyConverter(self.target_format.repository_format)
3016
3191
                converter.convert(repo, pb)
3017
 
        try:
3018
 
            branch = self.bzrdir.open_branch()
3019
 
        except errors.NotBranchError:
3020
 
            pass
3021
 
        else:
 
3192
        for branch in self.bzrdir.list_branches():
3022
3193
            # TODO: conversions of Branch and Tree should be done by
3023
3194
            # InterXFormat lookups/some sort of registry.
3024
3195
            # Avoid circular imports
3039
3210
                      new is _mod_branch.BzrBranchFormat8):
3040
3211
                    branch_converter = _mod_branch.Converter7to8()
3041
3212
                else:
3042
 
                    raise errors.BadConversionTarget("No converter", new)
 
3213
                    raise errors.BadConversionTarget("No converter", new,
 
3214
                        branch._format)
3043
3215
                branch_converter.convert(branch)
3044
3216
                branch = self.bzrdir.open_branch()
3045
3217
                old = branch._format.__class__
3065
3237
                isinstance(self.target_format.workingtree_format,
3066
3238
                    workingtree_4.WorkingTreeFormat6)):
3067
3239
                workingtree_4.Converter4or5to6().convert(tree)
 
3240
        self.pb.finished()
3068
3241
        return to_convert
3069
3242
 
3070
3243
 
3077
3250
 
3078
3251
    def __init__(self):
3079
3252
        BzrDirMetaFormat1.__init__(self)
 
3253
        # XXX: It's a bit ugly that the network name is here, because we'd
 
3254
        # like to believe that format objects are stateless or at least
 
3255
        # immutable,  However, we do at least avoid mutating the name after
 
3256
        # it's returned.  See <https://bugs.launchpad.net/bzr/+bug/504102>
3080
3257
        self._network_name = None
3081
3258
 
 
3259
    def __repr__(self):
 
3260
        return "%s(_network_name=%r)" % (self.__class__.__name__,
 
3261
            self._network_name)
 
3262
 
3082
3263
    def get_format_description(self):
 
3264
        if self._network_name:
 
3265
            real_format = network_format_registry.get(self._network_name)
 
3266
            return 'Remote: ' + real_format.get_format_description()
3083
3267
        return 'bzr remote bzrdir'
3084
3268
 
3085
3269
    def get_format_string(self):
3218
3402
        args.append(self._serialize_NoneString(repo_format_name))
3219
3403
        args.append(self._serialize_NoneTrueFalse(make_working_trees))
3220
3404
        args.append(self._serialize_NoneTrueFalse(shared_repo))
3221
 
        if self._network_name is None:
3222
 
            self._network_name = \
 
3405
        request_network_name = self._network_name or \
3223
3406
            BzrDirFormat.get_default_format().network_name()
3224
3407
        try:
3225
3408
            response = client.call('BzrDirFormat.initialize_ex_1.16',
3226
 
                self.network_name(), path, *args)
 
3409
                request_network_name, path, *args)
3227
3410
        except errors.UnknownSmartMethod:
3228
3411
            client._medium._remember_remote_is_before((1,16))
3229
3412
            local_dir_format = BzrDirMetaFormat1()
3479
3662
                experimental_pairs.append((key, help))
3480
3663
            else:
3481
3664
                output += wrapped(key, help, info)
3482
 
        output += "\nSee ``bzr help formats`` for more about storage formats."
 
3665
        output += "\nSee :doc:`formats-help` for more about storage formats."
3483
3666
        other_output = ""
3484
3667
        if len(experimental_pairs) > 0:
3485
3668
            other_output += "Experimental formats are shown below.\n\n"
3498
3681
            other_output += \
3499
3682
                "\nNo deprecated formats are available.\n\n"
3500
3683
        other_output += \
3501
 
            "\nSee ``bzr help formats`` for more about storage formats."
 
3684
                "\nSee :doc:`formats-help` for more about storage formats."
3502
3685
 
3503
3686
        if topic == 'other-formats':
3504
3687
            return other_output
3538
3721
            try:
3539
3722
                stack_on = urlutils.rebase_url(self._stack_on,
3540
3723
                    self._stack_on_pwd,
3541
 
                    branch.bzrdir.root_transport.base)
 
3724
                    branch.user_url)
3542
3725
            except errors.InvalidRebaseURLs:
3543
3726
                stack_on = self._get_full_stack_on()
3544
3727
        try:
3548
3731
            if self._require_stacking:
3549
3732
                raise
3550
3733
 
 
3734
    def requires_stacking(self):
 
3735
        """Return True if this policy requires stacking."""
 
3736
        return self._stack_on is not None and self._require_stacking
 
3737
 
3551
3738
    def _get_full_stack_on(self):
3552
3739
        """Get a fully-qualified URL for the stack_on location."""
3553
3740
        if self._stack_on is None:
3669
3856
format_registry.register('weave', BzrDirFormat6,
3670
3857
    'Pre-0.8 format.  Slower than knit and does not'
3671
3858
    ' support checkouts or shared repositories.',
 
3859
    hidden=True,
3672
3860
    deprecated=True)
3673
3861
format_registry.register_metadir('metaweave',
3674
3862
    'bzrlib.repofmt.weaverepo.RepositoryFormat7',
3675
3863
    'Transitional format in 0.8.  Slower than knit.',
3676
3864
    branch_format='bzrlib.branch.BzrBranchFormat5',
3677
3865
    tree_format='bzrlib.workingtree.WorkingTreeFormat3',
 
3866
    hidden=True,
3678
3867
    deprecated=True)
3679
3868
format_registry.register_metadir('knit',
3680
3869
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
3681
3870
    'Format using knits.  Recommended for interoperation with bzr <= 0.14.',
3682
3871
    branch_format='bzrlib.branch.BzrBranchFormat5',
3683
3872
    tree_format='bzrlib.workingtree.WorkingTreeFormat3',
 
3873
    hidden=True,
3684
3874
    deprecated=True)
3685
3875
format_registry.register_metadir('dirstate',
3686
3876
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
3690
3880
    # this uses bzrlib.workingtree.WorkingTreeFormat4 because importing
3691
3881
    # directly from workingtree_4 triggers a circular import.
3692
3882
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3883
    hidden=True,
3693
3884
    deprecated=True)
3694
3885
format_registry.register_metadir('dirstate-tags',
3695
3886
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
3698
3889
        ' Incompatible with bzr < 0.15.',
3699
3890
    branch_format='bzrlib.branch.BzrBranchFormat6',
3700
3891
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3892
    hidden=True,
3701
3893
    deprecated=True)
3702
3894
format_registry.register_metadir('rich-root',
3703
3895
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit4',
3705
3897
        ' bzr < 1.0.',
3706
3898
    branch_format='bzrlib.branch.BzrBranchFormat6',
3707
3899
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3900
    hidden=True,
3708
3901
    deprecated=True)
3709
3902
format_registry.register_metadir('dirstate-with-subtree',
3710
3903
    'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
3721
3914
    help='New in 0.92: Pack-based format with data compatible with '
3722
3915
        'dirstate-tags format repositories. Interoperates with '
3723
3916
        'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
3724
 
        'Previously called knitpack-experimental.  '
3725
 
        'For more information, see '
3726
 
        'http://doc.bazaar-vcs.org/latest/developers/packrepo.html.',
 
3917
        ,
3727
3918
    branch_format='bzrlib.branch.BzrBranchFormat6',
3728
3919
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3729
3920
    )
3732
3923
    help='New in 0.92: Pack-based format with data compatible with '
3733
3924
        'dirstate-with-subtree format repositories. Interoperates with '
3734
3925
        'bzr repositories before 0.92 but cannot be read by bzr < 0.92. '
3735
 
        'Previously called knitpack-experimental.  '
3736
 
        'For more information, see '
3737
 
        'http://doc.bazaar-vcs.org/latest/developers/packrepo.html.',
 
3926
        ,
3738
3927
    branch_format='bzrlib.branch.BzrBranchFormat6',
3739
3928
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
3740
3929
    hidden=True,
3746
3935
         '(needed for bzr-svn and bzr-git).',
3747
3936
    branch_format='bzrlib.branch.BzrBranchFormat6',
3748
3937
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3938
    hidden=True,
3749
3939
    )
3750
3940
format_registry.register_metadir('1.6',
3751
3941
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5',
3754
3944
         'not present locally.',
3755
3945
    branch_format='bzrlib.branch.BzrBranchFormat7',
3756
3946
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3947
    hidden=True,
3757
3948
    )
3758
3949
format_registry.register_metadir('1.6.1-rich-root',
3759
3950
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack5RichRoot',
3761
3952
         '(needed for bzr-svn and bzr-git).',
3762
3953
    branch_format='bzrlib.branch.BzrBranchFormat7',
3763
3954
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3955
    hidden=True,
3764
3956
    )
3765
3957
format_registry.register_metadir('1.9',
3766
3958
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
3769
3961
         'performance for most operations.',
3770
3962
    branch_format='bzrlib.branch.BzrBranchFormat7',
3771
3963
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3964
    hidden=True,
3772
3965
    )
3773
3966
format_registry.register_metadir('1.9-rich-root',
3774
3967
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6RichRoot',
3776
3969
         '(needed for bzr-svn and bzr-git).',
3777
3970
    branch_format='bzrlib.branch.BzrBranchFormat7',
3778
3971
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
3972
    hidden=True,
3779
3973
    )
3780
3974
format_registry.register_metadir('1.14',
3781
3975
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack6',
3797
3991
        'to and from rich-root-pack (and anything compatible with '
3798
3992
        'rich-root-pack) format repositories. Repositories and branches in '
3799
3993
        'this format can only be read by bzr.dev. Please read '
3800
 
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
 
3994
        'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
3801
3995
        'before use.',
3802
3996
    branch_format='bzrlib.branch.BzrBranchFormat7',
3803
3997
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
3804
3998
    experimental=True,
3805
3999
    alias=True,
 
4000
    hidden=True,
3806
4001
    )
3807
4002
format_registry.register_metadir('development-subtree',
3808
4003
    'bzrlib.repofmt.pack_repo.RepositoryFormatPackDevelopment2Subtree',
3810
4005
        'from pack-0.92-subtree (and anything compatible with '
3811
4006
        'pack-0.92-subtree) format repositories. Repositories and branches in '
3812
4007
        'this format can only be read by bzr.dev. Please read '
3813
 
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
 
4008
        'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
3814
4009
        'before use.',
3815
4010
    branch_format='bzrlib.branch.BzrBranchFormat7',
3816
4011
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
3817
4012
    experimental=True,
 
4013
    hidden=True,
3818
4014
    alias=False, # Restore to being an alias when an actual development subtree format is added
3819
4015
                 # This current non-alias status is simply because we did not introduce a
3820
4016
                 # chk based subtree format.
3825
4021
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormatCHK1',
3826
4022
    help='pack-1.9 with 255-way hashed CHK inv, group compress, rich roots '
3827
4023
        'Please read '
3828
 
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
 
4024
        'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
3829
4025
        'before use.',
3830
4026
    branch_format='bzrlib.branch.BzrBranchFormat7',
3831
4027
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
3837
4033
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormatCHK2',
3838
4034
    help='pack-1.9 with 255-way hashed CHK inv, bencode revision, group compress, '
3839
4035
        'rich roots. Please read '
3840
 
        'http://doc.bazaar-vcs.org/latest/developers/development-repo.html '
 
4036
        'http://doc.bazaar.canonical.com/latest/developers/development-repo.html '
3841
4037
        'before use.',
3842
4038
    branch_format='bzrlib.branch.BzrBranchFormat7',
3843
4039
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
3860
4056
# The following format should be an alias for the rich root equivalent 
3861
4057
# of the default format
3862
4058
format_registry.register_metadir('default-rich-root',
3863
 
    'bzrlib.repofmt.pack_repo.RepositoryFormatKnitPack4',
3864
 
    help='Default format, rich root variant. (needed for bzr-svn and bzr-git).',
3865
 
    branch_format='bzrlib.branch.BzrBranchFormat6',
3866
 
    tree_format='bzrlib.workingtree.WorkingTreeFormat4',
 
4059
    'bzrlib.repofmt.groupcompress_repo.RepositoryFormat2a',
 
4060
    branch_format='bzrlib.branch.BzrBranchFormat7',
 
4061
    tree_format='bzrlib.workingtree.WorkingTreeFormat6',
3867
4062
    alias=True,
3868
 
    )
 
4063
    hidden=True,
 
4064
    help='Same as 2a.')
 
4065
 
3869
4066
# The current format that is made on 'bzr init'.
3870
 
format_registry.set_default('pack-0.92')
 
4067
format_registry.set_default('2a')